diff --git a/3rd-dependencies/listDeps.sh b/3rd-dependencies/listDeps.sh old mode 100755 new mode 100644 diff --git a/MIGRATION.md b/MIGRATION.md index eacce864d..f9d9fff51 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -7,3 +7,14 @@ - hawkbit.server.email.support has changed to hawkbit.server.ui.links.support - hawkbit.server.email.request.account has changed to hawkbit.server.ui.links.requestAccount - hawkbit.server.im.login.url has changed to hawkbit.server.ui.links.userManagement + +### REST API model changes for clients +- ENTITYPagedList classes have been removed; generic PagedList used instead (e.g. PagedList instead of TargetPagedList). +- ENTITYsrest classes have been removed; List used instead (e.g. List instead of TargetsRest) + +### Renamed api annotations +- Annotation `org.eclipse.hawkbit.rest.resource.EnableRestResources` have changed to `org.eclipse.hawkbit.mgmt.annotation.EnableMgmtApi` +- Annotation `org.eclipse.hawkbit.ddi.resource.EnableDirectDeviceApi` have changed to `org.eclipse.hawkbit.ddi.annotation.EnableDdiApi` + +### Renamed maven modules +- Module hawkbit-mgmt-api-client have changed to hawkbit-example-mgmt-simulator \ No newline at end of file diff --git a/README.md b/README.md index fb649633b..1a33e0c60 100644 --- a/README.md +++ b/README.md @@ -14,10 +14,15 @@ 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 -We are not providing an off the shelf installation ready hawkBit update server. However, we recommend to check out the [Example Application](examples/hawkbit-example-app) for a runtime ready Spring Boot based update server that is empowered by hawkBit. +We are not providing an off the shelf installation ready hawkBit update server. However, we recommend to check out the [Example Application](examples/hawkbit-example-app) for a runtime ready Spring Boot based update server that is empowered by hawkBit. In addition we have [guide](https://github.com/eclipse/hawkbit/wiki/Run-hawkBit) for setting up a complete landscape. #### Clone and build hawkBit ``` @@ -36,9 +41,9 @@ $ java -jar ./examples/hawkbit-example-app/target/hawkbit-example-app-#version#. $ java -jar ./examples/hawkbit-device-simulator/target/hawkbit-device-simulator-#version#.jar ``` #### Generate Getting Started data -[Example Management API Client](examples/hawkbit-mgmt-api-client) +[Example Management API Client](examples/hawkbit-example-mgmt-simulator) ``` -$ java -jar ./examples/hawkbit-mgmt-api-client/target/hawkbit-mgmt-api-client-#version#.jar +$ java -jar ./examples/hawkbit-example-mgmt-simulator/target/hawkbit-example-mgmt-simulator-#version#.jar ``` # Releases and Roadmap @@ -47,21 +52,27 @@ $ java -jar ./examples/hawkbit-mgmt-api-client/target/hawkbit-mgmt-api-client-#v * The master branch contains future development towards 0.2. We are currently focusing on: * Rollout Management for large scale rollouts. * Clustering capabilities for the update server. - * Upgrade of Spring Boot and Vaadin depedencies. + * Upgrade of Spring Boot and Vaadin dependencies. * And of course tons of usability improvements and bug fixes. # Modules -`hawkbit-core` : core elements. -`hawkbit-security-core` : core security elements. -`hawkbit-security-integration` : security integration elements to integrate security into hawkbit. -`hawkbit-artifact-repository-mongo` : artifact repository implementation to mongoDB. -`hawkbit-autoconfigure` : spring-boot auto-configuration. -`hawkbit-dmf-api` : API for the Device Management Integration. -`hawkbit-dmf-amqp` : AMQP endpoint implementation for the DMF API. -`hawkbit-repository` : repository implemenation based on SQL for all meta-data. -`hawkbit-http-security` : implementation for security filters for HTTP. -`hawkbit-rest-api` : API classes for the REST Management API. -`hawkbit-rest-resource` : HTTP REST endpoints for the Management and the Direct Device API. -`hawkbit-ui` : Vaadin UI. -`hawkbit-cache-redis` : spring cache manager configuration and implementation with redis, distributed cache and distributed events. +* `examples` : hawkBit examples +* `hawkbit-artifact-repository-mongo` : Artifact repository implementation to mongoDB. +* `hawkbit-autoconfigure` : Spring-boot auto-configuration. +* `hawkbit-cache-redis` : Spring cache manager configuration and implementation with redis, distributed cache and distributed events. +* `hawkbit-core` : Core elements for internal interfaces and utility classes. +* `hawkbit-ddi-api` : The hawkBit DDI API. +* `hawkbit-ddi-dl-api` : The hawkBit DDI Download API. +* `hawkbit-ddi-resource` : Implementation of the hawkBit DDI API +* `hawkbit-dmf-amqp` : AMQP endpoint implementation for the DMF API. +* `hawkbit-dmf-api` : API for the Device Management Integration. +* `hawkbit-http-security` : Implementation for security filters for HTTP. +* `hawkbit-mgmt-api` : The hawkBit Management API +* `hawkbit-mgmt-resource` : Implementation of the hawkBit Management API +* `hawkbit-repository` : Repository implementation based on SQL for all meta-data. +* `hawkbit-rest-core` : Core elements for the rest modules. +* `hawkbit-security-core` : Core security elements. +* `hawkbit-security-integration` : Security integration elements to integrate security into hawkBit. +* `hawkbit-test-report` : Test reports +* `hawkbit-ui` : Vaadin UI. \ No newline at end of file diff --git a/deployHawkBitSandbox.sh b/deployHawkBitSandbox.sh new file mode 100644 index 000000000..d774f4205 --- /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 --hawkbit.url=hawkbit.eu-gb.mybluemix.net +cd hawkbit-device-simulator/target/ +cf push +cd ../../.. diff --git a/examples/README.md b/examples/README.md index 3ad5ecf66..0aebbc117 100644 --- a/examples/README.md +++ b/examples/README.md @@ -1,7 +1,12 @@ # Examples -Example projects that show how hawkBit can be used to create, run or access an hawkBit empowered update server. +Example projects that show how _hawkBit_ can be used to create, run or access an _hawkBit_ empowered update server. + +- `hawkbit-custom-theme-example` : Example for a customized theme for Management UI. +- `hawkbit-device-simulator` : Simulates device software updates, leveraging the hawkBit device integration options. +- `hawkbit-example-app` : Allows you to run the Spring Boot hawkBit app. Includes all _hawkBit_ interfaces, i.e. DDI, DMF, Mgmt-API, Mgmt-UI. +- `hawkbit-example-core-feign-client` : Core resources for the client examples. +- `hawkbit-example-ddi-feign-client` : Example _hawkBit_ DDI client based on the _hawkBit_ DDI API. +- `hawkbit-example-mgmt-feign-client` : Example _hawkBit_ Management client based on the _hawkBit_ Management API +- `hawkbit-example-mgmt-simulator` : Example client simulation for the _hawkBit_ Management API based on Spring Boot and the hawkbit-example-mgmt-feign-client. -`hawkbit-device-simulator` : Simulates device software updates, leveraging the hawkBit device integration options. -`hawkbit-example-app` : Allows you to run a Spring Boot and hawkBit based update server. -`hawkbit-mgmt-api-client` : Example client for the hawkBit management API. diff --git a/examples/hawkbit-custom-theme-example/README.md b/examples/hawkbit-custom-theme-example/README.md new file mode 100644 index 000000000..5a6a571c8 --- /dev/null +++ b/examples/hawkbit-custom-theme-example/README.md @@ -0,0 +1 @@ +Theme customization example for Eclipse hawkBit. See wiki for the theme customization guide. \ No newline at end of file diff --git a/examples/hawkbit-custom-theme-example/pom.xml b/examples/hawkbit-custom-theme-example/pom.xml new file mode 100644 index 000000000..7caa99ba2 --- /dev/null +++ b/examples/hawkbit-custom-theme-example/pom.xml @@ -0,0 +1,112 @@ + + + 4.0.0 + + org.eclipse.hawkbit + hawkbit-examples-parent + 0.2.0-SNAPSHOT + + hawkbit-custom-theme-example + hawkBit :: Custom Theme Example App + + + + + com.vaadin + vaadin-maven-plugin + ${vaadin.plugin.version} + + src/main/resources + + + + + update-theme + compile-theme + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + repackage + + + ${baseDir} + false + org.eclipse.hawkbit.app.Start + JAR + + + + + + + + + + + org.eclipse.hawkbit + hawkbit-autoconfigure + ${project.version} + + + org.eclipse.hawkbit + hawkbit-ui + ${project.version} + + + org.eclipse.hawkbit + hawkbit-security-integration + ${project.version} + + + org.eclipse.hawkbit + hawkbit-http-security + ${project.version} + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter + + + org.springframework.boot + spring-boot-starter-logging + + + + + org.springframework.boot + spring-boot-starter-log4j2 + + + org.springframework.security + spring-security-aspects + + + com.h2database + h2 + + + + diff --git a/examples/hawkbit-custom-theme-example/src/main/java/org/eclipse/hawkbit/app/MyLoginUI.java b/examples/hawkbit-custom-theme-example/src/main/java/org/eclipse/hawkbit/app/MyLoginUI.java new file mode 100644 index 000000000..c31086a70 --- /dev/null +++ b/examples/hawkbit-custom-theme-example/src/main/java/org/eclipse/hawkbit/app/MyLoginUI.java @@ -0,0 +1,34 @@ +/** + * 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.app; + +import org.eclipse.hawkbit.ui.login.HawkbitLoginUI; +import org.eclipse.hawkbit.ui.themes.HawkbitTheme; + +import com.vaadin.annotations.Theme; +import com.vaadin.annotations.Title; +import com.vaadin.spring.annotation.SpringUI; + +/** + * Example hawkBit login UI implementation. + * + * A {@link SpringUI} annotated class must be present in the classpath for the + * login path. The easiest way to get an hawkBit login UI running is to extend + * the {@link HawkbitLoginUI} and to annotated it with {@link SpringUI} as in + * this example to the defined {@link HawkbitTheme#LOGIN_UI_PATH}. + * + */ +@SpringUI(path = HawkbitTheme.LOGIN_UI_PATH) +@Title("hawkBit Theme example") +@Theme(value = "exampletheme") +public class MyLoginUI extends HawkbitLoginUI { + + private static final long serialVersionUID = 1L; + +} diff --git a/examples/hawkbit-custom-theme-example/src/main/java/org/eclipse/hawkbit/app/MyUI.java b/examples/hawkbit-custom-theme-example/src/main/java/org/eclipse/hawkbit/app/MyUI.java new file mode 100644 index 000000000..5ef632d10 --- /dev/null +++ b/examples/hawkbit-custom-theme-example/src/main/java/org/eclipse/hawkbit/app/MyUI.java @@ -0,0 +1,45 @@ +package org.eclipse.hawkbit.app; +/** + * 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 + */ + +import org.eclipse.hawkbit.ui.HawkbitUI; +import org.eclipse.hawkbit.ui.UIEventProvider; +import org.eclipse.hawkbit.ui.push.DelayedEventBusPushStrategy; +import org.springframework.beans.factory.annotation.Autowired; + +import com.google.common.eventbus.EventBus; +import com.vaadin.annotations.Push; +import com.vaadin.annotations.Theme; +import com.vaadin.annotations.Title; +import com.vaadin.shared.communication.PushMode; +import com.vaadin.shared.ui.ui.Transport; +import com.vaadin.spring.annotation.SpringUI; + +/** + * Example hawkBit UI implementation. + * + * A {@link SpringUI} annotated class must be present in the classpath. The + * easiest way to get an hawkBit UI running is to extend the {@link HawkbitUI} + * and to annotated it with {@link SpringUI} as in this example. + * + */ +@SpringUI +@Push(value = PushMode.AUTOMATIC, transport = Transport.WEBSOCKET) +@Title("hawkBit Theme example") +@Theme(value = "exampletheme") +public class MyUI extends HawkbitUI { + + private static final long serialVersionUID = 1L; + + @Autowired + public MyUI(final EventBus systemEventBus, final org.vaadin.spring.events.EventBus.SessionEventBus eventBus, + final UIEventProvider provider) { + super(new DelayedEventBusPushStrategy(eventBus, systemEventBus, provider)); + } +} diff --git a/examples/hawkbit-custom-theme-example/src/main/java/org/eclipse/hawkbit/app/Start.java b/examples/hawkbit-custom-theme-example/src/main/java/org/eclipse/hawkbit/app/Start.java new file mode 100644 index 000000000..abf2740fa --- /dev/null +++ b/examples/hawkbit-custom-theme-example/src/main/java/org/eclipse/hawkbit/app/Start.java @@ -0,0 +1,39 @@ +package org.eclipse.hawkbit.app; +/** + * 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 + */ + +import org.eclipse.hawkbit.RepositoryApplicationConfiguration; +import org.eclipse.hawkbit.autoconfigure.security.EnableHawkbitManagedSecurityConfiguration; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Import; + +/** + * A {@link SpringBootApplication} annotated class with a main method to start. + * The minimal configuration for the stand alone hawkBit server. + * + */ +@SpringBootApplication +@Import({ RepositoryApplicationConfiguration.class }) +@EnableHawkbitManagedSecurityConfiguration +// Exception squid:S1118 - Spring boot standard behavior +@SuppressWarnings({ "squid:S1118" }) +public class Start { + /** + * Main method to start the spring-boot application. + * + * @param args + * the VM arguments. + */ + // Exception squid:S2095 - Spring boot standard behavior + @SuppressWarnings({ "squid:S2095" }) + public static void main(final String[] args) { + SpringApplication.run(Start.class, args); + } +} diff --git a/examples/hawkbit-custom-theme-example/src/main/resources/VAADIN/themes/exampletheme/.gitignore b/examples/hawkbit-custom-theme-example/src/main/resources/VAADIN/themes/exampletheme/.gitignore new file mode 100644 index 000000000..1cdd02b74 --- /dev/null +++ b/examples/hawkbit-custom-theme-example/src/main/resources/VAADIN/themes/exampletheme/.gitignore @@ -0,0 +1,2 @@ +/addons.scss +/styles.css diff --git a/examples/hawkbit-custom-theme-example/src/main/resources/VAADIN/themes/exampletheme/customstyles/examplevariables.scss b/examples/hawkbit-custom-theme-example/src/main/resources/VAADIN/themes/exampletheme/customstyles/examplevariables.scss new file mode 100644 index 000000000..6bf201f9c --- /dev/null +++ b/examples/hawkbit-custom-theme-example/src/main/resources/VAADIN/themes/exampletheme/customstyles/examplevariables.scss @@ -0,0 +1,24 @@ +/** + * 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 + */ + +$dark-gray: #848484; + +//Example color change +$hawkbit-primary-color: $dark-gray; +$hawkbit-primary-color-light: #D8D8D8; +$app-selection-item-selection-color: $dark-gray; +$app-focus-color: $dark-gray; +$app-selection-color: $dark-gray; +$tag-text-color: $dark-gray; +$tab-sheet-caption-color: $dark-gray; +$table-details-tab-font-color: $dark-gray; +$widget-caption-color: $dark-gray; +$accordion-action-history-title-color: $dark-gray; +$menu-title-bg-color: $dark-gray; +$button-icon-color: $dark-gray; \ No newline at end of file diff --git a/examples/hawkbit-custom-theme-example/src/main/resources/VAADIN/themes/exampletheme/images/profile-pic-57px.jpg b/examples/hawkbit-custom-theme-example/src/main/resources/VAADIN/themes/exampletheme/images/profile-pic-57px.jpg new file mode 100644 index 000000000..d730cb5f6 Binary files /dev/null and b/examples/hawkbit-custom-theme-example/src/main/resources/VAADIN/themes/exampletheme/images/profile-pic-57px.jpg differ diff --git a/examples/hawkbit-custom-theme-example/src/main/resources/VAADIN/themes/exampletheme/layouts/footer.html b/examples/hawkbit-custom-theme-example/src/main/resources/VAADIN/themes/exampletheme/layouts/footer.html new file mode 100644 index 000000000..f2ac781ba --- /dev/null +++ b/examples/hawkbit-custom-theme-example/src/main/resources/VAADIN/themes/exampletheme/layouts/footer.html @@ -0,0 +1,29 @@ + + + + + diff --git a/examples/hawkbit-custom-theme-example/src/main/resources/VAADIN/themes/exampletheme/styles.scss b/examples/hawkbit-custom-theme-example/src/main/resources/VAADIN/themes/exampletheme/styles.scss new file mode 100644 index 000000000..4b3f29814 --- /dev/null +++ b/examples/hawkbit-custom-theme-example/src/main/resources/VAADIN/themes/exampletheme/styles.scss @@ -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 + */ + +@import "../hawkbit/customstyles/hawkbitvariables"; +@import "customstyles/examplevariables"; +@import "../hawkbit/hawkbittheme"; +@import "addons"; + +// This file prefixes all rules with the theme name to avoid causing conflicts with other themes. +.exampletheme { + @include addons; + @include hawkbittheme; +} diff --git a/examples/hawkbit-custom-theme-example/src/main/resources/application.properties b/examples/hawkbit-custom-theme-example/src/main/resources/application.properties new file mode 100644 index 000000000..3ffb51bd0 --- /dev/null +++ b/examples/hawkbit-custom-theme-example/src/main/resources/application.properties @@ -0,0 +1,16 @@ +# +# 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 +# + +# UI demo account +hawkbit.server.ui.demo.password=admin +hawkbit.server.ui.demo.user=admin +hawkbit.server.ui.demo.tenant=DEFAULT + +# UI help links +hawkbit.server.ui.links.documentation.root=https://github.com/eclipse/hawkbit 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 new file mode 100644 index 000000000..51a43ace6 --- /dev/null +++ b/examples/hawkbit-device-simulator/cf/manifest.yml @@ -0,0 +1,22 @@ +# +# 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: 1024M + instances: 1 + buildpack: https://github.com/cloudfoundry/java-buildpack + path: ${project.build.finalName}.jar + services: + - dmf-rabbit + env: + SPRING_PROFILES_ACTIVE: cloud,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..1b1bc5fdc 100644 --- a/examples/hawkbit-device-simulator/pom.xml +++ b/examples/hawkbit-device-simulator/pom.xml @@ -1,4 +1,3 @@ - - 4.0.0 @@ -19,7 +19,7 @@ hawkbit-device-simulator - hawkBit :: Device Simulator + hawkBit-example :: Device Simulator Device Management Federation API based simulator @@ -42,6 +42,19 @@ + + + src/main/resources + + + cf + true + ${project.build.directory} + + manifest.yml + + + @@ -69,16 +82,26 @@ org.springframework.boot spring-boot-starter - - - org.springframework.boot - spring-boot-starter-logging - - + - org.springframework.boot - spring-boot-starter-log4j2 + org.apache.logging.log4j + log4j-api + + + + org.slf4j + jul-to-slf4j + + + + org.slf4j + jcl-over-slf4j + + + + org.slf4j + log4j-over-slf4j com.vaadin @@ -120,13 +143,17 @@ spring-boot-configuration-processor true + + org.apache.httpcomponents + httpclient + com.vaadin vaadin-bom - 7.6.3 + ${vaadin.version} pom import diff --git a/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/AbstractSimulatedDevice.java b/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/AbstractSimulatedDevice.java index 474acb6c4..890f43367 100644 --- a/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/AbstractSimulatedDevice.java +++ b/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/AbstractSimulatedDevice.java @@ -8,6 +8,8 @@ */ package org.eclipse.hawkbit.simulator; +import org.eclipse.hawkbit.simulator.UpdateStatus.ResponseStatus; + /** * The bean of a simulated device which can be stored in the * {@link DeviceSimulatorRepository} or shown in the UI. @@ -22,16 +24,15 @@ public abstract class AbstractSimulatedDevice { private Status status; private double progress; private String swversion = "unknown"; - private ResponseStatus responseStatus = ResponseStatus.SUCCESSFUL; + private UpdateStatus updateStatus = new UpdateStatus(ResponseStatus.SUCCESSFUL, "Simulation complete!"); private Protocol protocol = Protocol.DMF_AMQP; + private String targetSecurityToken; private int nextPollCounterSec; /** * Enum definition of the protocol to be used for the simulated device. * - * @author Michael Hirsch - * */ public enum Protocol { /** @@ -69,24 +70,6 @@ public abstract class AbstractSimulatedDevice { ERROR; } - /** - * The status to response to the hawkbit update server if an simulated - * update process should be respond with successful or failure update. - * - * @author Michael Hirsch - * - */ - public enum ResponseStatus { - /** - * updated has been successful and response the successful update. - */ - SUCCESSFUL, - /** - * updated has been not successful and response the error update. - */ - ERROR; - } - /** * empty constructor. */ @@ -158,12 +141,12 @@ public abstract class AbstractSimulatedDevice { this.swversion = swversion; } - public ResponseStatus getResponseStatus() { - return responseStatus; + public UpdateStatus getUpdateStatus() { + return updateStatus; } - public void setResponseStatus(final ResponseStatus responseStatus) { - this.responseStatus = responseStatus; + public void setUpdateStatus(final UpdateStatus updateStatus) { + this.updateStatus = updateStatus; } public Protocol getProtocol() { @@ -177,4 +160,13 @@ public abstract class AbstractSimulatedDevice { public void setNextPollCounterSec(final int nextPollDelayInSec) { this.nextPollCounterSec = nextPollDelayInSec; } + + public String getTargetSecurityToken() { + return targetSecurityToken; + } + + public void setTargetSecurityToken(final String targetSecurityToken) { + this.targetSecurityToken = targetSecurityToken; + } + } diff --git a/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/DDISimulatedDevice.java b/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/DDISimulatedDevice.java index b58d3a413..26e613dd9 100644 --- a/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/DDISimulatedDevice.java +++ b/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/DDISimulatedDevice.java @@ -8,8 +8,6 @@ */ package org.eclipse.hawkbit.simulator; -import java.util.concurrent.ScheduledExecutorService; - import org.eclipse.hawkbit.simulator.http.ControllerResource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -18,7 +16,7 @@ import com.jayway.jsonpath.JsonPath; import com.jayway.jsonpath.PathNotFoundException; /** - * @author Michael Hirsch + * A simulated device using the DDI API of the hawkBit update server. * */ public class DDISimulatedDevice extends AbstractSimulatedDevice { @@ -26,12 +24,12 @@ public class DDISimulatedDevice extends AbstractSimulatedDevice { private static final Logger LOGGER = LoggerFactory.getLogger(DDISimulatedDevice.class); private final int pollDelaySec; - private final ScheduledExecutorService pollthreadpool; private final ControllerResource controllerResource; + private final DeviceSimulatorUpdater deviceUpdater; + private volatile boolean removed; private volatile Long currentActionId; - private final DeviceSimulatorUpdater deviceUpdater; /** * @param id @@ -42,18 +40,14 @@ public class DDISimulatedDevice extends AbstractSimulatedDevice { * the delay of the poll interval in sec * @param controllerResource * the http controller resource - * @param pollthreadpool - * the threadpool for polling endpoint * @param deviceUpdater * the service to update devices */ public DDISimulatedDevice(final String id, final String tenant, final int pollDelaySec, - final ControllerResource controllerResource, final ScheduledExecutorService pollthreadpool, - final DeviceSimulatorUpdater deviceUpdater) { + final ControllerResource controllerResource, final DeviceSimulatorUpdater deviceUpdater) { super(id, tenant, Protocol.DDI_HTTP); this.pollDelaySec = pollDelaySec; this.controllerResource = controllerResource; - this.pollthreadpool = pollthreadpool; this.deviceUpdater = deviceUpdater; setNextPollCounterSec(pollDelaySec); } @@ -76,27 +70,12 @@ public class DDISimulatedDevice extends AbstractSimulatedDevice { final String basePollJson = controllerResource.get(getTenant(), getId()); try { final String href = JsonPath.parse(basePollJson).read("_links.deploymentBase.href"); - final long actionId = Long.parseLong(href.substring(href.lastIndexOf("/") + 1, href.indexOf("?"))); + final long actionId = Long.parseLong(href.substring(href.lastIndexOf('/') + 1, href.indexOf('?'))); if (currentActionId == null) { final String deploymentJson = controllerResource.getDeployment(getTenant(), getId(), actionId); final String swVersion = JsonPath.parse(deploymentJson).read("deployment.chunks[0].version"); currentActionId = actionId; - deviceUpdater.startUpdate(getTenant(), getId(), actionId, swVersion, (device, actionId1) -> { - switch (device.getResponseStatus()) { - case SUCCESSFUL: - controllerResource.postSuccessFeedback(getTenant(), getId(), - actionId1); - break; - case ERROR: - controllerResource.postErrorFeedback(getTenant(), getId(), - actionId1); - break; - default: - throw new IllegalStateException( - "simulated device has an unknown response status + " + device.getResponseStatus()); - } - currentActionId = null; - }); + startDdiUpdate(actionId, swVersion); } } catch (final PathNotFoundException e) { // href might not be in the json response, so ignore @@ -106,4 +85,21 @@ public class DDISimulatedDevice extends AbstractSimulatedDevice { } } + + private void startDdiUpdate(final long actionId, final String swVersion) { + deviceUpdater.startUpdate(getTenant(), getId(), actionId, swVersion, null, null, (device, actionId1) -> { + switch (device.getUpdateStatus().getResponseStatus()) { + case SUCCESSFUL: + controllerResource.postSuccessFeedback(getTenant(), getId(), actionId1); + break; + case ERROR: + controllerResource.postErrorFeedback(getTenant(), getId(), actionId1); + break; + default: + throw new IllegalStateException("simulated device has an unknown response status + " + + device.getUpdateStatus().getResponseStatus()); + } + currentActionId = null; + }); + } } diff --git a/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/DMFSimulatedDevice.java b/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/DMFSimulatedDevice.java index b9fdc827c..6b79a85b8 100644 --- a/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/DMFSimulatedDevice.java +++ b/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/DMFSimulatedDevice.java @@ -9,10 +9,7 @@ package org.eclipse.hawkbit.simulator; /** - * An simulated device using the DMF API of the hawkbit update server. - * - * @author Michael Hirsch - * + * A simulated device using the DMF API of the hawkBit update server. */ public class DMFSimulatedDevice extends AbstractSimulatedDevice { diff --git a/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/DeviceSimulator.java b/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/DeviceSimulator.java index 944ba1d07..370d6af62 100644 --- a/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/DeviceSimulator.java +++ b/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/DeviceSimulator.java @@ -21,8 +21,6 @@ import com.vaadin.spring.annotation.EnableVaadin; /** * The main-method to start the Spring-Boot application. * - * - * */ @SpringBootApplication @EnableVaadin @@ -46,6 +44,8 @@ public class DeviceSimulator { * @param args * the args */ + // Exception squid:S2095 - Spring boot standard behavior + @SuppressWarnings({ "squid:S2095" }) public static void main(final String[] args) { SpringApplication.run(DeviceSimulator.class, args); } 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..34c5f548e 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 @@ -8,32 +8,65 @@ */ package org.eclipse.hawkbit.simulator; +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.security.DigestOutputStream; +import java.security.KeyManagementException; +import java.security.KeyStoreException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; +import java.util.ArrayList; +import java.util.List; import java.util.Random; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.conn.ssl.SSLContextBuilder; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.eclipse.hawkbit.dmf.json.model.Artifact; +import org.eclipse.hawkbit.dmf.json.model.SoftwareModule; +import org.eclipse.hawkbit.simulator.AbstractSimulatedDevice.Protocol; +import org.eclipse.hawkbit.simulator.UpdateStatus.ResponseStatus; import org.eclipse.hawkbit.simulator.amqp.SpSenderService; import org.eclipse.hawkbit.simulator.event.InitUpdate; import org.eclipse.hawkbit.simulator.event.ProgressUpdate; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import com.google.common.eventbus.EventBus; +import com.google.common.io.BaseEncoding; +import com.google.common.io.ByteStreams; /** - * @author Michael Hirsch + * Update simulation handler. * */ @Service public class DeviceSimulatorUpdater { + private static final Logger LOGGER = LoggerFactory.getLogger(DeviceSimulatorUpdater.class); private static final ScheduledExecutorService threadPool = Executors.newScheduledThreadPool(4); @Autowired private SpSenderService spSenderService; + @Autowired + private SimulatedDeviceFactory deviceFactory; + @Autowired private EventBus eventbus; @@ -50,24 +83,43 @@ public class DeviceSimulatorUpdater { * @param actionId * the actionId from the hawkbit update server to start the * update. - * @param swVersion + * @param modules * the software module version from the hawkbit update server + * @param swVersion + * the software version as static value in case modules is null + * @param targetSecurityToken + * the target security token for download authentication * @param callback * the callback which gets called when the simulated update * process has been finished */ 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); + final List modules, final String targetSecurityToken, final UpdaterCallback callback) { + 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); + + if (modules == null || modules.isEmpty()) { + device.setSwversion(swVersion); + } else { + device.setSwversion(modules.stream().map(sm -> sm.getModuleVersion()).collect(Collectors.joining(", "))); + } + device.setTargetSecurityToken(targetSecurityToken); eventbus.post(new InitUpdate(device)); - threadPool.schedule(new DeviceSimulatorUpdateThread(device, spSenderService, actionId, eventbus, callback), - 2_000, TimeUnit.MILLISECONDS); + threadPool.schedule( + new DeviceSimulatorUpdateThread(device, spSenderService, actionId, eventbus, callback, modules), 2_000, + TimeUnit.MILLISECONDS); } private static final class DeviceSimulatorUpdateThread implements Runnable { + private static final int MINIMUM_TOKENLENGTH_FOR_HINT = 6; + private static final Random rndSleep = new SecureRandom(); private final AbstractSimulatedDevice device; @@ -75,38 +127,211 @@ public class DeviceSimulatorUpdater { private final long actionId; private final EventBus eventbus; private final UpdaterCallback callback; + private final List modules; private DeviceSimulatorUpdateThread(final AbstractSimulatedDevice device, final SpSenderService spSenderService, - final long actionId, final EventBus eventbus, final UpdaterCallback callback) { + final long actionId, final EventBus eventbus, final UpdaterCallback callback, + final List modules) { this.device = device; this.spSenderService = spSenderService; this.actionId = actionId; this.eventbus = eventbus; this.callback = callback; + this.modules = modules; } @Override public void run() { + if (device.getProgress() <= 0 && modules != null) { + device.setUpdateStatus(simulateDownloads(device.getTargetSecurityToken())); + if (isErrorResponse(device.getUpdateStatus())) { + callback.updateFinished(device, actionId); + eventbus.post(new ProgressUpdate(device)); + return; + } + // download is 80% of the game after all + device.setProgress(0.8); + } + final double newProgress = device.getProgress() + 0.2; device.setProgress(newProgress); if (newProgress < 1.0) { threadPool.schedule( - new DeviceSimulatorUpdateThread(device, spSenderService, actionId, eventbus, callback), + new DeviceSimulatorUpdateThread(device, spSenderService, actionId, eventbus, callback, modules), rndSleep.nextInt(5_000), TimeUnit.MILLISECONDS); } else { callback.updateFinished(device, actionId); } eventbus.post(new ProgressUpdate(device)); } + + private UpdateStatus simulateDownloads(final String targetToken) { + final List status = new ArrayList<>(); + + LOGGER.info("Simulate downloads for {}", device.getId()); + + modules.forEach(module -> module.getArtifacts() + .forEach(artifact -> handleArtifacts(targetToken, status, artifact))); + + final UpdateStatus result = new UpdateStatus(ResponseStatus.SUCCESSFUL); + result.getStatusMessages().add("Simulation complete!"); + status.forEach(download -> { + result.getStatusMessages().addAll(download.getStatusMessages()); + if (isErrorResponse(download)) { + result.setResponseStatus(ResponseStatus.ERROR); + } + }); + + LOGGER.info("Download simulations complete for {}", device.getId()); + + return result; + } + + private boolean isErrorResponse(final UpdateStatus status) { + if (status == null) { + return false; + } + + return ResponseStatus.ERROR.equals(status.getResponseStatus()); + } + + private static void handleArtifacts(final String targetToken, final List status, + final Artifact artifact) { + artifact.getUrls().entrySet().forEach(entry -> { + switch (entry.getKey()) { + case HTTP: + case HTTPS: + status.add(downloadUrl(entry.getValue(), targetToken, artifact.getHashes().getSha1(), + artifact.getSize())); + break; + default: + // not supported yet + break; + } + }); + } + + private static UpdateStatus downloadUrl(final String url, final String targetToken, final String sha1Hash, + final long size) { + LOGGER.debug("Downloading {} with token {}, expected sha1 hash {} and size {}", url, + hideTokenDetails(targetToken), sha1Hash, size); + + long overallread = 0; + try { + final CloseableHttpClient httpclient = createHttpClientThatAcceptsAllServerCerts(); + final HttpGet request = new HttpGet(url); + request.addHeader(HttpHeaders.AUTHORIZATION, "TargetToken " + targetToken); + + final String sha1HashResult; + try (final CloseableHttpResponse response = httpclient.execute(request)) { + + if (response.getStatusLine().getStatusCode() != HttpStatus.OK.value()) { + final String message = wrongStatusCode(url, response); + return new UpdateStatus(ResponseStatus.ERROR, message); + } + + if (response.getEntity().getContentLength() != size) { + final String message = wrongContentLength(url, size, response); + return new UpdateStatus(ResponseStatus.ERROR, message); + } + + final File tempFile = File.createTempFile("uploadFile", null); + final MessageDigest md = MessageDigest.getInstance("SHA-1"); + + try (final DigestOutputStream dos = new DigestOutputStream(new FileOutputStream(tempFile), md)) { + try (final BufferedOutputStream bdos = new BufferedOutputStream(dos)) { + try (BufferedInputStream bis = new BufferedInputStream(response.getEntity().getContent())) { + overallread = ByteStreams.copy(bis, bdos); + } + } + } finally { + if (tempFile != null && !tempFile.delete()) { + LOGGER.error("Could not delete temporary file: {}", tempFile); + } + } + + if (overallread != size) { + final String message = incompleteRead(url, size, overallread); + return new UpdateStatus(ResponseStatus.ERROR, message); + } + + sha1HashResult = BaseEncoding.base16().lowerCase().encode(md.digest()); + } + + if (!sha1Hash.equalsIgnoreCase(sha1HashResult)) { + final String message = wrongHash(url, sha1Hash, overallread, sha1HashResult); + return new UpdateStatus(ResponseStatus.ERROR, message); + } + + } catch (IOException | KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) { + LOGGER.error("Failed to download" + url, e); + return new UpdateStatus(ResponseStatus.ERROR, "Failed to download " + url + ": " + e.getMessage()); + } + + final String message = "Downloaded " + url + " (" + overallread + " bytes)"; + LOGGER.debug(message); + return new UpdateStatus(ResponseStatus.SUCCESSFUL, message); + } + + private static String hideTokenDetails(final String targetToken) { + if (targetToken == null) { + return ""; + } + + if (targetToken.isEmpty()) { + return ""; + } + + if (targetToken.length() <= MINIMUM_TOKENLENGTH_FOR_HINT) { + return "***"; + } + + return targetToken.substring(0, 2) + "***" + + targetToken.substring(targetToken.length() - 2, targetToken.length()); + } + + private static String wrongHash(final String url, final String sha1Hash, final long overallread, + final String sha1HashResult) { + final String message = "Download " + url + " failed with SHA1 hash missmatch (Expected: " + sha1Hash + + " but got: " + sha1HashResult + ") (" + overallread + " bytes)"; + LOGGER.error(message); + return message; + } + + private static String incompleteRead(final String url, final long size, final long overallread) { + final String message = "Download " + url + " is incomplete (Expected: " + size + " but got: " + overallread + + ")"; + LOGGER.error(message); + return message; + } + + private static String wrongContentLength(final String url, final long size, + final CloseableHttpResponse response) { + final String message = "Download " + url + " has wrong content length (Expected: " + size + " but got: " + + response.getEntity().getContentLength() + ")"; + LOGGER.error(message); + return message; + } + + private static String wrongStatusCode(final String url, final CloseableHttpResponse response) { + final String message = "Download " + url + " failed (" + response.getStatusLine().getStatusCode() + ")"; + LOGGER.error(message); + return message; + } + + private static CloseableHttpClient createHttpClientThatAcceptsAllServerCerts() + throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException { + final SSLContextBuilder builder = new SSLContextBuilder(); + builder.loadTrustMaterial(null, (chain, authType) -> true); + final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build()); + return HttpClients.custom().setSSLSocketFactory(sslsf).build(); + } } /** * Callback interface which is called when the simulated update process has * been finished and the caller of starting the simulated update process can - * send the result to the hawkbit update server back. - * - * @author Michael Hirsch - * + * send the result back to the hawkBit update server. */ @FunctionalInterface public interface UpdaterCallback { diff --git a/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/NextPollTimeController.java b/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/NextPollTimeController.java index 9c78ec65a..956d6d36a 100644 --- a/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/NextPollTimeController.java +++ b/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/NextPollTimeController.java @@ -26,9 +26,6 @@ import com.google.common.eventbus.EventBus; /** * Poll time trigger which executes the {@link DDISimulatedDevice#poll()} every * second. - * - * @author Michael Hirsch - * */ @Component public class NextPollTimeController { @@ -59,16 +56,15 @@ public class NextPollTimeController { devices.forEach(device -> { int nextCounter = device.getNextPollCounterSec() - 1; - if (nextCounter < 0) { - if (device instanceof DDISimulatedDevice) { - try { - pollService.submit(() -> ((DDISimulatedDevice) device).poll()); - } catch (final IllegalStateException e) { - LOGGER.trace("Device could not be polled", e); - } - nextCounter = ((DDISimulatedDevice) device).getPollDelaySec(); + if (nextCounter < 0 && device instanceof DDISimulatedDevice) { + try { + pollService.submit(() -> ((DDISimulatedDevice) device).poll()); + } catch (final IllegalStateException e) { + LOGGER.trace("Device could not be polled", e); } + nextCounter = ((DDISimulatedDevice) device).getPollDelaySec(); } + device.setNextPollCounterSec(nextCounter); }); eventBus.post(new NextPollCounterUpdate(devices)); diff --git a/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/SimulatedDeviceFactory.java b/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/SimulatedDeviceFactory.java index d3e080806..f29aad001 100644 --- a/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/SimulatedDeviceFactory.java +++ b/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/SimulatedDeviceFactory.java @@ -9,8 +9,6 @@ package org.eclipse.hawkbit.simulator; import java.net.URL; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; import org.eclipse.hawkbit.simulator.AbstractSimulatedDevice.Protocol; import org.eclipse.hawkbit.simulator.http.ControllerResource; @@ -24,15 +22,9 @@ import feign.Logger; /** * The simulated device factory to create either {@link DMFSimulatedDevice} or * {@link DDISimulatedDevice#}. - * - * @author Michael Hirsch - * */ @Service public class SimulatedDeviceFactory { - - private static final ScheduledExecutorService pollThreadPool = Executors.newScheduledThreadPool(4); - @Autowired private DeviceSimulatorUpdater deviceUpdater; @@ -47,7 +39,8 @@ public class SimulatedDeviceFactory { * the protocol of the device * @return the created simulated device */ - public AbstractSimulatedDevice createSimulatedDevice(final String id, final String tenant, final Protocol protocol) { + public AbstractSimulatedDevice createSimulatedDevice(final String id, final String tenant, + final Protocol protocol) { return createSimulatedDevice(id, tenant, protocol, 30, null, null); } @@ -80,7 +73,7 @@ public class SimulatedDeviceFactory { final ControllerResource controllerResource = Feign.builder().logger(new Logger.ErrorLogger()) .requestInterceptor(new GatewayTokenInterceptor(gatewayToken)).logLevel(Logger.Level.BASIC) .target(ControllerResource.class, baseEndpoint.toString()); - return new DDISimulatedDevice(id, tenant, pollDelaySec, controllerResource, pollThreadPool, deviceUpdater); + return new DDISimulatedDevice(id, tenant, pollDelaySec, controllerResource, deviceUpdater); default: throw new IllegalArgumentException("Protocol " + protocol + " unknown"); } 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..649d88477 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()) { @@ -86,7 +86,10 @@ public class SimulationController { final String deviceId = name + i; repository.add(deviceFactory.createSimulatedDevice(deviceId, tenant, protocol, pollDelay, new URL(endpoint), gatewayToken)); - spSenderService.createOrUpdateThing(tenant, deviceId); + + if (protocol == Protocol.DMF_AMQP) { + spSenderService.createOrUpdateThing(tenant, deviceId); + } } return ResponseEntity.ok("Updated " + amount + " DMF connected targets!"); 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..19367a9d4 --- /dev/null +++ b/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/SimulatorStartup.java @@ -0,0 +1,65 @@ +/** + * 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.MalformedURLException; +import java.net.URL; + +import org.eclipse.hawkbit.simulator.AbstractSimulatedDevice.Protocol; +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.boot.autoconfigure.condition.ConditionalOnProperty; +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 +@ConditionalOnProperty(prefix = "hawkbit.device.simulator", name = "autostart", matchIfMissing = true) +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 MalformedURLException e) { + LOGGER.error("Creation of simulated device at startup failed.", e); + } + + if (autostart.getApi() == Protocol.DMF_AMQP) { + spSenderService.createOrUpdateThing(autostart.getTenant(), deviceId); + } + } + }); + } + +} diff --git a/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/UpdateStatus.java b/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/UpdateStatus.java new file mode 100644 index 000000000..f4e1f75a7 --- /dev/null +++ b/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/UpdateStatus.java @@ -0,0 +1,78 @@ +/** + * 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; + +/** + * Update status of the simulated update. + * + */ +public class UpdateStatus { + private ResponseStatus responseStatus; + private List statusMessages; + + /** + * Constructor. + * + * @param responseStatus + * of the update + */ + public UpdateStatus(final ResponseStatus responseStatus) { + this.responseStatus = responseStatus; + } + + /** + * Constructor including status message. + * + * @param responseStatus + * of the update + * @param message + * of the update status + */ + public UpdateStatus(final ResponseStatus responseStatus, final String message) { + this(responseStatus); + statusMessages = new ArrayList<>(); + statusMessages.add(message); + } + + public ResponseStatus getResponseStatus() { + return responseStatus; + } + + public void setResponseStatus(final ResponseStatus responseStatus) { + this.responseStatus = responseStatus; + } + + public List getStatusMessages() { + if (statusMessages == null) { + statusMessages = new ArrayList<>(); + } + + return statusMessages; + } + + /** + * The status to response to the hawkBit update server if an simulated + * update process should be respond with successful or failure update. + */ + public enum ResponseStatus { + /** + * Update has been successful and response the successful update. + */ + SUCCESSFUL, + + /** + * Update has been not successful and response the error update. + */ + ERROR; + } + +} \ No newline at end of file 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/AmqpProperties.java b/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/amqp/AmqpProperties.java index f9e6ab23d..8fba3ac5b 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,31 @@ 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"; + + /** + * Message time to live (ttl) for the deadletter queue. Default ttl is 1 + * hour. + */ + private int deadLetterTtl = 60_000; public String getReceiverConnectorQueueFromSp() { return receiverConnectorQueueFromSp; @@ -71,4 +76,12 @@ public class AmqpProperties { public void setSenderForSpExchange(final String senderForSpExchange) { this.senderForSpExchange = senderForSpExchange; } + + public int getDeadLetterTtl() { + return deadLetterTtl; + } + + public void setDeadLetterTtl(final int deadLetterTtl) { + this.deadLetterTtl = deadLetterTtl; + } } 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..e06b2baf3 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 @@ -25,15 +25,14 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.messaging.handler.annotation.Header; import org.springframework.stereotype.Component; +import com.google.common.collect.Lists; + /** - * Handle all incoming Messages from SP. - * - * + * Handle all incoming Messages from hawkBit update server. * */ @Component public class SpReceiverService extends ReceiverService { - private static final Logger LOGGER = LoggerFactory.getLogger(ReceiverService.class); public static final String SOFTWARE_MODULE_FIRMWARE = "firmware"; @@ -44,17 +43,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 +50,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 @@ -103,6 +90,8 @@ public class SpReceiverService extends ReceiverService { if (eventHeader == null) { logAndThrowMessageError(message, "Event Topic is not set"); } + // Exception squid:S2259 - Checked before + @SuppressWarnings({ "squid:S2259" }) final EventTopic eventTopic = EventTopic.valueOf(eventHeader.toString()); switch (eventTopic) { case DOWNLOAD_AND_INSTALL: @@ -124,7 +113,7 @@ public class SpReceiverService extends ReceiverService { final Long actionId = convertMessage(message, Long.class); final SimulatedUpdate update = new SimulatedUpdate(tenant, thingId, actionId); - spSenderService.finishUpdateProcess(update, "Simulation canceled"); + spSenderService.finishUpdateProcess(update, Lists.newArrayList("Simulation canceled")); } private void handleUpdateProcess(final Message message, final String thingId) { @@ -135,19 +124,20 @@ public class SpReceiverService extends ReceiverService { final DownloadAndUpdateRequest downloadAndUpdateRequest = convertMessage(message, DownloadAndUpdateRequest.class); final Long actionId = downloadAndUpdateRequest.getActionId(); + final String targetSecurityToken = downloadAndUpdateRequest.getTargetSecurityToken(); - deviceUpdater.startUpdate(tenant, thingId, actionId, - downloadAndUpdateRequest.getSoftwareModules().get(0).getModuleVersion(), (device, actionId1) -> { - switch (device.getResponseStatus()) { + deviceUpdater.startUpdate(tenant, thingId, actionId, null, downloadAndUpdateRequest.getSoftwareModules(), + targetSecurityToken, (device, actionId1) -> { + switch (device.getUpdateStatus().getResponseStatus()) { case SUCCESSFUL: spSenderService.finishUpdateProcess( new SimulatedUpdate(device.getTenant(), device.getId(), actionId1), - "Simulation complete!"); + device.getUpdateStatus().getStatusMessages()); break; case ERROR: spSenderService.finishUpdateProcessWithError( new SimulatedUpdate(device.getTenant(), device.getId(), actionId1), - "Simulation complete with error!"); + device.getUpdateStatus().getStatusMessages()); break; default: break; diff --git a/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/amqp/SpSenderService.java b/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/amqp/SpSenderService.java index 2358bf013..1ced8c2fd 100644 --- a/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/amqp/SpSenderService.java +++ b/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/amqp/SpSenderService.java @@ -8,6 +8,7 @@ */ package org.eclipse.hawkbit.simulator.amqp; +import java.util.List; import java.util.Map; import org.eclipse.hawkbit.dmf.amqp.api.AmqpSettings; @@ -23,13 +24,9 @@ import org.springframework.amqp.core.MessageProperties; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import org.springframework.util.StringUtils; /** - * Sender service to send message to SP. - * - * - * + * Sender service to send messages to update server. */ @Service public class SpSenderService extends SenderService { @@ -59,8 +56,9 @@ public class SpSenderService extends SenderService { * @param description * a description according the update process */ - public void finishUpdateProcess(final SimulatedUpdate update, final String description) { - final Message updateResultMessage = createUpdateResultMessage(update, ActionStatus.FINISHED, description); + public void finishUpdateProcess(final SimulatedUpdate update, final List updateResultMessages) { + final Message updateResultMessage = createUpdateResultMessage(update, ActionStatus.FINISHED, + updateResultMessages); sendMessage(spExchange, updateResultMessage); } @@ -72,9 +70,9 @@ public class SpSenderService extends SenderService { * @param messageDescription * a description according the update process */ - public void finishUpdateProcessWithError(final SimulatedUpdate update, final String messageDescription) { - sendErrorgMessage(update, messageDescription); - LOGGER.debug("Update process finished with error \"{}\" reported by thing {}", messageDescription, + public void finishUpdateProcessWithError(final SimulatedUpdate update, final List updateResultMessages) { + sendErrorgMessage(update, updateResultMessages); + LOGGER.debug("Update process finished with error \"{}\" reported by thing {}", updateResultMessages, update.getThingId()); } @@ -88,8 +86,8 @@ public class SpSenderService extends SenderService { * @param actionId * the ID of the action for the error message */ - public void sendErrorMessage(final String tenant, final String messageDescription, final Long actionId) { - final Message message = createActionStatusMessage(tenant, ActionStatus.ERROR, messageDescription, actionId); + public void sendErrorMessage(final String tenant, final List updateResultMessages, final Long actionId) { + final Message message = createActionStatusMessage(tenant, ActionStatus.ERROR, updateResultMessages, actionId); sendMessage(spExchange, message); } @@ -101,8 +99,8 @@ public class SpSenderService extends SenderService { * @param warningMessage * a warning description */ - public void sendWarningMessage(final SimulatedUpdate update, final String warningMessage) { - final Message message = createActionStatusMessage(update, warningMessage, ActionStatus.WARNING); + public void sendWarningMessage(final SimulatedUpdate update, final List updateResultMessages) { + final Message message = createActionStatusMessage(update, updateResultMessages, ActionStatus.WARNING); sendMessage(spExchange, message); } @@ -119,8 +117,8 @@ public class SpSenderService extends SenderService { * the cached value */ public void sendActionStatusMessage(final String tenant, final ActionStatus actionStatus, - final String actionMessage, final Long actionId) { - final Message message = createActionStatusMessage(tenant, actionStatus, actionMessage, actionId); + final List updateResultMessages, final Long actionId) { + final Message message = createActionStatusMessage(tenant, actionStatus, updateResultMessages, actionId); sendMessage(message); } @@ -162,11 +160,11 @@ public class SpSenderService extends SenderService { * * @param context * the current context - * @param messageDescription - * a description according the update process + * @param updateResultMessages + * a list of descriptions according the update process */ - private void sendErrorgMessage(final SimulatedUpdate update, final String messageDescription) { - final Message message = createActionStatusMessage(update, messageDescription, ActionStatus.ERROR); + private void sendErrorgMessage(final SimulatedUpdate update, final List updateResultMessages) { + final Message message = createActionStatusMessage(update, updateResultMessages, ActionStatus.ERROR); sendMessage(spExchange, message); } @@ -183,7 +181,7 @@ public class SpSenderService extends SenderService { * the cacheValue value */ private Message createActionStatusMessage(final String tenant, final ActionStatus actionStatus, - final String actionMessage, final Long actionId) { + final List updateResultMessages, final Long actionId) { final MessageProperties messageProperties = new MessageProperties(); final Map headers = messageProperties.getHeaders(); final ActionUpdateStatus actionUpdateStatus = new ActionUpdateStatus(); @@ -192,15 +190,14 @@ public class SpSenderService extends SenderService { headers.put(MessageHeaderKey.TENANT, tenant); headers.put(MessageHeaderKey.TOPIC, EventTopic.UPDATE_ACTION_STATUS.name()); headers.put(MessageHeaderKey.CONTENT_TYPE, MessageProperties.CONTENT_TYPE_JSON); - if (!StringUtils.isEmpty(actionMessage)) { - actionUpdateStatus.getMessage().add(actionMessage); - } + actionUpdateStatus.getMessage().addAll(updateResultMessages); + actionUpdateStatus.setActionId(actionId); return convertMessage(actionUpdateStatus, messageProperties); } private Message createUpdateResultMessage(final SimulatedUpdate cacheValue, final ActionStatus actionStatus, - final String updateResultMessage) { + final List updateResultMessages) { final MessageProperties messageProperties = new MessageProperties(); final Map headers = messageProperties.getHeaders(); final ActionUpdateStatus actionUpdateStatus = new ActionUpdateStatus(); @@ -209,14 +206,14 @@ public class SpSenderService extends SenderService { headers.put(MessageHeaderKey.TENANT, cacheValue.getTenant()); headers.put(MessageHeaderKey.TOPIC, EventTopic.UPDATE_ACTION_STATUS.name()); headers.put(MessageHeaderKey.CONTENT_TYPE, MessageProperties.CONTENT_TYPE_JSON); - actionUpdateStatus.getMessage().add(updateResultMessage); + actionUpdateStatus.getMessage().addAll(updateResultMessages); actionUpdateStatus.setActionId(cacheValue.getActionId()); return convertMessage(actionUpdateStatus, messageProperties); } - private Message createActionStatusMessage(final SimulatedUpdate update, final String messageDescription, + private Message createActionStatusMessage(final SimulatedUpdate update, final List updateResultMessages, final ActionStatus status) { - return createActionStatusMessage(update.getTenant(), status, messageDescription, update.getActionId()); + return createActionStatusMessage(update.getTenant(), status, updateResultMessages, update.getActionId()); } } diff --git a/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/event/ProgressUpdate.java b/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/event/ProgressUpdate.java index 3e34a0fa1..6c18e61ac 100644 --- a/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/event/ProgressUpdate.java +++ b/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/event/ProgressUpdate.java @@ -13,8 +13,6 @@ import org.eclipse.hawkbit.simulator.AbstractSimulatedDevice; /** * Event definition object which is published if the simulated device updated * its update progress. - * - * @author Michael Hirsch * */ public class ProgressUpdate { diff --git a/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/ui/SimulatorView.java b/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/ui/SimulatorView.java index e1d6bd15b..4834bece9 100644 --- a/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/ui/SimulatorView.java +++ b/examples/hawkbit-device-simulator/src/main/java/org/eclipse/hawkbit/simulator/ui/SimulatorView.java @@ -8,21 +8,19 @@ */ package org.eclipse.hawkbit.simulator.ui; -import java.net.URL; import java.util.List; import java.util.Locale; import org.eclipse.hawkbit.simulator.AbstractSimulatedDevice; import org.eclipse.hawkbit.simulator.AbstractSimulatedDevice.Protocol; -import org.eclipse.hawkbit.simulator.AbstractSimulatedDevice.ResponseStatus; import org.eclipse.hawkbit.simulator.AbstractSimulatedDevice.Status; import org.eclipse.hawkbit.simulator.DeviceSimulatorRepository; import org.eclipse.hawkbit.simulator.SimulatedDeviceFactory; +import org.eclipse.hawkbit.simulator.UpdateStatus.ResponseStatus; import org.eclipse.hawkbit.simulator.amqp.SpSenderService; import org.eclipse.hawkbit.simulator.event.InitUpdate; import org.eclipse.hawkbit.simulator.event.NextPollCounterUpdate; import org.eclipse.hawkbit.simulator.event.ProgressUpdate; -import org.eclipse.hawkbit.simulator.ui.GenerateDialog.GenerateDialogCallback; import org.springframework.beans.factory.annotation.Autowired; import com.google.common.collect.Lists; @@ -52,13 +50,29 @@ import com.vaadin.ui.renderers.ProgressBarRenderer; * Vaadin view which allows to generate devices through the DMF API and show the * current simulated devices in a grid with their current status and update * progress. - * - * @author Michael Hirsch * */ @SpringView(name = "") +// The inheritance comes from Vaadin +@SuppressWarnings("squid:MaximumInheritanceDepth") public class SimulatorView extends VerticalLayout implements View { + private static final String NEXT_POLL_COUNTER_SEC_COL = "nextPollCounterSec"; + + private static final String RESPONSE_STATUS_COL = "updateStatus"; + + private static final String PROTOCOL_COL = "protocol"; + + private static final String TENANT_COL = "tenant"; + + private static final String PROGRESS_COL = "progress"; + + private static final String SWVERSION_COL = "swversion"; + + private static final String STATUS_COL = "status"; + + private static final String ID_COL = "id"; + private static final long serialVersionUID = 1L; @Autowired @@ -79,6 +93,7 @@ public class SimulatorView extends VerticalLayout implements View { private BeanContainer beanContainer; + @SuppressWarnings("unchecked") @Override public void enter(final ViewChangeEvent event) { eventbus.register(this); @@ -91,7 +106,7 @@ public class SimulatorView extends VerticalLayout implements View { createToolbar(); beanContainer = new BeanContainer<>(AbstractSimulatedDevice.class); - beanContainer.setBeanIdProperty("id"); + beanContainer.setBeanIdProperty(ID_COL); grid.setSizeFull(); grid.setCellStyleGenerator(new CellStyleGenerator() { @@ -100,38 +115,37 @@ public class SimulatorView extends VerticalLayout implements View { @Override public String getStyle(final CellReference cellReference) { - return cellReference.getPropertyId().equals("status") ? "centeralign" : null; + return cellReference.getPropertyId().equals(STATUS_COL) ? "centeralign" : null; } }); grid.setSelectionMode(SelectionMode.NONE); grid.setContainerDataSource(beanContainer); - grid.appendHeaderRow().getCell("responseStatus").setComponent(responseComboBox); - grid.setColumnOrder("id", "status", "swversion", "progress", "tenant", "protocol", "responseStatus", - "nextPollCounterSec"); + grid.appendHeaderRow().getCell(RESPONSE_STATUS_COL).setComponent(responseComboBox); + grid.setColumnOrder(ID_COL, STATUS_COL, SWVERSION_COL, PROGRESS_COL, TENANT_COL, PROTOCOL_COL, + RESPONSE_STATUS_COL, NEXT_POLL_COUNTER_SEC_COL); // header widths - grid.getColumn("status").setMaximumWidth(80); - grid.getColumn("protocol").setMaximumWidth(180); - grid.getColumn("responseStatus").setMaximumWidth(240); - grid.getColumn("nextPollCounterSec").setMaximumWidth(210); + grid.getColumn(STATUS_COL).setMaximumWidth(80); + grid.getColumn(PROTOCOL_COL).setMaximumWidth(180); + grid.getColumn(RESPONSE_STATUS_COL).setMaximumWidth(240); + grid.getColumn(NEXT_POLL_COUNTER_SEC_COL).setMaximumWidth(210); - grid.getColumn("nextPollCounterSec").setHeaderCaption("Next Poll in (sec)"); - grid.getColumn("swversion").setHeaderCaption("SW Version"); - grid.getColumn("responseStatus").setHeaderCaption("Response Update Status"); - grid.getColumn("progress").setRenderer(new ProgressBarRenderer()); - grid.getColumn("protocol").setConverter(createProtocolConverter()); - grid.getColumn("status").setRenderer(new HtmlRenderer(), createStatusConverter()); - grid.removeColumn("tenant"); + grid.getColumn(NEXT_POLL_COUNTER_SEC_COL).setHeaderCaption("Next Poll in (sec)"); + grid.getColumn(SWVERSION_COL).setHeaderCaption("SW Version"); + grid.getColumn(RESPONSE_STATUS_COL).setHeaderCaption("Response Update Status"); + grid.getColumn(PROGRESS_COL).setRenderer(new ProgressBarRenderer()); + grid.getColumn(PROTOCOL_COL).setConverter(createProtocolConverter()); + grid.getColumn(STATUS_COL).setRenderer(new HtmlRenderer(), createStatusConverter()); + grid.removeColumn(TENANT_COL); // grid combobox responseComboBox.setItemIcon(ResponseStatus.SUCCESSFUL, FontAwesome.CHECK_CIRCLE); responseComboBox.setItemIcon(ResponseStatus.ERROR, FontAwesome.EXCLAMATION_CIRCLE); responseComboBox.setNullSelectionAllowed(false); responseComboBox.setValue(ResponseStatus.SUCCESSFUL); - responseComboBox.addValueChangeListener(valueChangeEvent -> { - beanContainer.getItemIds().forEach(itemId -> beanContainer.getItem(itemId).getItemProperty("responseStatus") - .setValue(valueChangeEvent.getProperty().getValue())); - }); + responseComboBox.addValueChangeListener( + valueChangeEvent -> beanContainer.getItemIds().forEach(itemId -> beanContainer.getItem(itemId) + .getItemProperty(RESPONSE_STATUS_COL).setValue(valueChangeEvent.getProperty().getValue()))); // add all components addComponent(caption); @@ -141,7 +155,7 @@ public class SimulatorView extends VerticalLayout implements View { setExpandRatio(grid, 1.0F); // load beans - repository.getAll().forEach(device -> beanContainer.addBean(device)); + repository.getAll().forEach(beanContainer::addBean); } @Override @@ -150,20 +164,16 @@ public class SimulatorView extends VerticalLayout implements View { eventbus.unregister(this); } + @SuppressWarnings("unchecked") @Subscribe public void pollCounterUpdate(final NextPollCounterUpdate update) { final List devices = update.getDevices(); - this.getUI().access(new Runnable() { - @Override - public void run() { - devices.forEach(device -> { - final BeanItem item = beanContainer.getItem(device.getId()); - if (item != null) { - item.getItemProperty("nextPollCounterSec").setValue(device.getNextPollCounterSec()); - } - }); + this.getUI().access(() -> devices.forEach(device -> { + final BeanItem item = beanContainer.getItem(device.getId()); + if (item != null) { + item.getItemProperty(NEXT_POLL_COUNTER_SEC_COL).setValue(device.getNextPollCounterSec()); } - }); + })); } /** @@ -172,20 +182,19 @@ public class SimulatorView extends VerticalLayout implements View { * @param update * the update event posted on the event bus */ + @SuppressWarnings("unchecked") @Subscribe public void initUpdate(final InitUpdate update) { final AbstractSimulatedDevice device = update.getDevice(); - this.getUI().access(new Runnable() { - @Override - public void run() { - final BeanItem item = beanContainer.getItem(device.getId()); - if (item != null) { - item.getItemProperty("progress").setValue(device.getProgress()); - item.getItemProperty("status").setValue(Status.PEDNING); - item.getItemProperty("swversion").setValue(device.getSwversion()); - } - + this.getUI().access(() -> { + final BeanItem item = beanContainer.getItem(device.getId()); + if (item == null) { + return; } + + item.getItemProperty(PROGRESS_COL).setValue(device.getProgress()); + item.getItemProperty(STATUS_COL).setValue(Status.PEDNING); + item.getItemProperty(SWVERSION_COL).setValue(device.getSwversion()); }); } @@ -195,35 +204,37 @@ public class SimulatorView extends VerticalLayout implements View { * @param update * the update event posted on the event bus */ + @SuppressWarnings("unchecked") @Subscribe public void progessUpdate(final ProgressUpdate update) { final AbstractSimulatedDevice device = update.getDevice(); - this.getUI().access(new Runnable() { - @Override - public void run() { - final BeanItem item = beanContainer.getItem(device.getId()); - if (item != null) { - item.getItemProperty("progress").setValue(device.getProgress()); - if (device.getProgress() >= 1) { - switch (device.getResponseStatus()) { - case SUCCESSFUL: - item.getItemProperty("status").setValue(Status.FINISH); - break; - case ERROR: - item.getItemProperty("status").setValue(Status.ERROR); - break; - default: - item.getItemProperty("status").setValue(Status.UNKNWON); - } - } else { - item.getItemProperty("status").setValue(Status.PEDNING); - } - } - + this.getUI().access(() -> { + final BeanItem item = beanContainer.getItem(device.getId()); + if (item != null) { + item.getItemProperty(PROGRESS_COL).setValue(device.getProgress()); + setStatusColumn(device, item); } }); } + @SuppressWarnings("unchecked") + private void setStatusColumn(final AbstractSimulatedDevice device, final BeanItem item) { + if (device.getProgress() >= 1) { + switch (device.getUpdateStatus().getResponseStatus()) { + case SUCCESSFUL: + item.getItemProperty(STATUS_COL).setValue(Status.FINISH); + break; + case ERROR: + item.getItemProperty(STATUS_COL).setValue(Status.ERROR); + break; + default: + item.getItemProperty(STATUS_COL).setValue(Status.UNKNWON); + } + } else { + item.getItemProperty(STATUS_COL).setValue(Status.PEDNING); + } + } + private void createToolbar() { final Button createDevicesButton = new Button("generate..."); createDevicesButton.setIcon(FontAwesome.GEARS); @@ -244,18 +255,15 @@ public class SimulatorView extends VerticalLayout implements View { } private void openGenerateDialog() { - UI.getCurrent().addWindow(new GenerateDialog(new GenerateDialogCallback() { - @Override - public void okButton(final String namePrefix, final String tenant, final int amount, final int pollDelay, - final URL basePollUrl, final String gatewayToken, final Protocol protocol) { - for (int index = 0; index < amount; index++) { - final String deviceId = namePrefix + index; - beanContainer.addBean(repository.add(deviceFactory.createSimulatedDevice(deviceId, - tenant.toLowerCase(), protocol, pollDelay, basePollUrl, gatewayToken))); - spSenderService.createOrUpdateThing(tenant, deviceId); - } - } - })); + UI.getCurrent().addWindow( + new GenerateDialog((namePrefix, tenant, amount, pollDelay, basePollUrl, gatewayToken, protocol) -> { + for (int index = 0; index < amount; index++) { + final String deviceId = namePrefix + index; + beanContainer.addBean(repository.add(deviceFactory.createSimulatedDevice(deviceId, + tenant.toLowerCase(), protocol, pollDelay, basePollUrl, gatewayToken))); + spSenderService.createOrUpdateThing(tenant, deviceId); + } + })); } private Converter createProtocolConverter() { diff --git a/examples/hawkbit-device-simulator/src/main/resources/application.properties b/examples/hawkbit-device-simulator/src/main/resources/application.properties index 56d0190a7..fbe7261be 100644 --- a/examples/hawkbit-device-simulator/src/main/resources/application.properties +++ b/examples/hawkbit-device-simulator/src/main/resources/application.properties @@ -7,18 +7,17 @@ # 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 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-device-simulator/src/main/resources/logback.xml b/examples/hawkbit-device-simulator/src/main/resources/logback.xml new file mode 100644 index 000000000..da64e62d1 --- /dev/null +++ b/examples/hawkbit-device-simulator/src/main/resources/logback.xml @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/examples/hawkbit-example-app/README.md b/examples/hawkbit-example-app/README.md index eaf30f306..068acdd15 100644 --- a/examples/hawkbit-example-app/README.md +++ b/examples/hawkbit-example-app/README.md @@ -1,15 +1,35 @@ # 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 (username: admin, passwd: admin) +- try out Management API https://hawkbit.eu-gb.mybluemix.net/rest/v1/targets (don't forget basic auth header; username: admin, passwd: admin) +- try out DDI API https://hawkbit.eu-gb.mybluemix.net/DEFAULT/controller/v1/MYTESTDEVICE (authentication disabled) + +## On your own workstation +### Run ``` java -jar examples/hawkbit-example-app/target/hawkbit-example-app-*-SNAPSHOT.jar ``` + +_(Note: you have to add the JDBC driver also to your class path if you intend to use another database than H2.)_ + 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 ```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/cf/manifest-simple.yml b/examples/hawkbit-example-app/cf/manifest-simple.yml new file mode 100644 index 000000000..c87a533f4 --- /dev/null +++ b/examples/hawkbit-example-app/cf/manifest-simple.yml @@ -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 +# + +--- +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..2145f467d --- /dev/null +++ b/examples/hawkbit-example-app/cf/manifest.yml @@ -0,0 +1,22 @@ +# +# 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..957ba8d6a 100644 --- a/examples/hawkbit-example-app/pom.xml +++ b/examples/hawkbit-example-app/pom.xml @@ -17,7 +17,7 @@ 0.2.0-SNAPSHOT hawkbit-example-app - hawkBit :: Example App + hawkBit-example :: UI Application @@ -39,6 +39,20 @@ + + + src/main/resources + + + cf + true + ${project.build.directory} + + manifest.yml + manifest-simple.yml + + + @@ -50,7 +64,12 @@ org.eclipse.hawkbit - hawkbit-rest-resource + hawkbit-mgmt-resource + ${project.version} + + + org.eclipse.hawkbit + hawkbit-ddi-resource ${project.version} @@ -82,16 +101,26 @@ org.springframework.boot spring-boot-starter - - - org.springframework.boot - spring-boot-starter-logging - - + - org.springframework.boot - spring-boot-starter-log4j2 + org.apache.logging.log4j + log4j-api + + + + org.slf4j + jul-to-slf4j + + + + org.slf4j + jcl-over-slf4j + + + + org.slf4j + log4j-over-slf4j org.springframework.security diff --git a/examples/hawkbit-example-app/src/main/java/org/eclipse/hawkbit/app/MyLoginUI.java b/examples/hawkbit-example-app/src/main/java/org/eclipse/hawkbit/app/MyLoginUI.java index 763e8447e..d8c5c8493 100644 --- a/examples/hawkbit-example-app/src/main/java/org/eclipse/hawkbit/app/MyLoginUI.java +++ b/examples/hawkbit-example-app/src/main/java/org/eclipse/hawkbit/app/MyLoginUI.java @@ -20,11 +20,11 @@ import com.vaadin.spring.annotation.SpringUI; * login path. The easiest way to get an hawkBit login UI running is to extend * the {@link HawkbitLoginUI} and to annotated it with {@link SpringUI} as in * this example to the defined {@link HawkbitTheme#LOGIN_UI_PATH}. - * - * - * */ @SpringUI(path = HawkbitTheme.LOGIN_UI_PATH) +// Exception squid:MaximumInheritanceDepth - Most of the inheritance comes from +// Vaadin. +@SuppressWarnings({ "squid:MaximumInheritanceDepth" }) public class MyLoginUI extends HawkbitLoginUI { private static final long serialVersionUID = 1L; diff --git a/examples/hawkbit-example-app/src/main/java/org/eclipse/hawkbit/app/MyUI.java b/examples/hawkbit-example-app/src/main/java/org/eclipse/hawkbit/app/MyUI.java index e55cb02d2..e5bc7535d 100644 --- a/examples/hawkbit-example-app/src/main/java/org/eclipse/hawkbit/app/MyUI.java +++ b/examples/hawkbit-example-app/src/main/java/org/eclipse/hawkbit/app/MyUI.java @@ -9,6 +9,7 @@ package org.eclipse.hawkbit.app; import org.eclipse.hawkbit.ui.HawkbitUI; +import org.eclipse.hawkbit.ui.UIEventProvider; import org.eclipse.hawkbit.ui.push.DelayedEventBusPushStrategy; import org.springframework.beans.factory.annotation.Autowired; @@ -28,12 +29,16 @@ import com.vaadin.spring.annotation.SpringUI; */ @SpringUI @Push(value = PushMode.AUTOMATIC, transport = Transport.WEBSOCKET) +// Exception squid:MaximumInheritanceDepth - Most of the inheritance comes from +// Vaadin. +@SuppressWarnings({ "squid:MaximumInheritanceDepth" }) public class MyUI extends HawkbitUI { private static final long serialVersionUID = 1L; @Autowired - public MyUI(final EventBus systemEventBus, final org.vaadin.spring.events.EventBus.SessionEventBus eventBus) { - super(new DelayedEventBusPushStrategy(eventBus, systemEventBus)); + public MyUI(final EventBus systemEventBus, final org.vaadin.spring.events.EventBus.SessionEventBus eventBus, + final UIEventProvider provider) { + super(new DelayedEventBusPushStrategy(eventBus, systemEventBus, provider)); } } diff --git a/examples/hawkbit-example-app/src/main/java/org/eclipse/hawkbit/app/Start.java b/examples/hawkbit-example-app/src/main/java/org/eclipse/hawkbit/app/Start.java index a517dbb08..4a3e6028a 100644 --- a/examples/hawkbit-example-app/src/main/java/org/eclipse/hawkbit/app/Start.java +++ b/examples/hawkbit-example-app/src/main/java/org/eclipse/hawkbit/app/Start.java @@ -10,8 +10,8 @@ package org.eclipse.hawkbit.app; import org.eclipse.hawkbit.RepositoryApplicationConfiguration; import org.eclipse.hawkbit.autoconfigure.security.EnableHawkbitManagedSecurityConfiguration; -import org.eclipse.hawkbit.controller.EnableDirectDeviceApi; -import org.eclipse.hawkbit.rest.resource.EnableRestResources; +import org.eclipse.hawkbit.ddi.EnableDdiApi; +import org.eclipse.hawkbit.mgmt.EnableMgmtApi; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Import; @@ -24,8 +24,10 @@ import org.springframework.context.annotation.Import; @SpringBootApplication @Import({ RepositoryApplicationConfiguration.class }) @EnableHawkbitManagedSecurityConfiguration -@EnableRestResources -@EnableDirectDeviceApi +@EnableMgmtApi +@EnableDdiApi +// Exception squid:S1118 - Spring boot standard behavior +@SuppressWarnings({ "squid:S1118" }) public class Start { /** @@ -34,6 +36,8 @@ public class Start { * @param args * the VM arguments. */ + // Exception squid:S2095 - Spring boot standard behavior + @SuppressWarnings({ "squid:S2095" }) public static void main(final String[] args) { SpringApplication.run(Start.class, args); } 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..a0cad4e9b --- /dev/null +++ b/examples/hawkbit-example-app/src/main/resources/application-cloudsandbox.properties @@ -0,0 +1,16 @@ +# +# 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 +# + +vaadin.servlet.productionMode=true + +hawkbit.artifact.url.coap.enabled=false +hawkbit.artifact.url.http.enabled=false +hawkbit.artifact.url.https.enabled=true +hawkbit.artifact.url.https.pattern={protocol}://{hostname}/{tenant}/controller/v1/{targetId}/softwaremodules/{softwareModuleId}/artifacts/{artifactFileName} +hawkbit.artifact.url.https.hostname=hawkbit.eu-gb.mybluemix.net \ No newline at end of file diff --git a/examples/hawkbit-example-app/src/main/resources/application-mysql.properties b/examples/hawkbit-example-app/src/main/resources/application-mysql.properties new file mode 100644 index 000000000..202500245 --- /dev/null +++ b/examples/hawkbit-example-app/src/main/resources/application-mysql.properties @@ -0,0 +1,32 @@ +# +# 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 profile adds basic configurations for a MySQL DB usage. +# Keep in mind that you need the MariaDB driver in your classpath on compile. +# see https://github.com/eclipse/hawkbit/wiki/Run-hawkBit + +spring.jpa.database=MYSQL +spring.datasource.url=jdbc:mysql://localhost:3306/hawkbit +spring.datasource.username=root +spring.datasource.password= +spring.datasource.driverClassName=org.mariadb.jdbc.Driver + +spring.datasource.max-active=100 +spring.datasource.max-idle=10 +spring.datasource.min-idle=10 +spring.datasource.initial-size=10 +spring.datasource.validation-query=select 1 from dual +spring.datasource.validation-interval=30000 +spring.datasource.test-on-borrow=true +spring.datasource.test-on-return=false +spring.datasource.test-while-idle=true +spring.datasource.time-between-eviction-runs-millis=30000 +spring.datasource.min-evictable-idle-time-millis=60000 +spring.datasource.max-wait=10000 +spring.datasource.jmx-enabled=true diff --git a/examples/hawkbit-example-app/src/main/resources/application.properties b/examples/hawkbit-example-app/src/main/resources/application.properties index 7864087c8..6e05b6b5a 100644 --- a/examples/hawkbit-example-app/src/main/resources/application.properties +++ b/examples/hawkbit-example-app/src/main/resources/application.properties @@ -7,21 +7,28 @@ # http://www.eclipse.org/legal/epl-v10.html # +# DDI authentication configuration hawkbit.server.ddi.security.authentication.anonymous.enabled=true -hawkbit.server.ddi.security.authentication.targettoken.enabled=false -hawkbit.server.ddi.security.authentication.gatewaytoken.enabled=false +hawkbit.server.ddi.security.authentication.targettoken.enabled=true +hawkbit.server.ddi.security.authentication.gatewaytoken.enabled=true -spring.profiles.active=amqp +# Download URL generation config +hawkbit.artifact.url.coap.enabled=false +hawkbit.artifact.url.http.enabled=true +hawkbit.artifact.url.http.port=8080 +hawkbit.artifact.url.https.enabled=false +## Vaadin configuration vaadin.servlet.productionMode=false -## Configuration for RabbitMQ integration +## Configuration for DMF/RabbitMQ integration +spring.profiles.active=amqp spring.rabbitmq.username=guest spring.rabbitmq.password=guest spring.rabbitmq.virtualHost=/ spring.rabbitmq.host=localhost spring.rabbitmq.port=5672 -hawkbit.dmf.rabbitmq.deadLetterQueue=dmf_connector_deadletter +hawkbit.dmf.rabbitmq.deadLetterQueue=dmf_connector_deadletter_ttl hawkbit.dmf.rabbitmq.deadLetterExchange=dmf.connector.deadletter hawkbit.dmf.rabbitmq.receiverQueue=dmf_receiver diff --git a/examples/hawkbit-example-app/src/main/resources/logback.xml b/examples/hawkbit-example-app/src/main/resources/logback.xml new file mode 100644 index 000000000..a76e39683 --- /dev/null +++ b/examples/hawkbit-example-app/src/main/resources/logback.xml @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/examples/hawkbit-example-core-feign-client/README.md b/examples/hawkbit-example-core-feign-client/README.md new file mode 100644 index 000000000..432a31c41 --- /dev/null +++ b/examples/hawkbit-example-core-feign-client/README.md @@ -0,0 +1,13 @@ +# Eclipse.IoT hawkBit - Example Core Feign Client + +This modules contains core beans that are needed to create a [Feign Client](https://github.com/Netflix/feign) with hwakBit. + +# Compile + +#### Build hawkbit-example-core-feign-client + +``` +$ cd hawkbit/examples/hawkbit-example-core-feign-client +$ mvn clean install +``` + diff --git a/examples/hawkbit-example-core-feign-client/pom.xml b/examples/hawkbit-example-core-feign-client/pom.xml new file mode 100644 index 000000000..5b3df2ef2 --- /dev/null +++ b/examples/hawkbit-example-core-feign-client/pom.xml @@ -0,0 +1,46 @@ + + + 4.0.0 + + org.eclipse.hawkbit + hawkbit-examples-parent + 0.2.0-SNAPSHOT + + + hawkbit-example-core-feign-client + hawkBit-example :: Feign Core Client + + + + com.netflix.feign + feign-core + + + org.springframework + spring-web + + + org.springframework.cloud + spring-cloud-netflix-core + 1.0.7.RELEASE + + + org.slf4j + slf4j-api + + + com.netflix.feign + feign-slf4j + + + diff --git a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/ApplicationJsonRequestHeaderInterceptor.java b/examples/hawkbit-example-core-feign-client/src/main/java/org/eclipse/hawkbit/feign/core/client/ApplicationJsonRequestHeaderInterceptor.java similarity index 95% rename from examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/ApplicationJsonRequestHeaderInterceptor.java rename to examples/hawkbit-example-core-feign-client/src/main/java/org/eclipse/hawkbit/feign/core/client/ApplicationJsonRequestHeaderInterceptor.java index 75f3b0dd1..e7faca3b7 100644 --- a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/ApplicationJsonRequestHeaderInterceptor.java +++ b/examples/hawkbit-example-core-feign-client/src/main/java/org/eclipse/hawkbit/feign/core/client/ApplicationJsonRequestHeaderInterceptor.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.mgmt.client; +package org.eclipse.hawkbit.feign.core.client; import org.springframework.http.MediaType; diff --git a/examples/hawkbit-example-core-feign-client/src/main/java/org/eclipse/hawkbit/feign/core/client/FeignClientConfiguration.java b/examples/hawkbit-example-core-feign-client/src/main/java/org/eclipse/hawkbit/feign/core/client/FeignClientConfiguration.java new file mode 100644 index 000000000..1512b7f9e --- /dev/null +++ b/examples/hawkbit-example-core-feign-client/src/main/java/org/eclipse/hawkbit/feign/core/client/FeignClientConfiguration.java @@ -0,0 +1,38 @@ +/** + * 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.feign.core.client; + +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.cloud.netflix.feign.FeignClientsConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; + +import feign.Contract; +import feign.Feign; + +/** + * Spring annotated java configuration class which defines necessary beans for + * configure the feign-client. + */ +@Configuration +@ConditionalOnClass(Feign.class) +@Import(FeignClientsConfiguration.class) +public class FeignClientConfiguration { + + @Bean + public ApplicationJsonRequestHeaderInterceptor jsonHeaderInterceptor() { + return new ApplicationJsonRequestHeaderInterceptor(); + } + + @Bean + public Contract feignContract() { + return new IgnoreMultipleConsumersProducersSpringMvcContract(); + } +} diff --git a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/IgnoreMultipleConsumersProducersSpringMvcContract.java b/examples/hawkbit-example-core-feign-client/src/main/java/org/eclipse/hawkbit/feign/core/client/IgnoreMultipleConsumersProducersSpringMvcContract.java similarity index 97% rename from examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/IgnoreMultipleConsumersProducersSpringMvcContract.java rename to examples/hawkbit-example-core-feign-client/src/main/java/org/eclipse/hawkbit/feign/core/client/IgnoreMultipleConsumersProducersSpringMvcContract.java index c796aa019..b04143cdf 100644 --- a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/IgnoreMultipleConsumersProducersSpringMvcContract.java +++ b/examples/hawkbit-example-core-feign-client/src/main/java/org/eclipse/hawkbit/feign/core/client/IgnoreMultipleConsumersProducersSpringMvcContract.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.mgmt.client; +package org.eclipse.hawkbit.feign.core.client; import java.lang.annotation.Annotation; import java.lang.reflect.Method; diff --git a/examples/hawkbit-example-ddi-feign-client/README.md b/examples/hawkbit-example-ddi-feign-client/README.md new file mode 100644 index 000000000..0eae90c23 --- /dev/null +++ b/examples/hawkbit-example-ddi-feign-client/README.md @@ -0,0 +1,14 @@ +# Eclipse.IoT hawkBit - Example DDI Feign Client API + +This modules contains the declarative client binding resources of the DDI API. +For more information see 'Feign Inheritance Support' at [Spring Cloud] (http://projects.spring.io/spring-cloud/spring-cloud.html). +Powered by [Feign](https://github.com/Netflix/feign). + +# Compile + +#### Build hawkbit-example-ddi-feign-client + +``` +$ cd hawkbit/examples/hawkbit-example-ddi-feign-client +$ mvn clean install +``` diff --git a/examples/hawkbit-example-ddi-feign-client/pom.xml b/examples/hawkbit-example-ddi-feign-client/pom.xml new file mode 100644 index 000000000..5388544db --- /dev/null +++ b/examples/hawkbit-example-ddi-feign-client/pom.xml @@ -0,0 +1,68 @@ + + + 4.0.0 + + org.eclipse.hawkbit + hawkbit-examples-parent + 0.2.0-SNAPSHOT + + hawkbit-example-ddi-feign-client + + hawkBit-example :: DDI Feign Client + + + + + org.springframework.cloud + spring-cloud-netflix + 1.0.7.RELEASE + pom + import + + + + + + + org.eclipse.hawkbit + hawkbit-example-core-feign-client + ${project.version} + + + org.eclipse.hawkbit + hawkbit-ddi-dl-api + ${project.version} + + + org.eclipse.hawkbit + hawkbit-ddi-api + ${project.version} + + + com.google.guava + guava + + + com.netflix.feign + feign-core + + + com.netflix.feign + feign-jackson + + + com.fasterxml.jackson.core + jackson-databind + + + diff --git a/examples/hawkbit-example-ddi-feign-client/src/main/java/org/eclipse/hawkbit/ddi/client/resource/DdiDlArtifactStoreControllerResourceClient.java b/examples/hawkbit-example-ddi-feign-client/src/main/java/org/eclipse/hawkbit/ddi/client/resource/DdiDlArtifactStoreControllerResourceClient.java new file mode 100644 index 000000000..c37602d7a --- /dev/null +++ b/examples/hawkbit-example-ddi-feign-client/src/main/java/org/eclipse/hawkbit/ddi/client/resource/DdiDlArtifactStoreControllerResourceClient.java @@ -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 + */ +package org.eclipse.hawkbit.ddi.client.resource; + +import org.eclipse.hawkbit.ddi.dl.rest.api.DdiDlArtifactStoreControllerRestApi; +import org.eclipse.hawkbit.ddi.dl.rest.api.DdiDlRestConstants; +import org.springframework.cloud.netflix.feign.FeignClient; + +/** + * Client binding for the artifact store controller resource of the DDI-DL API. + */ +@FeignClient(url = "${hawkbit.url:localhost:8080}/" + DdiDlRestConstants.ARTIFACTS_V1_REQUEST_MAPPING) +public interface DdiDlArtifactStoreControllerResourceClient extends DdiDlArtifactStoreControllerRestApi { + +} diff --git a/examples/hawkbit-example-ddi-feign-client/src/main/java/org/eclipse/hawkbit/ddi/client/resource/RootControllerResourceClient.java b/examples/hawkbit-example-ddi-feign-client/src/main/java/org/eclipse/hawkbit/ddi/client/resource/RootControllerResourceClient.java new file mode 100644 index 000000000..389f65da7 --- /dev/null +++ b/examples/hawkbit-example-ddi-feign-client/src/main/java/org/eclipse/hawkbit/ddi/client/resource/RootControllerResourceClient.java @@ -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 + */ +package org.eclipse.hawkbit.ddi.client.resource; + +import org.eclipse.hawkbit.ddi.rest.api.DdiRestConstants; +import org.eclipse.hawkbit.ddi.rest.api.DdiRootControllerRestApi; +import org.springframework.cloud.netflix.feign.FeignClient; + +/** + * Client binding for the Rootcontroller resource of the DDI API. + */ +@FeignClient(url = "${hawkbit.url:localhost:8080}/" + DdiRestConstants.BASE_V1_REQUEST_MAPPING) +public interface RootControllerResourceClient extends DdiRootControllerRestApi { + +} diff --git a/examples/hawkbit-mgmt-api-client/.gitignore b/examples/hawkbit-example-mgmt-feign-client/.gitignore similarity index 100% rename from examples/hawkbit-mgmt-api-client/.gitignore rename to examples/hawkbit-example-mgmt-feign-client/.gitignore diff --git a/examples/hawkbit-example-mgmt-feign-client/README.md b/examples/hawkbit-example-mgmt-feign-client/README.md new file mode 100644 index 000000000..b5b7eb3d2 --- /dev/null +++ b/examples/hawkbit-example-mgmt-feign-client/README.md @@ -0,0 +1,15 @@ +# Eclipse.IoT hawkBit - Example Management Feign Client API + +This modules contains the declarative client binding resources of the Management API. +For more information see 'Feign Inheritance Support' at [Spring Cloud] (http://projects.spring.io/spring-cloud/spring-cloud.html). +Powered by [Feign](https://github.com/Netflix/feign). + +# Compile + +#### Build hawkbit-example-mgmt-feign-client + +``` +$ cd hawkbit/examples/hawkbit-example-mgmt-feign-client +$ mvn clean install +``` + diff --git a/examples/hawkbit-example-mgmt-feign-client/pom.xml b/examples/hawkbit-example-mgmt-feign-client/pom.xml new file mode 100644 index 000000000..7e96e3b00 --- /dev/null +++ b/examples/hawkbit-example-mgmt-feign-client/pom.xml @@ -0,0 +1,56 @@ + + + 4.0.0 + + org.eclipse.hawkbit + hawkbit-examples-parent + 0.2.0-SNAPSHOT + + jar + hawkbit-example-mgmt-feign-client + hawkBit-example :: Management client API + + + + org.eclipse.hawkbit + hawkbit-example-core-feign-client + ${project.version} + + + org.eclipse.hawkbit + hawkbit-mgmt-api + ${project.version} + + + com.google.guava + guava + + + com.netflix.feign + feign-core + + + + com.netflix.feign + feign-jackson + + + com.fasterxml.jackson.core + jackson-databind + + + hibernate-validator + org.hibernate + + + \ No newline at end of file diff --git a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/DistributionSetResourceClient.java b/examples/hawkbit-example-mgmt-feign-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/MgmtDistributionSetClientResource.java similarity index 62% rename from examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/DistributionSetResourceClient.java rename to examples/hawkbit-example-mgmt-feign-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/MgmtDistributionSetClientResource.java index 00a9b3fba..7bf696a8f 100644 --- a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/DistributionSetResourceClient.java +++ b/examples/hawkbit-example-mgmt-feign-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/MgmtDistributionSetClientResource.java @@ -8,13 +8,14 @@ */ package org.eclipse.hawkbit.mgmt.client.resource; -import org.eclipse.hawkbit.rest.resource.api.DistributionSetRestApi; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtDistributionSetRestApi; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants; 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") -public interface DistributionSetResourceClient extends DistributionSetRestApi { +@FeignClient(url = "${hawkbit.url:localhost:8080}/" + MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING) +public interface MgmtDistributionSetClientResource extends MgmtDistributionSetRestApi { } diff --git a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/DistributionSetTagResourceClient.java b/examples/hawkbit-example-mgmt-feign-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/MgmtDistributionSetTagClientResource.java similarity index 61% rename from examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/DistributionSetTagResourceClient.java rename to examples/hawkbit-example-mgmt-feign-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/MgmtDistributionSetTagClientResource.java index ea9f5d28a..783cc09fa 100644 --- a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/DistributionSetTagResourceClient.java +++ b/examples/hawkbit-example-mgmt-feign-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/MgmtDistributionSetTagClientResource.java @@ -8,13 +8,13 @@ */ package org.eclipse.hawkbit.mgmt.client.resource; -import org.eclipse.hawkbit.rest.resource.api.DistributionSetTagRestApi; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtDistributionSetTagRestApi; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants; 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") -public interface DistributionSetTagResourceClient extends DistributionSetTagRestApi { - +@FeignClient(url = "${hawkbit.url:localhost:8080}/" + MgmtRestConstants.DISTRIBUTIONSET_TAG_V1_REQUEST_MAPPING) +public interface MgmtDistributionSetTagClientResource extends MgmtDistributionSetTagRestApi { } diff --git a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/DistributionSetTypeResourceClient.java b/examples/hawkbit-example-mgmt-feign-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/MgmtDistributionSetTypeClientResource.java similarity index 61% rename from examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/DistributionSetTypeResourceClient.java rename to examples/hawkbit-example-mgmt-feign-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/MgmtDistributionSetTypeClientResource.java index 08d40dfa5..35f26781f 100644 --- a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/DistributionSetTypeResourceClient.java +++ b/examples/hawkbit-example-mgmt-feign-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/MgmtDistributionSetTypeClientResource.java @@ -8,14 +8,15 @@ */ package org.eclipse.hawkbit.mgmt.client.resource; -import org.eclipse.hawkbit.rest.resource.api.DistributionSetTypeRestApi; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtDistributionSetTypeRestApi; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants; 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") -public interface DistributionSetTypeResourceClient extends DistributionSetTypeRestApi { +@FeignClient(url = "${hawkbit.url:localhost:8080}/" + MgmtRestConstants.DISTRIBUTIONSETTYPE_V1_REQUEST_MAPPING) +public interface MgmtDistributionSetTypeClientResource extends MgmtDistributionSetTypeRestApi { } diff --git a/examples/hawkbit-example-mgmt-feign-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/MgmtDownloadArtifactClientResource.java b/examples/hawkbit-example-mgmt-feign-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/MgmtDownloadArtifactClientResource.java new file mode 100644 index 000000000..d25a609b2 --- /dev/null +++ b/examples/hawkbit-example-mgmt-feign-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/MgmtDownloadArtifactClientResource.java @@ -0,0 +1,22 @@ +/** + * 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.mgmt.client.resource; + +import org.eclipse.hawkbit.mgmt.rest.api.MgmtDownloadArtifactRestApi; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants; +import org.springframework.cloud.netflix.feign.FeignClient; + +/** + * A feign-client interface declaration which allows to build a feign-client + * stub. + */ +@FeignClient(url = "${hawkbit.url:localhost:8080}/" + MgmtRestConstants.SOFTWAREMODULE_V1_REQUEST_MAPPING) +public interface MgmtDownloadArtifactClientResource extends MgmtDownloadArtifactRestApi { + +} diff --git a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/SoftwareModuleResourceClient.java b/examples/hawkbit-example-mgmt-feign-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/MgmtDownloadClientResource.java similarity index 59% rename from examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/SoftwareModuleResourceClient.java rename to examples/hawkbit-example-mgmt-feign-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/MgmtDownloadClientResource.java index 88e664d78..9a1dcee61 100644 --- a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/SoftwareModuleResourceClient.java +++ b/examples/hawkbit-example-mgmt-feign-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/MgmtDownloadClientResource.java @@ -8,13 +8,13 @@ */ package org.eclipse.hawkbit.mgmt.client.resource; -import org.eclipse.hawkbit.rest.resource.api.SoftwareModuleRestAPI; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtDownloadRestApi; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants; 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") -public interface SoftwareModuleResourceClient extends SoftwareModuleRestAPI { - +@FeignClient(url = "${hawkbit.url:localhost:8080}/" + MgmtRestConstants.DOWNLOAD_ID_V1_REQUEST_MAPPING_BASE) +public interface MgmtDownloadClientResource extends MgmtDownloadRestApi { } diff --git a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/RolloutResourceClient.java b/examples/hawkbit-example-mgmt-feign-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/MgmtRolloutClientResource.java similarity index 63% rename from examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/RolloutResourceClient.java rename to examples/hawkbit-example-mgmt-feign-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/MgmtRolloutClientResource.java index 78b7413e7..d2643a938 100644 --- a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/RolloutResourceClient.java +++ b/examples/hawkbit-example-mgmt-feign-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/MgmtRolloutClientResource.java @@ -8,13 +8,13 @@ */ package org.eclipse.hawkbit.mgmt.client.resource; -import org.eclipse.hawkbit.rest.resource.api.RolloutRestApi; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtRolloutRestApi; 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") -public interface RolloutResourceClient extends RolloutRestApi { - +@FeignClient(url = "${hawkbit.url:localhost:8080}/" + MgmtRestConstants.ROLLOUT_V1_REQUEST_MAPPING) +public interface MgmtRolloutClientResource extends MgmtRolloutRestApi { } diff --git a/examples/hawkbit-example-mgmt-feign-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/MgmtSoftwareModuleClientResource.java b/examples/hawkbit-example-mgmt-feign-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/MgmtSoftwareModuleClientResource.java new file mode 100644 index 000000000..16ea188bd --- /dev/null +++ b/examples/hawkbit-example-mgmt-feign-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/MgmtSoftwareModuleClientResource.java @@ -0,0 +1,36 @@ +/** + * 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.mgmt.client.resource; + +import org.eclipse.hawkbit.mgmt.json.model.artifact.MgmtArtifact; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtSoftwareModuleRestApi; +import org.springframework.cloud.netflix.feign.FeignClient; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.multipart.MultipartFile; + +import feign.Param; + +/** + * Client binding for the SoftwareModule resource of the management API. + */ +@FeignClient(url = "${hawkbit.url:localhost:8080}/" + MgmtRestConstants.SOFTWAREMODULE_V1_REQUEST_MAPPING) +public interface MgmtSoftwareModuleClientResource extends MgmtSoftwareModuleRestApi { + + @RequestMapping(method = RequestMethod.POST, value = "/{softwareModuleId}/artifacts") + ResponseEntity uploadArtifact(@PathVariable("softwareModuleId") final Long softwareModuleId, + @Param("file") final MultipartFile file, + @RequestParam(value = "filename", required = false) final String optionalFileName, + @RequestParam(value = "md5sum", required = false) final String md5Sum, + @RequestParam(value = "sha1sum", required = false) final String sha1Sum); +} diff --git a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/SoftwareModuleTypeResourceClient.java b/examples/hawkbit-example-mgmt-feign-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/MgmtSoftwareModuleTypeClientResource.java similarity index 52% rename from examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/SoftwareModuleTypeResourceClient.java rename to examples/hawkbit-example-mgmt-feign-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/MgmtSoftwareModuleTypeClientResource.java index 4896cb8d8..1e9462c47 100644 --- a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/SoftwareModuleTypeResourceClient.java +++ b/examples/hawkbit-example-mgmt-feign-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/MgmtSoftwareModuleTypeClientResource.java @@ -8,13 +8,13 @@ */ package org.eclipse.hawkbit.mgmt.client.resource; -import org.eclipse.hawkbit.rest.resource.api.SoftwareModuleTypeRestApi; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtSoftwareModuleTypeRestApi; import org.springframework.cloud.netflix.feign.FeignClient; /** - * Client binding for the oftwareModuleType resource of the management API. + * Client binding for the SoftwareModuleType resource of the management API. */ -@FeignClient(url = "${hawkbit.endpoint.url:localhost:8080}/rest/v1/softwaremoduletypes") -public interface SoftwareModuleTypeResourceClient extends SoftwareModuleTypeRestApi { - +@FeignClient(url = "${hawkbit.url:localhost:8080}/" + MgmtRestConstants.SOFTWAREMODULETYPE_V1_REQUEST_MAPPING) +public interface MgmtSoftwareModuleTypeClientResource extends MgmtSoftwareModuleTypeRestApi { } diff --git a/examples/hawkbit-example-mgmt-feign-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/MgmtSystemClientResource.java b/examples/hawkbit-example-mgmt-feign-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/MgmtSystemClientResource.java new file mode 100644 index 000000000..7d6967fed --- /dev/null +++ b/examples/hawkbit-example-mgmt-feign-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/MgmtSystemClientResource.java @@ -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 + */ +package org.eclipse.hawkbit.mgmt.client.resource; + +import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtSystemRestApi; +import org.springframework.cloud.netflix.feign.FeignClient; + +/** + * Client binding for the {@link MgmtSystemRestApi}. + * + */ +@FeignClient(url = "${hawkbit.url:localhost:8080}/" + MgmtRestConstants.SYSTEM_V1_REQUEST_MAPPING) +public interface MgmtSystemClientResource extends MgmtSystemRestApi { +} diff --git a/examples/hawkbit-example-mgmt-feign-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/MgmtSystemManagementClientResource.java b/examples/hawkbit-example-mgmt-feign-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/MgmtSystemManagementClientResource.java new file mode 100644 index 000000000..d1974b43f --- /dev/null +++ b/examples/hawkbit-example-mgmt-feign-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/MgmtSystemManagementClientResource.java @@ -0,0 +1,22 @@ +/** + * 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.mgmt.client.resource; + +import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtSystemManagementRestApi; +import org.springframework.cloud.netflix.feign.FeignClient; + +/** + * Client binding for the {@link MgmtSystemManagementRestApi}. + * + */ +@FeignClient(url = "${hawkbit.url:localhost:8080}/" + MgmtRestConstants.SYSTEM_ADMIN_MAPPING) +public interface MgmtSystemManagementClientResource extends MgmtSystemManagementRestApi { + +} diff --git a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/TargetResourceClient.java b/examples/hawkbit-example-mgmt-feign-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/MgmtTargetClientResource.java similarity index 63% rename from examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/TargetResourceClient.java rename to examples/hawkbit-example-mgmt-feign-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/MgmtTargetClientResource.java index a82aa5443..872c4251a 100644 --- a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/TargetResourceClient.java +++ b/examples/hawkbit-example-mgmt-feign-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/MgmtTargetClientResource.java @@ -8,13 +8,13 @@ */ package org.eclipse.hawkbit.mgmt.client.resource; -import org.eclipse.hawkbit.rest.resource.api.TargetRestApi; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtTargetRestApi; 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") -public interface TargetResourceClient extends TargetRestApi { - +@FeignClient(url = "${hawkbit.url:localhost:8080}/" + MgmtRestConstants.TARGET_V1_REQUEST_MAPPING) +public interface MgmtTargetClientResource extends MgmtTargetRestApi { } diff --git a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/TargetTagResourceClient.java b/examples/hawkbit-example-mgmt-feign-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/MgmtTargetTagClientResource.java similarity index 62% rename from examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/TargetTagResourceClient.java rename to examples/hawkbit-example-mgmt-feign-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/MgmtTargetTagClientResource.java index fee30c686..7b0c213af 100644 --- a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/TargetTagResourceClient.java +++ b/examples/hawkbit-example-mgmt-feign-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/MgmtTargetTagClientResource.java @@ -8,13 +8,13 @@ */ package org.eclipse.hawkbit.mgmt.client.resource; -import org.eclipse.hawkbit.rest.resource.api.TargetTagRestApi; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtTargetTagRestApi; 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") -public interface TargetTagResourceClient extends TargetTagRestApi { - +@FeignClient(url = "${hawkbit.url:localhost:8080}/" + MgmtRestConstants.TARGET_TAG_V1_REQUEST_MAPPING) +public interface MgmtTargetTagClientResource extends MgmtTargetTagRestApi { } diff --git a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/DistributionSetBuilder.java b/examples/hawkbit-example-mgmt-feign-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/DistributionSetBuilder.java similarity index 53% rename from examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/DistributionSetBuilder.java rename to examples/hawkbit-example-mgmt-feign-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/DistributionSetBuilder.java index c821b106c..1e58b8415 100644 --- a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/DistributionSetBuilder.java +++ b/examples/hawkbit-example-mgmt-feign-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/DistributionSetBuilder.java @@ -11,22 +11,23 @@ package org.eclipse.hawkbit.mgmt.client.resource.builder; import java.util.ArrayList; import java.util.List; -import org.eclipse.hawkbit.rest.resource.model.distributionset.DistributionSetRequestBodyPost; +import org.eclipse.hawkbit.mgmt.json.model.distributionset.MgmtDistributionSetRequestBodyPost; +import org.eclipse.hawkbit.mgmt.json.model.softwaremodule.MgmtSoftwareModuleAssigment; import com.google.common.collect.Lists; /** - * - * Builder pattern for building {@link DistributionSetRequestBodyPost}. - * - * @author Jonathan Knoblauch - * + * Builder pattern for building {@link MgmtDistributionSetRequestBodyPost}. */ +// Exception squid:S1701 - builder pattern +@SuppressWarnings({ "squid:S1701" }) public class DistributionSetBuilder { private String name; private String version; private String type; + private String description; + private final List modules = new ArrayList<>(); /** * @param name @@ -38,6 +39,13 @@ public class DistributionSetBuilder { return this; } + public DistributionSetBuilder moduleByID(final Long id) { + final MgmtSoftwareModuleAssigment softwareModuleAssigmentRest = new MgmtSoftwareModuleAssigment(); + softwareModuleAssigmentRest.setId(id); + modules.add(softwareModuleAssigmentRest); + return this; + } + /** * @param version * the version of the distribution set @@ -59,28 +67,38 @@ public class DistributionSetBuilder { } /** - * Builds a list with a single entry of - * {@link DistributionSetRequestBodyPost} which can directly be used to post - * on the RESTful-API. - * - * @return a single entry list of {@link DistributionSetRequestBodyPost} + * @param description + * the description + * @return the builder itself */ - public List build() { + public DistributionSetBuilder description(final String description) { + this.description = description; + return this; + } + + /** + * Builds a list with a single entry of + * {@link MgmtDistributionSetRequestBodyPost} which can directly be used to + * post on the RESTful-API. + * + * @return a single entry list of {@link MgmtDistributionSetRequestBodyPost} + */ + public List build() { return Lists.newArrayList(doBuild(name)); } /** - * Builds a list of multiple {@link DistributionSetRequestBodyPost} to + * Builds a list of multiple {@link MgmtDistributionSetRequestBodyPost} to * create multiple distribution sets at once. An increasing number will be * added to the name of the distribution set. The version and type will * remain the same. * * @param count * the amount of distribution sets body which should be created - * @return a list of {@link DistributionSetRequestBodyPost} + * @return a list of {@link MgmtDistributionSetRequestBodyPost} */ - public List buildAsList(final int count) { - final ArrayList bodyList = Lists.newArrayList(); + public List buildAsList(final int count) { + final ArrayList bodyList = Lists.newArrayList(); for (int index = 0; index < count; index++) { bodyList.add(doBuild(name + index)); } @@ -88,11 +106,13 @@ public class DistributionSetBuilder { return bodyList; } - private DistributionSetRequestBodyPost doBuild(final String prefixName) { - final DistributionSetRequestBodyPost body = new DistributionSetRequestBodyPost(); + private MgmtDistributionSetRequestBodyPost doBuild(final String prefixName) { + final MgmtDistributionSetRequestBodyPost body = new MgmtDistributionSetRequestBodyPost(); body.setName(prefixName); body.setVersion(version); body.setType(type); + body.setDescription(description); + body.setModules(modules); return body; } diff --git a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/DistributionSetTypeBuilder.java b/examples/hawkbit-example-mgmt-feign-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/DistributionSetTypeBuilder.java similarity index 57% rename from examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/DistributionSetTypeBuilder.java rename to examples/hawkbit-example-mgmt-feign-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/DistributionSetTypeBuilder.java index e1da1f048..1ce2ff270 100644 --- a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/DistributionSetTypeBuilder.java +++ b/examples/hawkbit-example-mgmt-feign-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/DistributionSetTypeBuilder.java @@ -11,24 +11,25 @@ package org.eclipse.hawkbit.mgmt.client.resource.builder; import java.util.ArrayList; import java.util.List; -import org.eclipse.hawkbit.rest.resource.model.distributionsettype.DistributionSetTypeRequestBodyPost; -import org.eclipse.hawkbit.rest.resource.model.softwaremoduletype.SoftwareModuleTypeAssigmentRest; +import org.eclipse.hawkbit.mgmt.json.model.distributionsettype.MgmtDistributionSetTypeRequestBodyPost; +import org.eclipse.hawkbit.mgmt.json.model.softwaremoduletype.MgmtSoftwareModuleTypeAssigment; import com.google.common.collect.Lists; /** * - * Builder pattern for building {@link DistributionSetTypeRequestBodyPost}. - * - * @author Jonathan Knoblauch + * Builder pattern for building {@link MgmtDistributionSetTypeRequestBodyPost}. * */ +// Exception squid:S1701 - builder pattern +@SuppressWarnings({ "squid:S1701" }) public class DistributionSetTypeBuilder { private String key; private String name; - private final List mandatorymodules = Lists.newArrayList(); - private final List optionalmodules = Lists.newArrayList(); + private String description; + private final List mandatorymodules = Lists.newArrayList(); + private final List optionalmodules = Lists.newArrayList(); /** * @param key @@ -50,6 +51,16 @@ public class DistributionSetTypeBuilder { return this; } + /** + * @param description + * the description + * @return the builder itself + */ + public DistributionSetTypeBuilder description(final String description) { + this.description = description; + return this; + } + /** * @param softwareModuleTypeIds * the IDs of the software module types which should be mandatory @@ -58,7 +69,7 @@ public class DistributionSetTypeBuilder { */ public DistributionSetTypeBuilder mandatorymodules(final Long... softwareModuleTypeIds) { for (final Long id : softwareModuleTypeIds) { - final SoftwareModuleTypeAssigmentRest softwareModuleTypeAssigmentRest = new SoftwareModuleTypeAssigmentRest(); + final MgmtSoftwareModuleTypeAssigment softwareModuleTypeAssigmentRest = new MgmtSoftwareModuleTypeAssigment(); softwareModuleTypeAssigmentRest.setId(id); this.mandatorymodules.add(softwareModuleTypeAssigmentRest); } @@ -74,7 +85,7 @@ public class DistributionSetTypeBuilder { */ public DistributionSetTypeBuilder optionalmodules(final Long... softwareModuleTypeIds) { for (final Long id : softwareModuleTypeIds) { - final SoftwareModuleTypeAssigmentRest softwareModuleTypeAssigmentRest = new SoftwareModuleTypeAssigmentRest(); + final MgmtSoftwareModuleTypeAssigment softwareModuleTypeAssigmentRest = new MgmtSoftwareModuleTypeAssigment(); softwareModuleTypeAssigmentRest.setId(id); this.optionalmodules.add(softwareModuleTypeAssigmentRest); } @@ -83,28 +94,29 @@ public class DistributionSetTypeBuilder { /** * Builds a list with a single entry of - * {@link DistributionSetTypeRequestBodyPost} which can directly be used in - * the RESTful-API. + * {@link MgmtDistributionSetTypeRequestBodyPost} which can directly be used + * in the RESTful-API. * - * @return a single entry list of {@link DistributionSetTypeRequestBodyPost} + * @return a single entry list of + * {@link MgmtDistributionSetTypeRequestBodyPost} */ - public List build() { + public List build() { return Lists.newArrayList(doBuild(name, key)); } /** - * Builds a list of multiple {@link DistributionSetTypeRequestBodyPost} to - * create multiple distribution set types at once. An increasing number will - * be added to the name and key of the distribution set type. The optional - * and mandatory software module types will remain the same. + * Builds a list of multiple {@link MgmtDistributionSetTypeRequestBodyPost} + * to create multiple distribution set types at once. An increasing number + * will be added to the name and key of the distribution set type. The + * optional and mandatory software module types will remain the same. * * @param count * the amount of distribution sets type body which should be * created - * @return a list of {@link DistributionSetTypeRequestBodyPost} + * @return a list of {@link MgmtDistributionSetTypeRequestBodyPost} */ - public List buildAsList(final int count) { - final ArrayList bodyList = Lists.newArrayList(); + public List buildAsList(final int count) { + final ArrayList bodyList = Lists.newArrayList(); for (int index = 0; index < count; index++) { bodyList.add(doBuild(name + index, key + index)); } @@ -112,10 +124,11 @@ public class DistributionSetTypeBuilder { } - private DistributionSetTypeRequestBodyPost doBuild(final String prefixName, final String prefixKey) { - final DistributionSetTypeRequestBodyPost body = new DistributionSetTypeRequestBodyPost(); + private MgmtDistributionSetTypeRequestBodyPost doBuild(final String prefixName, final String prefixKey) { + final MgmtDistributionSetTypeRequestBodyPost body = new MgmtDistributionSetTypeRequestBodyPost(); body.setKey(prefixKey); body.setName(prefixName); + body.setDescription(description); body.setMandatorymodules(mandatorymodules); body.setOptionalmodules(optionalmodules); return body; diff --git a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/RolloutBuilder.java b/examples/hawkbit-example-mgmt-feign-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/RolloutBuilder.java similarity index 74% rename from examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/RolloutBuilder.java rename to examples/hawkbit-example-mgmt-feign-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/RolloutBuilder.java index bea0fd9a4..02ebe2de3 100644 --- a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/RolloutBuilder.java +++ b/examples/hawkbit-example-mgmt-feign-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/RolloutBuilder.java @@ -8,17 +8,17 @@ */ package org.eclipse.hawkbit.mgmt.client.resource.builder; -import org.eclipse.hawkbit.rest.resource.model.rollout.RolloutCondition; -import org.eclipse.hawkbit.rest.resource.model.rollout.RolloutCondition.Condition; -import org.eclipse.hawkbit.rest.resource.model.rollout.RolloutRestRequestBody; +import org.eclipse.hawkbit.mgmt.json.model.rollout.MgmtRolloutCondition; +import org.eclipse.hawkbit.mgmt.json.model.rollout.MgmtRolloutCondition.Condition; +import org.eclipse.hawkbit.mgmt.json.model.rollout.MgmtRolloutRestRequestBody; /** * - * Builder pattern for building {@link RolloutRestRequestBody}. - * - * @author Jonathan Knoblauch + * Builder pattern for building {@link MgmtRolloutRestRequestBody}. * */ +// Exception squid:S1701 - builder pattern +@SuppressWarnings({ "squid:S1701" }) public class RolloutBuilder { private String name; @@ -27,6 +27,7 @@ public class RolloutBuilder { private long distributionSetId; private String successThreshold; private String errorThreshold; + private String description; /** * @param name @@ -59,6 +60,16 @@ public class RolloutBuilder { return this; } + /** + * @param description + * the description + * @return the builder itself + */ + public RolloutBuilder description(final String description) { + this.description = description; + return this; + } + /** * @param distributionSetId * the ID of the distribution set to assign to the target in the @@ -97,18 +108,19 @@ public class RolloutBuilder { * * @return the rest request body for creating a rollout */ - public RolloutRestRequestBody build() { + public MgmtRolloutRestRequestBody build() { return doBuild(); } - private RolloutRestRequestBody doBuild() { - final RolloutRestRequestBody body = new RolloutRestRequestBody(); + private MgmtRolloutRestRequestBody doBuild() { + final MgmtRolloutRestRequestBody body = new MgmtRolloutRestRequestBody(); body.setName(name); body.setAmountGroups(groupSize); body.setTargetFilterQuery(targetFilterQuery); body.setDistributionSetId(distributionSetId); - body.setSuccessCondition(new RolloutCondition(Condition.THRESHOLD, successThreshold)); - body.setErrorCondition(new RolloutCondition(Condition.THRESHOLD, errorThreshold)); + body.setDescription(description); + body.setSuccessCondition(new MgmtRolloutCondition(Condition.THRESHOLD, successThreshold)); + body.setErrorCondition(new MgmtRolloutCondition(Condition.THRESHOLD, errorThreshold)); return body; } diff --git a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/SoftwareModuleAssigmentBuilder.java b/examples/hawkbit-example-mgmt-feign-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/SoftwareModuleAssigmentBuilder.java similarity index 65% rename from examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/SoftwareModuleAssigmentBuilder.java rename to examples/hawkbit-example-mgmt-feign-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/SoftwareModuleAssigmentBuilder.java index b209dbe8b..b9fbcb498 100644 --- a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/SoftwareModuleAssigmentBuilder.java +++ b/examples/hawkbit-example-mgmt-feign-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/SoftwareModuleAssigmentBuilder.java @@ -11,15 +11,15 @@ package org.eclipse.hawkbit.mgmt.client.resource.builder; import java.util.ArrayList; import java.util.List; -import org.eclipse.hawkbit.rest.resource.model.softwaremodule.SoftwareModuleAssigmentRest; +import org.eclipse.hawkbit.mgmt.json.model.softwaremodule.MgmtSoftwareModuleAssigment; /** * - * Builder pattern for building {@link SoftwareModuleAssigmentRest}. - * - * @author Jonathan Knoblauch + * Builder pattern for building {@link MgmtSoftwareModuleAssigment}. * */ +// Exception squid:S1701 - builder pattern +@SuppressWarnings({ "squid:S1701" }) public class SoftwareModuleAssigmentBuilder { private final List ids; @@ -39,15 +39,15 @@ public class SoftwareModuleAssigmentBuilder { } /** - * Builds a list with a single entry of {@link SoftwareModuleAssigmentRest} + * Builds a list with a single entry of {@link MgmtSoftwareModuleAssigment} * which can directly be used in the RESTful-API. * - * @return a single entry list of {@link SoftwareModuleAssigmentRest} + * @return a single entry list of {@link MgmtSoftwareModuleAssigment} */ - public List build() { - final List softwareModuleAssigmentRestList = new ArrayList<>(); + public List build() { + final List softwareModuleAssigmentRestList = new ArrayList<>(); for (final Long id : ids) { - final SoftwareModuleAssigmentRest softwareModuleAssigmentRest = new SoftwareModuleAssigmentRest(); + final MgmtSoftwareModuleAssigment softwareModuleAssigmentRest = new MgmtSoftwareModuleAssigment(); softwareModuleAssigmentRest.setId(id); softwareModuleAssigmentRestList.add(softwareModuleAssigmentRest); } diff --git a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/SoftwareModuleBuilder.java b/examples/hawkbit-example-mgmt-feign-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/SoftwareModuleBuilder.java similarity index 51% rename from examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/SoftwareModuleBuilder.java rename to examples/hawkbit-example-mgmt-feign-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/SoftwareModuleBuilder.java index 30b85d901..b2e544f88 100644 --- a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/SoftwareModuleBuilder.java +++ b/examples/hawkbit-example-mgmt-feign-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/SoftwareModuleBuilder.java @@ -11,23 +11,25 @@ package org.eclipse.hawkbit.mgmt.client.resource.builder; import java.util.ArrayList; import java.util.List; -import org.eclipse.hawkbit.rest.resource.model.distributionsettype.DistributionSetTypeRequestBodyPost; -import org.eclipse.hawkbit.rest.resource.model.softwaremodule.SoftwareModuleRequestBodyPost; +import org.eclipse.hawkbit.mgmt.json.model.distributionsettype.MgmtDistributionSetTypeRequestBodyPost; +import org.eclipse.hawkbit.mgmt.json.model.softwaremodule.MgmtSoftwareModuleRequestBodyPost; import com.google.common.collect.Lists; /** * - * Builder pattern for building {@link SoftwareModuleRequestBodyPost}. - * - * @author Jonathan Knoblauch + * Builder pattern for building {@link MgmtSoftwareModuleRequestBodyPost}. * */ +// Exception squid:S1701 - builder pattern +@SuppressWarnings({ "squid:S1701" }) public class SoftwareModuleBuilder { private String name; private String version; private String type; + private String vendor; + private String description; /** * @param name @@ -61,28 +63,48 @@ public class SoftwareModuleBuilder { } /** - * Builds a list with a single entry of - * {@link SoftwareModuleRequestBodyPost} which can directly be used in the - * RESTful-API. - * - * @return a single entry list of {@link SoftwareModuleRequestBodyPost} + * @param vendor + * the vendor + * @return the builder itself */ - public List build() { + public SoftwareModuleBuilder vendor(final String vendor) { + this.vendor = vendor; + return this; + } + + /** + * @param description + * the description + * @return the builder itself + */ + public SoftwareModuleBuilder description(final String description) { + this.description = description; + return this; + } + + /** + * Builds a list with a single entry of + * {@link MgmtSoftwareModuleRequestBodyPost} which can directly be used in + * the RESTful-API. + * + * @return a single entry list of {@link MgmtSoftwareModuleRequestBodyPost} + */ + public List build() { return Lists.newArrayList(doBuild(name)); } /** - * Builds a list of multiple {@link SoftwareModuleRequestBodyPost} to create - * multiple software module at once. An increasing number will be added to - * the name of the software module. The version and type will remain the - * same. + * Builds a list of multiple {@link MgmtSoftwareModuleRequestBodyPost} to + * create multiple software module at once. An increasing number will be + * added to the name of the software module. The version and type will + * remain the same. * * @param count * the amount of software module body which should be created - * @return a list of {@link DistributionSetTypeRequestBodyPost} + * @return a list of {@link MgmtDistributionSetTypeRequestBodyPost} */ - public List buildAsList(final int count) { - final ArrayList bodyList = Lists.newArrayList(); + public List buildAsList(final int count) { + final ArrayList bodyList = Lists.newArrayList(); for (int index = 0; index < count; index++) { bodyList.add(doBuild(name + index)); } @@ -90,11 +112,13 @@ public class SoftwareModuleBuilder { return bodyList; } - private SoftwareModuleRequestBodyPost doBuild(final String prefixName) { - final SoftwareModuleRequestBodyPost body = new SoftwareModuleRequestBodyPost(); + private MgmtSoftwareModuleRequestBodyPost doBuild(final String prefixName) { + final MgmtSoftwareModuleRequestBodyPost body = new MgmtSoftwareModuleRequestBodyPost(); body.setName(prefixName); body.setVersion(version); body.setType(type); + body.setVendor(vendor); + body.setDescription(description); return body; } diff --git a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/SoftwareModuleTypeBuilder.java b/examples/hawkbit-example-mgmt-feign-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/SoftwareModuleTypeBuilder.java similarity index 61% rename from examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/SoftwareModuleTypeBuilder.java rename to examples/hawkbit-example-mgmt-feign-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/SoftwareModuleTypeBuilder.java index ce128d592..7981e61cf 100644 --- a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/SoftwareModuleTypeBuilder.java +++ b/examples/hawkbit-example-mgmt-feign-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/SoftwareModuleTypeBuilder.java @@ -11,18 +11,18 @@ package org.eclipse.hawkbit.mgmt.client.resource.builder; import java.util.ArrayList; import java.util.List; -import org.eclipse.hawkbit.rest.resource.model.softwaremodule.SoftwareModuleRequestBodyPost; -import org.eclipse.hawkbit.rest.resource.model.softwaremoduletype.SoftwareModuleTypeRequestBodyPost; +import org.eclipse.hawkbit.mgmt.json.model.softwaremodule.MgmtSoftwareModuleRequestBodyPost; +import org.eclipse.hawkbit.mgmt.json.model.softwaremoduletype.MgmtSoftwareModuleTypeRequestBodyPost; import com.google.common.collect.Lists; /** * - * Builder pattern for building {@link SoftwareModuleRequestBodyPost}. - * - * @author Jonathan Knoblauch + * Builder pattern for building {@link MgmtSoftwareModuleRequestBodyPost}. * */ +// Exception squid:S1701 - builder pattern +@SuppressWarnings({ "squid:S1701" }) public class SoftwareModuleTypeBuilder { private String key; @@ -62,35 +62,36 @@ public class SoftwareModuleTypeBuilder { /** * Builds a list with a single entry of - * {@link SoftwareModuleTypeRequestBodyPost} which can directly be used in - * the RESTful-API. + * {@link MgmtSoftwareModuleTypeRequestBodyPost} which can directly be used + * in the RESTful-API. * - * @return a single entry list of {@link SoftwareModuleTypeRequestBodyPost} + * @return a single entry list of + * {@link MgmtSoftwareModuleTypeRequestBodyPost} */ - public List build() { + public List build() { return Lists.newArrayList(doBuild(key, name)); } /** - * Builds a list of multiple {@link SoftwareModuleTypeRequestBodyPost} to - * create multiple software module types at once. An increasing number will - * be added to the name and key of the software module type. + * Builds a list of multiple {@link MgmtSoftwareModuleTypeRequestBodyPost} + * to create multiple software module types at once. An increasing number + * will be added to the name and key of the software module type. * * @param count * the amount of software module type bodies which should be * created - * @return a list of {@link SoftwareModuleTypeRequestBodyPost} + * @return a list of {@link MgmtSoftwareModuleTypeRequestBodyPost} */ - public List buildAsList(final int count) { - final ArrayList bodyList = Lists.newArrayList(); + public List buildAsList(final int count) { + final ArrayList bodyList = Lists.newArrayList(); for (int index = 0; index < count; index++) { bodyList.add(doBuild(key + index, name + index)); } return bodyList; } - private SoftwareModuleTypeRequestBodyPost doBuild(final String prefixKey, final String prefixName) { - final SoftwareModuleTypeRequestBodyPost body = new SoftwareModuleTypeRequestBodyPost(); + private MgmtSoftwareModuleTypeRequestBodyPost doBuild(final String prefixKey, final String prefixName) { + final MgmtSoftwareModuleTypeRequestBodyPost body = new MgmtSoftwareModuleTypeRequestBodyPost(); body.setKey(prefixKey); body.setName(prefixName); body.setDescription(description); diff --git a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/TagBuilder.java b/examples/hawkbit-example-mgmt-feign-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/TagBuilder.java similarity index 63% rename from examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/TagBuilder.java rename to examples/hawkbit-example-mgmt-feign-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/TagBuilder.java index f3888de54..ce13602df 100644 --- a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/TagBuilder.java +++ b/examples/hawkbit-example-mgmt-feign-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/TagBuilder.java @@ -11,16 +11,16 @@ package org.eclipse.hawkbit.mgmt.client.resource.builder; import java.util.ArrayList; import java.util.List; -import org.eclipse.hawkbit.rest.resource.model.tag.TagRequestBodyPut; +import org.eclipse.hawkbit.mgmt.json.model.tag.MgmtTagRequestBodyPut; import com.google.common.collect.Lists; /** - * Builder pattern for building {@link TagRequestBodyPut}. - * - * @author Jonathan Knoblauch + * Builder pattern for building {@link MgmtTagRequestBodyPut}. * */ +// Exception squid:S1701 - builder pattern +@SuppressWarnings({ "squid:S1701" }) public class TagBuilder { private String name; @@ -58,26 +58,26 @@ public class TagBuilder { } /** - * Builds a list with a single entry of {@link TagRequestBodyPut} which can - * directly be used in the RESTful-API. + * Builds a list with a single entry of {@link MgmtTagRequestBodyPut} which + * can directly be used in the RESTful-API. * - * @return a single entry list of {@link TagRequestBodyPut} + * @return a single entry list of {@link MgmtTagRequestBodyPut} */ - public List build() { + public List build() { return Lists.newArrayList(doBuild(name)); } /** - * Builds a list of multiple {@link TagRequestBodyPut} to create multiple - * tags at once. An increasing number will be added to the name of the tag. - * The color and description will remain the same. + * Builds a list of multiple {@link MgmtTagRequestBodyPut} to create + * multiple tags at once. An increasing number will be added to the name of + * the tag. The color and description will remain the same. * * @param count * the amount of distribution sets body which should be created - * @return a list of {@link TagRequestBodyPut} + * @return a list of {@link MgmtTagRequestBodyPut} */ - public List buildAsList(final int count) { - final ArrayList bodyList = Lists.newArrayList(); + public List buildAsList(final int count) { + final ArrayList bodyList = Lists.newArrayList(); for (int index = 0; index < count; index++) { bodyList.add(doBuild(name + index)); } @@ -85,8 +85,8 @@ public class TagBuilder { return bodyList; } - private TagRequestBodyPut doBuild(final String prefixName) { - final TagRequestBodyPut body = new TagRequestBodyPut(); + private MgmtTagRequestBodyPut doBuild(final String prefixName) { + final MgmtTagRequestBodyPut body = new MgmtTagRequestBodyPut(); body.setName(prefixName); body.setDescription(description); body.setColour(color); diff --git a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/TargetBuilder.java b/examples/hawkbit-example-mgmt-feign-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/TargetBuilder.java similarity index 62% rename from examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/TargetBuilder.java rename to examples/hawkbit-example-mgmt-feign-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/TargetBuilder.java index 5123903d9..7bcc0af09 100644 --- a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/TargetBuilder.java +++ b/examples/hawkbit-example-mgmt-feign-client/src/main/java/org/eclipse/hawkbit/mgmt/client/resource/builder/TargetBuilder.java @@ -11,18 +11,18 @@ package org.eclipse.hawkbit.mgmt.client.resource.builder; import java.util.ArrayList; import java.util.List; -import org.eclipse.hawkbit.rest.resource.model.softwaremoduletype.SoftwareModuleTypeRequestBodyPost; -import org.eclipse.hawkbit.rest.resource.model.target.TargetRequestBody; +import org.eclipse.hawkbit.mgmt.json.model.softwaremoduletype.MgmtSoftwareModuleTypeRequestBodyPost; +import org.eclipse.hawkbit.mgmt.json.model.target.MgmtTargetRequestBody; import com.google.common.collect.Lists; /** * - * Builder pattern for building {@link TargetRequestBody}. - * - * @author Jonathan Knoblauch + * Builder pattern for building {@link MgmtTargetRequestBody}. * */ +// Exception squid:S1701 - builder pattern +@SuppressWarnings({ "squid:S1701" }) public class TargetBuilder { private String controllerId; @@ -60,35 +60,35 @@ public class TargetBuilder { } /** - * Builds a list with a single entry of {@link TargetRequestBody} which can - * directly be used in the RESTful-API. + * Builds a list with a single entry of {@link MgmtTargetRequestBody} which + * can directly be used in the RESTful-API. * - * @return a single entry list of {@link TargetRequestBody} + * @return a single entry list of {@link MgmtTargetRequestBody} */ - public List build() { + public List build() { return Lists.newArrayList(doBuild(controllerId)); } /** - * Builds a list of multiple {@link TargetRequestBody} to create multiple - * targets at once. An increasing number will be added to the controllerId - * of the target. The name and description will remain. + * Builds a list of multiple {@link MgmtTargetRequestBody} to create + * multiple targets at once. An increasing number will be added to the + * controllerId of the target. The name and description will remain. * * @param count * the amount of software module type bodies which should be * created - * @return a list of {@link SoftwareModuleTypeRequestBodyPost} + * @return a list of {@link MgmtSoftwareModuleTypeRequestBodyPost} */ - public List buildAsList(final int count) { - final ArrayList bodyList = Lists.newArrayList(); + public List buildAsList(final int count) { + final ArrayList bodyList = Lists.newArrayList(); for (int index = 0; index < count; index++) { bodyList.add(doBuild(controllerId + index)); } return bodyList; } - private TargetRequestBody doBuild(final String prefixControllerId) { - final TargetRequestBody body = new TargetRequestBody(); + private MgmtTargetRequestBody doBuild(final String prefixControllerId) { + final MgmtTargetRequestBody body = new MgmtTargetRequestBody(); body.setControllerId(prefixControllerId); body.setName(name); body.setDescription(description); diff --git a/examples/hawkbit-example-mgmt-simulator/.gitignore b/examples/hawkbit-example-mgmt-simulator/.gitignore new file mode 100644 index 000000000..4b9b73073 --- /dev/null +++ b/examples/hawkbit-example-mgmt-simulator/.gitignore @@ -0,0 +1,3 @@ +/target/ +/bin/ +/.apt_generated/ diff --git a/examples/hawkbit-mgmt-api-client/README.md b/examples/hawkbit-example-mgmt-simulator/README.md similarity index 62% rename from examples/hawkbit-mgmt-api-client/README.md rename to examples/hawkbit-example-mgmt-simulator/README.md index eff301e20..925df8041 100644 --- a/examples/hawkbit-mgmt-api-client/README.md +++ b/examples/hawkbit-example-mgmt-simulator/README.md @@ -1,6 +1,6 @@ -# HawkBit management API example +# Eclipse.IoT hawkBit - Example Management Feign Client -Example client that shows how to efficiently use the hawkBit management API. +Example Spring Boot client that shows how to efficiently use the hawkBit Example Management Feign Client and the hawkBit Management API. Powered by [Feign](https://github.com/Netflix/feign). @@ -10,13 +10,13 @@ Run getting started example - $ java -jar hawkbit-mgmt-api-client-#version#.jar + $ java -jar hawkbit-example-mgmt-simulator-#version#.jar Run create and start rollout example - $ java -jar hawkbit-mgmt-api-client-#version#.jar --createrollout + $ java -jar hawkbit-example-mgmt-simulator-#version#.jar --createrollout ## This example shows @@ -28,7 +28,7 @@ In getting started example: * creating software modules * assigning software modules to distribution sets -In rollout mode: +In create rollout example: * creating software modules type * creating distribution set type * creating distribution sets @@ -36,4 +36,3 @@ In rollout mode: * assigning software modules to distribution sets * creating a rollout * starting a rollout - diff --git a/examples/hawkbit-mgmt-api-client/pom.xml b/examples/hawkbit-example-mgmt-simulator/pom.xml similarity index 87% rename from examples/hawkbit-mgmt-api-client/pom.xml rename to examples/hawkbit-example-mgmt-simulator/pom.xml index 9aaf53dc6..469290dfc 100644 --- a/examples/hawkbit-mgmt-api-client/pom.xml +++ b/examples/hawkbit-example-mgmt-simulator/pom.xml @@ -17,8 +17,8 @@ 0.2.0-SNAPSHOT jar - hawkbit-mgmt-api-client - hawkBit Management API example client + hawkbit-example-mgmt-simulator + hawkBit-example :: Management feign client simulator @@ -57,14 +57,20 @@ org.eclipse.hawkbit - hawkbit-rest-api + hawkbit-example-mgmt-feign-client ${project.version} com.netflix.feign feign-core - - 8.14.2 + + + com.netflix.feign + feign-jackson + + + com.fasterxml.jackson.core + jackson-databind hibernate-validator @@ -82,11 +88,6 @@ org.springframework.boot spring-boot-starter-logging - - com.google.collections - google-collections - 1.0-rc2 - org.springframework.boot spring-boot-configuration-processor diff --git a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/Application.java b/examples/hawkbit-example-mgmt-simulator/src/main/java/org/eclipse/hawkbit/mgmt/client/Application.java similarity index 80% rename from examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/Application.java rename to examples/hawkbit-example-mgmt-simulator/src/main/java/org/eclipse/hawkbit/mgmt/client/Application.java index 27584b50a..7e1f191a9 100644 --- a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/Application.java +++ b/examples/hawkbit-example-mgmt-simulator/src/main/java/org/eclipse/hawkbit/mgmt/client/Application.java @@ -8,22 +8,28 @@ */ package org.eclipse.hawkbit.mgmt.client; +import org.eclipse.hawkbit.feign.core.client.FeignClientConfiguration; import org.eclipse.hawkbit.mgmt.client.scenarios.CreateStartedRolloutExample; import org.eclipse.hawkbit.mgmt.client.scenarios.GettingStartedDefaultScenario; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.cloud.netflix.feign.EnableFeignClients; import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; -import feign.Contract; import feign.auth.BasicAuthRequestInterceptor; @SpringBootApplication @EnableFeignClients @EnableConfigurationProperties(ClientConfigurationProperties.class) +@Configuration +@AutoConfigureAfter(FeignClientConfiguration.class) +@Import(FeignClientConfiguration.class) public class Application implements CommandLineRunner { @Autowired @@ -57,13 +63,13 @@ public class Application implements CommandLineRunner { } @Bean - public ApplicationJsonRequestHeaderInterceptor jsonHeaderInterceptor() { - return new ApplicationJsonRequestHeaderInterceptor(); + public GettingStartedDefaultScenario gettingStartedDefaultScenario() { + return new GettingStartedDefaultScenario(); } @Bean - public Contract feignContract() { - return new IgnoreMultipleConsumersProducersSpringMvcContract(); + public CreateStartedRolloutExample createStartedRolloutExample() { + return new CreateStartedRolloutExample(); } private boolean containsArg(final String containsArg, final String... args) { diff --git a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/ClientConfigurationProperties.java b/examples/hawkbit-example-mgmt-simulator/src/main/java/org/eclipse/hawkbit/mgmt/client/ClientConfigurationProperties.java similarity index 100% rename from examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/ClientConfigurationProperties.java rename to examples/hawkbit-example-mgmt-simulator/src/main/java/org/eclipse/hawkbit/mgmt/client/ClientConfigurationProperties.java diff --git a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/scenarios/CreateStartedRolloutExample.java b/examples/hawkbit-example-mgmt-simulator/src/main/java/org/eclipse/hawkbit/mgmt/client/scenarios/CreateStartedRolloutExample.java similarity index 63% rename from examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/scenarios/CreateStartedRolloutExample.java rename to examples/hawkbit-example-mgmt-simulator/src/main/java/org/eclipse/hawkbit/mgmt/client/scenarios/CreateStartedRolloutExample.java index 35b0f31ea..90d61471e 100644 --- a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/scenarios/CreateStartedRolloutExample.java +++ b/examples/hawkbit-example-mgmt-simulator/src/main/java/org/eclipse/hawkbit/mgmt/client/scenarios/CreateStartedRolloutExample.java @@ -8,12 +8,14 @@ */ package org.eclipse.hawkbit.mgmt.client.scenarios; -import org.eclipse.hawkbit.mgmt.client.resource.DistributionSetResourceClient; -import org.eclipse.hawkbit.mgmt.client.resource.DistributionSetTypeResourceClient; -import org.eclipse.hawkbit.mgmt.client.resource.RolloutResourceClient; -import org.eclipse.hawkbit.mgmt.client.resource.SoftwareModuleResourceClient; -import org.eclipse.hawkbit.mgmt.client.resource.SoftwareModuleTypeResourceClient; -import org.eclipse.hawkbit.mgmt.client.resource.TargetResourceClient; +import java.util.List; + +import org.eclipse.hawkbit.mgmt.client.resource.MgmtDistributionSetClientResource; +import org.eclipse.hawkbit.mgmt.client.resource.MgmtDistributionSetTypeClientResource; +import org.eclipse.hawkbit.mgmt.client.resource.MgmtRolloutClientResource; +import org.eclipse.hawkbit.mgmt.client.resource.MgmtSoftwareModuleClientResource; +import org.eclipse.hawkbit.mgmt.client.resource.MgmtSoftwareModuleTypeClientResource; +import org.eclipse.hawkbit.mgmt.client.resource.MgmtTargetClientResource; import org.eclipse.hawkbit.mgmt.client.resource.builder.DistributionSetBuilder; import org.eclipse.hawkbit.mgmt.client.resource.builder.DistributionSetTypeBuilder; import org.eclipse.hawkbit.mgmt.client.resource.builder.RolloutBuilder; @@ -21,43 +23,41 @@ import org.eclipse.hawkbit.mgmt.client.resource.builder.SoftwareModuleAssigmentB import org.eclipse.hawkbit.mgmt.client.resource.builder.SoftwareModuleBuilder; import org.eclipse.hawkbit.mgmt.client.resource.builder.SoftwareModuleTypeBuilder; import org.eclipse.hawkbit.mgmt.client.resource.builder.TargetBuilder; -import org.eclipse.hawkbit.rest.resource.model.distributionset.DistributionSetsRest; -import org.eclipse.hawkbit.rest.resource.model.rollout.RolloutResponseBody; -import org.eclipse.hawkbit.rest.resource.model.softwaremodule.SoftwareModulesRest; -import org.eclipse.hawkbit.rest.resource.model.softwaremoduletype.SoftwareModuleTypesRest; +import org.eclipse.hawkbit.mgmt.json.model.distributionset.MgmtDistributionSet; +import org.eclipse.hawkbit.mgmt.json.model.rollout.MgmtRolloutResponseBody; +import org.eclipse.hawkbit.mgmt.json.model.softwaremodule.MgmtSoftwareModule; +import org.eclipse.hawkbit.mgmt.json.model.softwaremoduletype.MgmtSoftwareModuleType; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; /** * Example for creating and starting a Rollout. * */ -@Component public class CreateStartedRolloutExample { /* known software module type name and key */ 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; + private MgmtDistributionSetClientResource distributionSetResource; @Autowired - private SoftwareModuleResourceClient softwareModuleResource; + private MgmtSoftwareModuleClientResource softwareModuleResource; @Autowired - private TargetResourceClient targetResource; + private MgmtTargetClientResource targetResource; @Autowired - private RolloutResourceClient rolloutResource; + private MgmtRolloutClientResource rolloutResource; @Autowired - private DistributionSetTypeResourceClient distributionSetTypeResource; + private MgmtDistributionSetTypeClientResource distributionSetTypeResource; @Autowired - private SoftwareModuleTypeResourceClient softwareModuleTypeResource; + private MgmtSoftwareModuleTypeClientResource softwareModuleTypeResource; /** * Run the Rollout scenario. @@ -65,8 +65,9 @@ public class CreateStartedRolloutExample { public void run() { // create three SoftwareModuleTypes - final SoftwareModuleTypesRest createdSoftwareModuleTypes = softwareModuleTypeResource.createSoftwareModuleTypes( - new SoftwareModuleTypeBuilder().key(SM_MODULE_TYPE).name(SM_MODULE_TYPE).maxAssignments(1).build()) + final List createdSoftwareModuleTypes = softwareModuleTypeResource + .createSoftwareModuleTypes(new SoftwareModuleTypeBuilder().key(SM_MODULE_TYPE).name(SM_MODULE_TYPE) + .maxAssignments(1).build()) .getBody(); // create one DistributionSetType @@ -75,12 +76,12 @@ public class CreateStartedRolloutExample { .getBody(); // create one DistributionSet - final DistributionSetsRest distributionSetsRest = distributionSetResource.createDistributionSets( + final List distributionSetsRest = distributionSetResource.createDistributionSets( new DistributionSetBuilder().name("rollout-example").version("1.0.0").type(DS_MODULE_TYPE).build()) .getBody(); // create three SoftwareModules - final SoftwareModulesRest softwareModulesRest = softwareModuleResource + final List softwareModulesRest = softwareModuleResource .createSoftwareModules( new SoftwareModuleBuilder().name("firmware").version("1.0.0").type(SM_MODULE_TYPE).build()) .getBody(); @@ -94,7 +95,7 @@ public class CreateStartedRolloutExample { .description("Targets used for rollout example").buildAsList(10)); // create a Rollout - final RolloutResponseBody rolloutResponseBody = rolloutResource + final MgmtRolloutResponseBody rolloutResponseBody = rolloutResource .create(new RolloutBuilder().name("MyRollout").groupSize(2).targetFilterQuery("name==00-FF-AA-0*") .distributionSetId(distributionSetsRest.get(0).getDsId()).successThreshold("80") .errorThreshold("50").build()) diff --git a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/scenarios/GettingStartedDefaultScenario.java b/examples/hawkbit-example-mgmt-simulator/src/main/java/org/eclipse/hawkbit/mgmt/client/scenarios/GettingStartedDefaultScenario.java similarity index 71% rename from examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/scenarios/GettingStartedDefaultScenario.java rename to examples/hawkbit-example-mgmt-simulator/src/main/java/org/eclipse/hawkbit/mgmt/client/scenarios/GettingStartedDefaultScenario.java index 5767ab9e7..fdb824e8e 100644 --- a/examples/hawkbit-mgmt-api-client/src/main/java/org/eclipse/hawkbit/mgmt/client/scenarios/GettingStartedDefaultScenario.java +++ b/examples/hawkbit-example-mgmt-simulator/src/main/java/org/eclipse/hawkbit/mgmt/client/scenarios/GettingStartedDefaultScenario.java @@ -8,29 +8,29 @@ */ package org.eclipse.hawkbit.mgmt.client.scenarios; -import org.eclipse.hawkbit.mgmt.client.resource.DistributionSetResourceClient; -import org.eclipse.hawkbit.mgmt.client.resource.DistributionSetTypeResourceClient; -import org.eclipse.hawkbit.mgmt.client.resource.SoftwareModuleResourceClient; -import org.eclipse.hawkbit.mgmt.client.resource.SoftwareModuleTypeResourceClient; +import java.util.List; + +import org.eclipse.hawkbit.mgmt.client.resource.MgmtDistributionSetClientResource; +import org.eclipse.hawkbit.mgmt.client.resource.MgmtDistributionSetTypeClientResource; +import org.eclipse.hawkbit.mgmt.client.resource.MgmtSoftwareModuleClientResource; +import org.eclipse.hawkbit.mgmt.client.resource.MgmtSoftwareModuleTypeClientResource; import org.eclipse.hawkbit.mgmt.client.resource.builder.DistributionSetBuilder; import org.eclipse.hawkbit.mgmt.client.resource.builder.DistributionSetTypeBuilder; import org.eclipse.hawkbit.mgmt.client.resource.builder.SoftwareModuleAssigmentBuilder; import org.eclipse.hawkbit.mgmt.client.resource.builder.SoftwareModuleBuilder; import org.eclipse.hawkbit.mgmt.client.resource.builder.SoftwareModuleTypeBuilder; -import org.eclipse.hawkbit.rest.resource.model.distributionset.DistributionSetsRest; -import org.eclipse.hawkbit.rest.resource.model.softwaremodule.SoftwareModulesRest; -import org.eclipse.hawkbit.rest.resource.model.softwaremoduletype.SoftwareModuleTypesRest; +import org.eclipse.hawkbit.mgmt.json.model.distributionset.MgmtDistributionSet; +import org.eclipse.hawkbit.mgmt.json.model.softwaremodule.MgmtSoftwareModule; +import org.eclipse.hawkbit.mgmt.json.model.softwaremoduletype.MgmtSoftwareModuleType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; /** * * Default getting started scenario. * */ -@Component public class GettingStartedDefaultScenario { private static final Logger LOGGER = LoggerFactory.getLogger(GettingStartedDefaultScenario.class); @@ -39,25 +39,25 @@ 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; + private MgmtDistributionSetClientResource distributionSetResource; @Autowired - private DistributionSetTypeResourceClient distributionSetTypeResource; + private MgmtDistributionSetTypeClientResource distributionSetTypeResource; @Autowired - private SoftwareModuleResourceClient softwareModuleResource; + private MgmtSoftwareModuleClientResource softwareModuleResource; @Autowired - private SoftwareModuleTypeResourceClient softwareModuleTypeResource; + private MgmtSoftwareModuleTypeClientResource softwareModuleTypeResource; /** * Run the default getting started scenario. @@ -68,8 +68,9 @@ public class GettingStartedDefaultScenario { // create one SoftwareModuleTypes LOGGER.info("Creating software module type {}", SM_MODULE_TYPE); - final SoftwareModuleTypesRest createdSoftwareModuleTypes = softwareModuleTypeResource.createSoftwareModuleTypes( - new SoftwareModuleTypeBuilder().key(SM_MODULE_TYPE).name(SM_MODULE_TYPE).maxAssignments(1).build()) + final List createdSoftwareModuleTypes = softwareModuleTypeResource + .createSoftwareModuleTypes(new SoftwareModuleTypeBuilder().key(SM_MODULE_TYPE).name(SM_MODULE_TYPE) + .maxAssignments(1).build()) .getBody(); // create one DistributionSetType @@ -83,17 +84,17 @@ public class GettingStartedDefaultScenario { final String dsVersion3 = "2.1.0"; LOGGER.info("Creating distribution set {}:{}", DS_EXAMPLE_NAME, dsVersion1); - final DistributionSetsRest distributionSetsRest1 = distributionSetResource.createDistributionSets( + final List distributionSetsRest1 = distributionSetResource.createDistributionSets( new DistributionSetBuilder().name(DS_EXAMPLE_NAME).version(dsVersion1).type(DS_MODULE_TYPE).build()) .getBody(); LOGGER.info("Creating distribution set {}:{}", DS_EXAMPLE_NAME, dsVersion2); - final DistributionSetsRest distributionSetsRest2 = distributionSetResource.createDistributionSets( + final List distributionSetsRest2 = distributionSetResource.createDistributionSets( new DistributionSetBuilder().name(DS_EXAMPLE_NAME).version(dsVersion2).type(DS_MODULE_TYPE).build()) .getBody(); LOGGER.info("Creating distribution set {}:{}", DS_EXAMPLE_NAME, dsVersion3); - final DistributionSetsRest distributionSetsRest3 = distributionSetResource.createDistributionSets( + final List distributionSetsRest3 = distributionSetResource.createDistributionSets( new DistributionSetBuilder().name(DS_EXAMPLE_NAME).version(dsVersion3).type(DS_MODULE_TYPE).build()) .getBody(); @@ -103,15 +104,15 @@ public class GettingStartedDefaultScenario { final String swVersion3 = "3"; LOGGER.info("Creating distribution set {}:{}", SM_EXAMPLE_NAME, swVersion1); - final SoftwareModulesRest softwareModulesRest1 = softwareModuleResource.createSoftwareModules( + final List softwareModulesRest1 = softwareModuleResource.createSoftwareModules( new SoftwareModuleBuilder().name(SM_EXAMPLE_NAME).version(swVersion1).type(SM_MODULE_TYPE).build()) .getBody(); LOGGER.info("Creating distribution set {}:{}", SM_EXAMPLE_NAME, swVersion2); - final SoftwareModulesRest softwareModulesRest2 = softwareModuleResource.createSoftwareModules( + final List softwareModulesRest2 = softwareModuleResource.createSoftwareModules( new SoftwareModuleBuilder().name(SM_EXAMPLE_NAME).version(swVersion2).type(SM_MODULE_TYPE).build()) .getBody(); LOGGER.info("Creating distribution set {}:{}", SM_EXAMPLE_NAME, swVersion3); - final SoftwareModulesRest softwareModulesRest3 = softwareModuleResource.createSoftwareModules( + final List softwareModulesRest3 = softwareModuleResource.createSoftwareModules( new SoftwareModuleBuilder().name(SM_EXAMPLE_NAME).version(swVersion3).type(SM_MODULE_TYPE).build()) .getBody(); diff --git a/examples/hawkbit-mgmt-api-client/src/main/resources/application.properties b/examples/hawkbit-example-mgmt-simulator/src/main/resources/application.properties similarity index 100% rename from examples/hawkbit-mgmt-api-client/src/main/resources/application.properties rename to examples/hawkbit-example-mgmt-simulator/src/main/resources/application.properties diff --git a/examples/hawkbit-mgmt-api-client/src/main/resources/logback.xml b/examples/hawkbit-example-mgmt-simulator/src/main/resources/logback.xml similarity index 100% rename from examples/hawkbit-mgmt-api-client/src/main/resources/logback.xml rename to examples/hawkbit-example-mgmt-simulator/src/main/resources/logback.xml diff --git a/examples/pom.xml b/examples/pom.xml index 5f1377123..fb8ef3fc3 100644 --- a/examples/pom.xml +++ b/examples/pom.xml @@ -8,8 +8,7 @@ http://www.eclipse.org/legal/epl-v10.html --> - + 4.0.0 @@ -19,13 +18,45 @@ hawkbit-examples-parent - hawkBit :: Examples Parent + hawkBit-example :: Parent pom hawkbit-device-simulator hawkbit-example-app - hawkbit-mgmt-api-client - + hawkbit-example-core-feign-client + hawkbit-example-ddi-feign-client + hawkbit-example-mgmt-feign-client + hawkbit-example-mgmt-simulator + + + + + 8.14.2 + + + + + + com.netflix.feign + feign-core + + + ${feign.version} + + + com.netflix.feign + feign-jackson + + + ${feign.version} + + + com.netflix.feign + feign-slf4j + ${feign.version} + + + \ No newline at end of file diff --git a/hawkbit-artifact-repository-mongo/src/main/java/org/eclipse/hawkbit/artifact/repository/ArtifactStore.java b/hawkbit-artifact-repository-mongo/src/main/java/org/eclipse/hawkbit/artifact/repository/ArtifactStore.java index 78658da91..5f12498ff 100644 --- a/hawkbit-artifact-repository-mongo/src/main/java/org/eclipse/hawkbit/artifact/repository/ArtifactStore.java +++ b/hawkbit-artifact-repository-mongo/src/main/java/org/eclipse/hawkbit/artifact/repository/ArtifactStore.java @@ -8,11 +8,14 @@ */ package org.eclipse.hawkbit.artifact.repository; +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; +import java.io.OutputStream; import java.security.DigestOutputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; @@ -38,10 +41,7 @@ import com.mongodb.gridfs.GridFSDBFile; import com.mongodb.gridfs.GridFSFile; /** - * The file management which looks up all the file in the filestore. - * - * - * + * The file management which looks up all the file in the file tore. * */ public class ArtifactStore implements ArtifactRepository { @@ -60,7 +60,7 @@ public class ArtifactStore implements ArtifactRepository { private static final String MD5 = "md5"; /** - * The mongoDB field which holds the SHA1 hash, stored in the metadata + * The mongoDB field which holds the SHA1 hash, stored in the meta data * object. */ private static final String SHA1 = "sha1"; @@ -75,11 +75,10 @@ public class ArtifactStore implements ArtifactRepository { /** * Retrieves a {@link GridFSDBFile} from the store by it's SHA1 hash. * - * @param tenant - * the tenant to retrieve the artifacts from, ignore case. * @param sha1Hash * the sha1-hash of the file to lookup. - * @return The gridfs file object or {@code null} if no file exists. + * + * @return The DbArtifact object or {@code null} if no file exists. */ @Override public DbArtifact getArtifactBySha1(final String sha1Hash) { @@ -126,7 +125,11 @@ public class ArtifactStore implements ArtifactRepository { LOGGER.debug("storing file {} of content {}", filename, contentType); tempFile = File.createTempFile("uploadFile", null); try (final FileOutputStream os = new FileOutputStream(tempFile)) { - return store(content, contentType, os, tempFile, hash); + try (BufferedOutputStream bos = new BufferedOutputStream(os)) { + try (BufferedInputStream bis = new BufferedInputStream(content)) { + return store(content, contentType, bos, tempFile, hash); + } + } } } catch (final IOException | MongoException e1) { throw new ArtifactStoreException(e1.getMessage(), e1); @@ -166,7 +169,7 @@ public class ArtifactStore implements ArtifactRepository { } - private DbArtifact store(final InputStream content, final String contentType, final FileOutputStream os, + private DbArtifact store(final InputStream content, final String contentType, final OutputStream os, final File tempFile, final DbArtifactHash hash) { final GridFsArtifact storedArtifact; try { @@ -189,7 +192,8 @@ public class ArtifactStore implements ArtifactRepository { throw new ArtifactStoreException(e.getMessage(), e); } - if (hash != null && hash.getMd5() != null && !storedArtifact.getHashes().getMd5().equals(hash.getMd5())) { + if (hash != null && hash.getMd5() != null + && !storedArtifact.getHashes().getMd5().equalsIgnoreCase(hash.getMd5())) { throw new HashNotMatchException("The given md5 hash " + hash.getMd5() + " not matching the calculated md5 hash " + storedArtifact.getHashes().getMd5(), HashNotMatchException.MD5); @@ -199,14 +203,14 @@ public class ArtifactStore implements ArtifactRepository { } - private static String computeSHA1Hash(final InputStream stream, final FileOutputStream os, - final String providedSHA1Sum) throws NoSuchAlgorithmException, IOException { + private static String computeSHA1Hash(final InputStream stream, final OutputStream os, final String providedSHA1Sum) + throws NoSuchAlgorithmException, IOException { String sha1Hash; // compute digest final MessageDigest md = MessageDigest.getInstance("SHA-1"); - final DigestOutputStream dos = new DigestOutputStream(os, md); - ByteStreams.copy(stream, dos); - dos.close(); + try (final DigestOutputStream dos = new DigestOutputStream(os, md)) { + ByteStreams.copy(stream, dos); + } sha1Hash = BaseEncoding.base16().lowerCase().encode(md.digest()); if (providedSHA1Sum != null && !providedSHA1Sum.equalsIgnoreCase(sha1Hash)) { throw new HashNotMatchException( @@ -226,8 +230,7 @@ public class ArtifactStore implements ArtifactRepository { * @return a paged list of artifacts mapped from the given dbFiles */ private List map(final List dbFiles) { - final List collect = dbFiles.stream().map(dbFile -> map(dbFile)).collect(Collectors.toList()); - return collect; + return dbFiles.stream().map(dbFile -> map(dbFile)).collect(Collectors.toList()); } /** @@ -238,7 +241,7 @@ public class ArtifactStore implements ArtifactRepository { * the tenant to retrieve the artifacts from, ignore case. * @param sha1Hashes * the sha1-hashes of the files to lookup. - * @return list of artfiacts + * @return list of artifacts */ @Override public List getArtifactsBySha1(final List sha1Hashes) { diff --git a/hawkbit-artifact-repository-mongo/src/main/java/org/eclipse/hawkbit/artifact/repository/MongoConfiguration.java b/hawkbit-artifact-repository-mongo/src/main/java/org/eclipse/hawkbit/artifact/repository/MongoConfiguration.java index 02fb22725..e01c6a455 100644 --- a/hawkbit-artifact-repository-mongo/src/main/java/org/eclipse/hawkbit/artifact/repository/MongoConfiguration.java +++ b/hawkbit-artifact-repository-mongo/src/main/java/org/eclipse/hawkbit/artifact/repository/MongoConfiguration.java @@ -71,6 +71,8 @@ public class MongoConfiguration extends AbstractMongoConfiguration { @Override @Bean @ConditionalOnMissingBean + // Closed by pre-destroy + @SuppressWarnings({ "squid:S2095" }) public Mongo mongo() throws UnknownHostException { final MongoClientURI uri = new MongoClientURI(properties.getUri(), createBuilderOutOfOptions(options)); diff --git a/hawkbit-autoconfigure/pom.xml b/hawkbit-autoconfigure/pom.xml index 7670da406..7ad0e0911 100644 --- a/hawkbit-autoconfigure/pom.xml +++ b/hawkbit-autoconfigure/pom.xml @@ -64,7 +64,13 @@ org.eclipse.hawkbit - hawkbit-rest-resource + hawkbit-ddi-resource + ${project.version} + true + + + org.eclipse.hawkbit + hawkbit-mgmt-resource ${project.version} true 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..825e21c12 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; @@ -27,14 +26,15 @@ import org.eclipse.hawkbit.im.authentication.SpPermission; import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions; import org.eclipse.hawkbit.im.authentication.TenantUserPasswordAuthenticationToken; import org.eclipse.hawkbit.im.authentication.UserAuthenticationFilter; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants; import org.eclipse.hawkbit.repository.ControllerManagement; import org.eclipse.hawkbit.repository.SystemManagement; import org.eclipse.hawkbit.repository.TenantConfigurationManagement; -import org.eclipse.hawkbit.rest.resource.RestConstants; import org.eclipse.hawkbit.security.ControllerTenantAwareAuthenticationDetailsSource; import org.eclipse.hawkbit.security.DdiSecurityProperties; import org.eclipse.hawkbit.security.DosFilter; import org.eclipse.hawkbit.security.HawkbitSecurityProperties; +import org.eclipse.hawkbit.security.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); @@ -282,8 +292,9 @@ public class SecurityManagedConfiguration { new AuthenticationSuccessTenantMetadataCreationFilter(tenantAware, systemManagement), RequestHeaderAuthenticationFilter.class) .authorizeRequests().anyRequest().authenticated() - .antMatchers(RestConstants.BASE_SYSTEM_MAPPING + "/admin/**") - .hasAnyAuthority(SpPermission.SYSTEM_ADMIN).antMatchers(RestConstants.BASE_SYSTEM_MAPPING + "/**") + .antMatchers(MgmtRestConstants.BASE_SYSTEM_MAPPING + "/admin/**") + .hasAnyAuthority(SpPermission.SYSTEM_ADMIN) + .antMatchers(MgmtRestConstants.BASE_SYSTEM_MAPPING + "/**") .hasAnyAuthority(SpPermission.SYSTEM_DIAG); } } diff --git a/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/ui/UIAutoConfiguration.java b/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/ui/UIAutoConfiguration.java index ff73eff7b..be66904d5 100644 --- a/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/ui/UIAutoConfiguration.java +++ b/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/ui/UIAutoConfiguration.java @@ -9,6 +9,9 @@ package org.eclipse.hawkbit.autoconfigure.ui; import org.eclipse.hawkbit.DistributedResourceBundleMessageSource; +import org.eclipse.hawkbit.ui.HawkbitEventProvider; +import org.eclipse.hawkbit.ui.UIEventProvider; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.vaadin.spring.annotation.EnableVaadinExtensions; @@ -17,9 +20,6 @@ import org.vaadin.spring.security.annotation.EnableVaadinSecurity; /** * The hawkbit-ui autoconfiguration. - * - * - * */ @Configuration @EnableVaadinSecurity @@ -37,4 +37,15 @@ public class UIAutoConfiguration { return new DistributedResourceBundleMessageSource(); } + /** + * A event provider bean which hold the supported events for the UI. + * + * @return the provider bean + */ + @Bean + @ConditionalOnMissingBean + public UIEventProvider eventProvider() { + return new HawkbitEventProvider(); + } + } diff --git a/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/web/ResourceControllerAutoConfiguration.java b/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/web/ResourceControllerAutoConfiguration.java index 1d75510e4..ee54995c8 100644 --- a/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/web/ResourceControllerAutoConfiguration.java +++ b/hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/web/ResourceControllerAutoConfiguration.java @@ -8,21 +8,19 @@ */ package org.eclipse.hawkbit.autoconfigure.web; -import org.eclipse.hawkbit.controller.EnableDirectDeviceApi; -import org.eclipse.hawkbit.rest.resource.EnableRestResources; +import org.eclipse.hawkbit.ddi.EnableDdiApi; +import org.eclipse.hawkbit.mgmt.EnableMgmtApi; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; /** * Auto-Configuration for enabling the REST-Resources. - * - * * */ @Configuration -@ConditionalOnClass({ EnableDirectDeviceApi.class, EnableRestResources.class }) -@Import({ EnableDirectDeviceApi.class, EnableRestResources.class }) +@ConditionalOnClass({ EnableDdiApi.class, EnableMgmtApi.class }) +@Import({ EnableDdiApi.class, EnableMgmtApi.class }) public class ResourceControllerAutoConfiguration { } diff --git a/hawkbit-autoconfigure/src/main/resources/hawkbitdefaults.properties b/hawkbit-autoconfigure/src/main/resources/hawkbitdefaults.properties index 198fce255..488777b8d 100644 --- a/hawkbit-autoconfigure/src/main/resources/hawkbitdefaults.properties +++ b/hawkbit-autoconfigure/src/main/resources/hawkbitdefaults.properties @@ -42,6 +42,6 @@ hawkbit.controller.minPollingTime=00:00:30 # Configuration for RabbitMQ integration -hawkbit.dmf.rabbitmq.deadLetterQueue=dmf_connector_deadletter +hawkbit.dmf.rabbitmq.deadLetterQueue=dmf_connector_deadletter_ttl hawkbit.dmf.rabbitmq.deadLetterExchange=dmf.connector.deadletter hawkbit.dmf.rabbitmq.receiverQueue=dmf_receiver \ No newline at end of file diff --git a/hawkbit-core/README.md b/hawkbit-core/README.md new file mode 100644 index 000000000..bf75314d1 --- /dev/null +++ b/hawkbit-core/README.md @@ -0,0 +1,3 @@ +# hawkBit Core + +Various internal interfaces and utility classes. \ No newline at end of file diff --git a/hawkbit-core/src/main/java/org/eclipse/hawkbit/ControllerPollProperties.java b/hawkbit-core/src/main/java/org/eclipse/hawkbit/ControllerPollProperties.java index c923963d2..0d70ae69d 100644 --- a/hawkbit-core/src/main/java/org/eclipse/hawkbit/ControllerPollProperties.java +++ b/hawkbit-core/src/main/java/org/eclipse/hawkbit/ControllerPollProperties.java @@ -31,7 +31,7 @@ public class ControllerPollProperties { * Maximum polling time that can be configured by a tenant in HH:MM:SS * notation. */ - private String maxPollingTime = "23:59:00"; + private String maxPollingTime = "23:59:59"; /** * Minimum polling time that can be configured by a tenant in HH:MM:SS diff --git a/hawkbit-core/src/main/java/org/eclipse/hawkbit/DistributedResourceBundleMessageSource.java b/hawkbit-core/src/main/java/org/eclipse/hawkbit/DistributedResourceBundleMessageSource.java index 0b0847652..0f5301c40 100644 --- a/hawkbit-core/src/main/java/org/eclipse/hawkbit/DistributedResourceBundleMessageSource.java +++ b/hawkbit-core/src/main/java/org/eclipse/hawkbit/DistributedResourceBundleMessageSource.java @@ -22,11 +22,10 @@ import org.springframework.core.io.support.ResourcePatternResolver; * This resource bundles using specified basenames, to resource loading. This * MessageSource implementation supports more than 1 properties file with the * same name. All properties files will be merged. - * - * - * */ public class DistributedResourceBundleMessageSource extends ReloadableResourceBundleMessageSource { + // Exception squid:S2387 - Follows our upper case convention + @SuppressWarnings({ "squid:S2387" }) private static final Logger LOGGER = LoggerFactory.getLogger(DistributedResourceBundleMessageSource.class); private static final String PROPERTIES_SUFFIX = ".properties"; private ResourceLoader resourceLoader; 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 new file mode 100644 index 000000000..03492122c --- /dev/null +++ b/hawkbit-core/src/main/java/org/eclipse/hawkbit/api/ArtifactUrlHandler.java @@ -0,0 +1,43 @@ +/** + * 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; + +/** + * Interface declaration of the {@link ArtifactUrlHandler} which generates the + * URLs to specific artifacts. + * + */ +public interface ArtifactUrlHandler { + + /** + * Returns a generated download URL for a given artifact parameters for a + * specific protocol. + * + * @param controllerId + * the authenticated controller id + * @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 parameters in a given protocol + */ + String getUrl(String controllerId, final Long softwareModuleId, final String filename, final String sha1Hash, + final UrlProtocol protocol); + + /** + * @param protocol + * to check support for + * @return true of the handler supports given protocol. + */ + boolean protocolSupported(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..c589e40e0 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,40 +6,32 @@ * 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 { private static final String DEFAULT_IP_LOCALHOST = "127.0.0.1"; + private static final String DEFAULT_PORT = "8080"; private static final String LOCALHOST = "localhost"; private final Http http = new Http(); 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 +58,6 @@ public class ArtifactUrlHandlerProperties { /** * Interface for declaring common properties through all supported protocols * pattern. - * - * - * */ public interface ProtocolProperties { /** @@ -90,18 +79,21 @@ public class ArtifactUrlHandlerProperties { * @return the pattern to build the URL. */ String getPattern(); + + /** + * @return true if the {@link ProtocolProperties} is + * enabled. + */ + boolean isEnabled(); } /** * Object to hold the properties for the HTTP protocol. - * - * - * */ public static class Http implements ProtocolProperties { private String hostname = LOCALHOST; private String ip = DEFAULT_IP_LOCALHOST; - private String port = ""; + private String port = DEFAULT_PORT; /** * An ant-URL pattern with placeholder to build the URL on. The URL can * have specific artifact placeholder. @@ -109,65 +101,51 @@ public class ArtifactUrlHandlerProperties { private String pattern = "{protocol}://{hostname}:{port}/{tenant}/controller/v1/{targetId}/softwaremodules/{softwareModuleId}/artifacts/{artifactFileName}"; /** - * @return the hostname + * Enables HTTP URI generation in DDI and DMF. */ + private boolean enabled = true; + + @Override + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(final boolean enabled) { + this.enabled = enabled; + } + @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,14 +153,11 @@ public class ArtifactUrlHandlerProperties { /** * Object to hold the properties for the HTTP protocol. - * - * - * */ public static class Https implements ProtocolProperties { private String hostname = LOCALHOST; private String ip = DEFAULT_IP_LOCALHOST; - private String port = ""; + private String port = DEFAULT_PORT; /** * An ant-URL pattern with placeholder to build the URL on. The URL can * have specific artifact placeholder. @@ -190,65 +165,51 @@ public class ArtifactUrlHandlerProperties { private String pattern = "{protocol}://{hostname}:{port}/{tenant}/controller/v1/{targetId}/softwaremodules/{softwareModuleId}/artifacts/{artifactFileName}"; /** - * @return the hostname + * Enables HTTPS URI generation in DDI and DMF. */ + private boolean enabled = true; + + @Override + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(final boolean enabled) { + this.enabled = enabled; + } + @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 +217,6 @@ public class ArtifactUrlHandlerProperties { /** * Object to hold the properties for the HTTP protocol. - * - * - * */ public static class Coap implements ProtocolProperties { private String hostname = LOCALHOST; @@ -271,67 +229,54 @@ public class ArtifactUrlHandlerProperties { private String pattern = "{protocol}://{ip}:{port}/fw/{tenant}/{targetId}/sha1/{artifactSHA1}"; /** - * @return the hostname + * Enables CoAP URI generation in DMF. */ + private boolean enabled = true; + + @Override + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(final boolean enabled) { + this.enabled = enabled; + } + @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 71% 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..d43d660ca 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,12 +56,12 @@ 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() + "}", - Strings.isNullOrEmpty(entry.getValue()) ? "" : ":" + entry.getValue()); + Strings.isNullOrEmpty(entry.getValue()) ? "" : (":" + entry.getValue())); } else { urlPattern = urlPattern.replace("{" + entry.getKey() + "}", entry.getValue()); } @@ -69,19 +69,30 @@ 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; } + @Override + public boolean protocolSupported(final UrlProtocol protocol) { + final String protocolString = protocol.name().toLowerCase(); + final ProtocolProperties properties = urlHandlerProperties.getProperties(protocolString); + if (properties == null || properties.getPattern() == null) { + return false; + } + + return properties.isEnabled(); + } + } 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..77c23ad0d --- /dev/null +++ b/hawkbit-core/src/main/java/org/eclipse/hawkbit/api/UrlProtocol.java @@ -0,0 +1,16 @@ +/** + * 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; + +/** + * Represented the supported protocols for artifact url's. + */ +public enum UrlProtocol { + COAP, HTTP, HTTPS +} diff --git a/hawkbit-core/src/main/java/org/eclipse/hawkbit/artifact/repository/model/DbArtifact.java b/hawkbit-core/src/main/java/org/eclipse/hawkbit/artifact/repository/model/DbArtifact.java index b4c2dcdba..2385e0dfa 100644 --- a/hawkbit-core/src/main/java/org/eclipse/hawkbit/artifact/repository/model/DbArtifact.java +++ b/hawkbit-core/src/main/java/org/eclipse/hawkbit/artifact/repository/model/DbArtifact.java @@ -14,9 +14,6 @@ import java.io.OutputStream; /** * Database representation of artifact. * - * - * - * */ public class DbArtifact { diff --git a/hawkbit-core/src/main/java/org/eclipse/hawkbit/artifact/repository/model/DbArtifactHash.java b/hawkbit-core/src/main/java/org/eclipse/hawkbit/artifact/repository/model/DbArtifactHash.java index c16d3a620..5619a2292 100644 --- a/hawkbit-core/src/main/java/org/eclipse/hawkbit/artifact/repository/model/DbArtifactHash.java +++ b/hawkbit-core/src/main/java/org/eclipse/hawkbit/artifact/repository/model/DbArtifactHash.java @@ -11,9 +11,6 @@ package org.eclipse.hawkbit.artifact.repository.model; /** * Database representation of artifact hash. * - * - * - * */ public class DbArtifactHash { diff --git a/hawkbit-core/src/main/java/org/eclipse/hawkbit/tenancy/configuration/DurationHelper.java b/hawkbit-core/src/main/java/org/eclipse/hawkbit/tenancy/configuration/DurationHelper.java index 8e7c46223..5968f4420 100644 --- a/hawkbit-core/src/main/java/org/eclipse/hawkbit/tenancy/configuration/DurationHelper.java +++ b/hawkbit-core/src/main/java/org/eclipse/hawkbit/tenancy/configuration/DurationHelper.java @@ -36,8 +36,15 @@ public final class DurationHelper { this.max = max; } + /** + * Checks if the requested duration is in the defined min/max range. + * + * @param duration + * to checked + * @return true if in time range + */ public boolean isWithinRange(final Duration duration) { - return duration.compareTo(min) > 0 && duration.compareTo(max) < 0; + return duration.compareTo(min) >= 0 && duration.compareTo(max) <= 0; } } 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..402185be3 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 @@ -30,40 +30,60 @@ public enum TenantConfigurationKey { /** * boolean value {@code true} {@code false}. */ - AUTHENTICATION_MODE_HEADER_ENABLED("authentication.header.enabled", "hawkbit.server.ddi.security.authentication.header.enabled", Boolean.class, Boolean.FALSE.toString(), TenantConfigurationBooleanValidator.class), + AUTHENTICATION_MODE_HEADER_ENABLED("authentication.header.enabled", + "hawkbit.server.ddi.security.authentication.header.enabled", Boolean.class, Boolean.FALSE.toString(), + TenantConfigurationBooleanValidator.class), /** * */ - AUTHENTICATION_MODE_HEADER_AUTHORITY_NAME("authentication.header.authority", "hawkbit.server.ddi.security.authentication.header.authority", String.class, Boolean.FALSE.toString(), TenantConfigurationStringValidator.class), + AUTHENTICATION_MODE_HEADER_AUTHORITY_NAME("authentication.header.authority", + "hawkbit.server.ddi.security.authentication.header.authority", String.class, Boolean.FALSE.toString(), + TenantConfigurationStringValidator.class), /** * boolean value {@code true} {@code false}. */ - AUTHENTICATION_MODE_TARGET_SECURITY_TOKEN_ENABLED("authentication.targettoken.enabled", "hawkbit.server.ddi.security.authentication.targettoken.enabled", Boolean.class, Boolean.FALSE.toString(), TenantConfigurationBooleanValidator.class), + AUTHENTICATION_MODE_TARGET_SECURITY_TOKEN_ENABLED("authentication.targettoken.enabled", + "hawkbit.server.ddi.security.authentication.targettoken.enabled", Boolean.class, Boolean.FALSE.toString(), + TenantConfigurationBooleanValidator.class), /** * boolean value {@code true} {@code false}. */ - AUTHENTICATION_MODE_GATEWAY_SECURITY_TOKEN_ENABLED("authentication.gatewaytoken.enabled", "hawkbit.server.ddi.security.authentication.gatewaytoken.enabled", Boolean.class, Boolean.FALSE.toString(), TenantConfigurationBooleanValidator.class), + AUTHENTICATION_MODE_GATEWAY_SECURITY_TOKEN_ENABLED("authentication.gatewaytoken.enabled", + "hawkbit.server.ddi.security.authentication.gatewaytoken.enabled", Boolean.class, Boolean.FALSE.toString(), + TenantConfigurationBooleanValidator.class), /** * string value which holds the name of the security token key. */ - AUTHENTICATION_MODE_GATEWAY_SECURITY_TOKEN_NAME("authentication.gatewaytoken.name", "hawkbit.server.ddi.security.authentication.gatewaytoken.name", String.class, null, TenantConfigurationStringValidator.class), + AUTHENTICATION_MODE_GATEWAY_SECURITY_TOKEN_NAME("authentication.gatewaytoken.name", + "hawkbit.server.ddi.security.authentication.gatewaytoken.name", String.class, null, + TenantConfigurationStringValidator.class), /** * string value which holds the actual security-key of the gateway security * token. */ - AUTHENTICATION_MODE_GATEWAY_SECURITY_TOKEN_KEY("authentication.gatewaytoken.key", "hawkbit.server.ddi.security.authentication.gatewaytoken.key", String.class, null, TenantConfigurationStringValidator.class), + AUTHENTICATION_MODE_GATEWAY_SECURITY_TOKEN_KEY("authentication.gatewaytoken.key", + "hawkbit.server.ddi.security.authentication.gatewaytoken.key", String.class, null, + TenantConfigurationStringValidator.class), /** * string value which holds the polling time interval in the format HH:mm:ss */ - POLLING_TIME_INTERVAL("pollingOverdueTime", "hawkbit.controller.pollingOverdueTime", String.class, null, TenantConfigurationPollingDurationValidator.class), + POLLING_TIME_INTERVAL("pollingTime", "hawkbit.controller.pollingTime", String.class, null, + TenantConfigurationPollingDurationValidator.class), /** * 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("pollingOverdueTime", "hawkbit.controller.pollingOverdueTime", 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-core/src/main/java/org/eclipse/hawkbit/tenancy/configuration/validator/TenantConfigurationPollingDurationValidator.java b/hawkbit-core/src/main/java/org/eclipse/hawkbit/tenancy/configuration/validator/TenantConfigurationPollingDurationValidator.java index 11c9666e8..376ba8877 100644 --- a/hawkbit-core/src/main/java/org/eclipse/hawkbit/tenancy/configuration/validator/TenantConfigurationPollingDurationValidator.java +++ b/hawkbit-core/src/main/java/org/eclipse/hawkbit/tenancy/configuration/validator/TenantConfigurationPollingDurationValidator.java @@ -39,6 +39,8 @@ public class TenantConfigurationPollingDurationValidator implements TenantConfig } @Override + // Exception squid:S1166 - Hide origin exception + @SuppressWarnings({ "squid:S1166" }) public void validate(final Object tenantConfigurationObject) { TenantConfigurationValidator.super.validate(tenantConfigurationObject); final String tenantConfigurationString = (String) tenantConfigurationObject; diff --git a/hawkbit-ddi-api/README.md b/hawkbit-ddi-api/README.md new file mode 100644 index 000000000..b47b74895 --- /dev/null +++ b/hawkbit-ddi-api/README.md @@ -0,0 +1,12 @@ +# Eclipse.IoT hawkBit - DDI API + +The Direct Device Integration (DDI) API is used by devices for communicating with the HawkBit Update Server through HTTP. + +# Compile + +#### Build hawkbit-ddi-api + +``` +$ cd hawkbit/hawkbit-ddi-api +$ mvn clean install +``` diff --git a/hawkbit-ddi-api/pom.xml b/hawkbit-ddi-api/pom.xml new file mode 100644 index 000000000..969f0d930 --- /dev/null +++ b/hawkbit-ddi-api/pom.xml @@ -0,0 +1,45 @@ + + + + 4.0.0 + + org.eclipse.hawkbit + hawkbit-parent + 0.2.0-SNAPSHOT + + hawkbit-ddi-api + hawkBit :: DDI API + + + + org.springframework.hateoas + spring-hateoas + + + com.fasterxml.jackson.core + jackson-annotations + + + javax.validation + validation-api + + + org.hibernate + hibernate-validator + + + org.springframework.security + spring-security-web + + + diff --git a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/model/ActionFeedback.java b/hawkbit-ddi-api/src/main/java/org/eclipse/hawkbit/ddi/json/model/DdiActionFeedback.java similarity index 60% rename from hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/model/ActionFeedback.java rename to hawkbit-ddi-api/src/main/java/org/eclipse/hawkbit/ddi/json/model/DdiActionFeedback.java index 3fe511e49..cbb45b788 100644 --- a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/model/ActionFeedback.java +++ b/hawkbit-ddi-api/src/main/java/org/eclipse/hawkbit/ddi/json/model/DdiActionFeedback.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.controller.model; +package org.eclipse.hawkbit.ddi.json.model; import javax.validation.constraints.NotNull; @@ -15,16 +15,16 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; /** - * *

- * After the SP Target has executed an action, received by a GET(URL) request it - * reports the completion of it to the SP Server with a action status message, - * i.e. with a PUT message to the feedback channel, i.e. PUT URL/feedback. This - * message could be used not only at the end of execution but also as status - * updates during a longer lasting execution period. The format of each action - * answer message is defined below at each action. But it is expected, that the - * contents of the message answers have all a similar structure: The content - * starts with a generic header and additional elements. * + * After the HawkBit Target has executed an action, received by a GET(URL) + * request it reports the completion of it to the HawkBit Server with a action + * status message, i.e. with a PUT message to the feedback channel, i.e. PUT + * URL/feedback. This message could be used not only at the end of execution but + * also as status updates during a longer lasting execution period. The format + * of each action answer message is defined below at each action. But it is + * expected, that the contents of the message answers have all a similar + * structure: The content starts with a generic header and additional elements. + * * *

* *

@@ -35,12 +35,12 @@ import com.fasterxml.jackson.annotation.JsonProperty; * */ @JsonIgnoreProperties(ignoreUnknown = true) -public class ActionFeedback { +public class DdiActionFeedback { private final Long id; private final String time; @NotNull - private final Status status; + private final DdiStatus status; /** * Constructor. @@ -53,8 +53,8 @@ public class ActionFeedback { * is the feedback itself */ @JsonCreator - public ActionFeedback(@JsonProperty("id") final Long id, @JsonProperty("time") final String time, - @JsonProperty("status") final Status status) { + public DdiActionFeedback(@JsonProperty("id") final Long id, @JsonProperty("time") final String time, + @JsonProperty("status") final DdiStatus status) { this.id = id; this.time = time; this.status = status; @@ -68,15 +68,10 @@ public class ActionFeedback { return time; } - public Status getStatus() { + public DdiStatus getStatus() { return status; } - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ @Override public String toString() { return "ActionFeedback [id=" + id + ", time=" + time + ", status=" + status + "]"; diff --git a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/model/Artifact.java b/hawkbit-ddi-api/src/main/java/org/eclipse/hawkbit/ddi/json/model/DdiArtifact.java similarity index 61% rename from hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/model/Artifact.java rename to hawkbit-ddi-api/src/main/java/org/eclipse/hawkbit/ddi/json/model/DdiArtifact.java index b995491d9..5fc911946 100644 --- a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/model/Artifact.java +++ b/hawkbit-ddi-api/src/main/java/org/eclipse/hawkbit/ddi/json/model/DdiArtifact.java @@ -6,72 +6,50 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.controller.model; +package org.eclipse.hawkbit.ddi.json.model; import javax.validation.constraints.NotNull; -import org.eclipse.hawkbit.rest.resource.model.artifact.ArtifactHash; import org.springframework.hateoas.ResourceSupport; import com.fasterxml.jackson.annotation.JsonProperty; /** - * Download information for all artifacts related to a specific {@link Chunk}. - * + * Download information for all artifacts related to a specific {@link DdiChunk} + * . */ -public class Artifact extends ResourceSupport { +public class DdiArtifact extends ResourceSupport { @NotNull @JsonProperty private String filename; @JsonProperty - private ArtifactHash hashes; + private DdiArtifactHash hashes; @JsonProperty private Long size; - /** - * @return the hashes - */ - public ArtifactHash getHashes() { + public DdiArtifactHash getHashes() { return hashes; } - /** - * @param hashes - * the hashes to set - */ - public void setHashes(final ArtifactHash hashes) { + public void setHashes(final DdiArtifactHash hashes) { this.hashes = hashes; } - /** - * @return the fileName - */ public String getFilename() { return filename; } - /** - * @param fileName - * the fileName to set - */ public void setFilename(final String fileName) { filename = fileName; } - /** - * @return the size - */ public Long getSize() { return size; } - /** - * @param size - * the size to set - */ public void setSize(final Long size) { this.size = size; } diff --git a/hawkbit-ddi-api/src/main/java/org/eclipse/hawkbit/ddi/json/model/DdiArtifactHash.java b/hawkbit-ddi-api/src/main/java/org/eclipse/hawkbit/ddi/json/model/DdiArtifactHash.java new file mode 100644 index 000000000..9541055f8 --- /dev/null +++ b/hawkbit-ddi-api/src/main/java/org/eclipse/hawkbit/ddi/json/model/DdiArtifactHash.java @@ -0,0 +1,57 @@ +/** + * 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.ddi.json.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Hashes for given Artifact. + * + * + */ +public class DdiArtifactHash { + + @JsonProperty + private String sha1; + + @JsonProperty + private String md5; + + /** + * Default constructor. + */ + public DdiArtifactHash() { + } + + /** + * Public constructor. + * + * @param sha1 + * @param md5 + */ + public DdiArtifactHash(final String sha1, final String md5) { + this.sha1 = sha1; + this.md5 = md5; + } + + /** + * @return the sha1 + */ + public String getSha1() { + return sha1; + } + + /** + * @return the md5 + */ + public String getMd5() { + return md5; + } + +} diff --git a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/model/Cancel.java b/hawkbit-ddi-api/src/main/java/org/eclipse/hawkbit/ddi/json/model/DdiCancel.java similarity index 66% rename from hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/model/Cancel.java rename to hawkbit-ddi-api/src/main/java/org/eclipse/hawkbit/ddi/json/model/DdiCancel.java index 77055828f..c117dea14 100644 --- a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/model/Cancel.java +++ b/hawkbit-ddi-api/src/main/java/org/eclipse/hawkbit/ddi/json/model/DdiCancel.java @@ -6,53 +6,42 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.controller.model; +package org.eclipse.hawkbit.ddi.json.model; import javax.validation.constraints.NotNull; /** * Cancel action to be provided to the target. - * */ -public class Cancel { +public class DdiCancel { + private final String id; @NotNull - private final CancelActionToStop cancelAction; + private final DdiCancelActionToStop cancelAction; /** * Parameterized constructor. * * @param id - * of the {@link CancelAction} + * of the cancel action * @param cancelAction * the action */ - public Cancel(final String id, final CancelActionToStop cancelAction) { + public DdiCancel(final String id, final DdiCancelActionToStop cancelAction) { super(); this.id = id; this.cancelAction = cancelAction; } - /** - * @return the id - */ public String getId() { return id; } - /** - * @return the cancelAction - */ - public CancelActionToStop getCancelAction() { + public DdiCancelActionToStop getCancelAction() { return cancelAction; } - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ @Override public String toString() { return "Cancel [id=" + id + ", cancelAction=" + cancelAction + "]"; diff --git a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/model/CancelActionToStop.java b/hawkbit-ddi-api/src/main/java/org/eclipse/hawkbit/ddi/json/model/DdiCancelActionToStop.java similarity index 62% rename from hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/model/CancelActionToStop.java rename to hawkbit-ddi-api/src/main/java/org/eclipse/hawkbit/ddi/json/model/DdiCancelActionToStop.java index 9b954aa57..3ab8d6b55 100644 --- a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/model/CancelActionToStop.java +++ b/hawkbit-ddi-api/src/main/java/org/eclipse/hawkbit/ddi/json/model/DdiCancelActionToStop.java @@ -6,17 +6,14 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.controller.model; +package org.eclipse.hawkbit.ddi.json.model; import javax.validation.constraints.NotNull; -import org.eclipse.hawkbit.repository.model.Action; - /** - * The {@link Action} that has to be stopped by the target. - * + * The action that has to be stopped by the target. */ -public class CancelActionToStop { +public class DdiCancelActionToStop { @NotNull private final String stopId; @@ -25,25 +22,17 @@ public class CancelActionToStop { * Parameterized constructor. * * @param stopId - * ID of the {@link Action} to be stoppedW + * ID of the action to be stoppedW */ - public CancelActionToStop(final String stopId) { + public DdiCancelActionToStop(final String stopId) { super(); this.stopId = stopId; } - /** - * @return the stopId - */ public String getStopId() { return stopId; } - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ @Override public String toString() { return "CancelAction [stopId=" + stopId + "]"; diff --git a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/model/Chunk.java b/hawkbit-ddi-api/src/main/java/org/eclipse/hawkbit/ddi/json/model/DdiChunk.java similarity index 70% rename from hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/model/Chunk.java rename to hawkbit-ddi-api/src/main/java/org/eclipse/hawkbit/ddi/json/model/DdiChunk.java index 66809bfbb..78de8591d 100644 --- a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/model/Chunk.java +++ b/hawkbit-ddi-api/src/main/java/org/eclipse/hawkbit/ddi/json/model/DdiChunk.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.controller.model; +package org.eclipse.hawkbit.ddi.json.model; import java.util.List; @@ -14,20 +14,23 @@ import javax.validation.constraints.NotNull; /** * Deployment chunks. - * */ -public class Chunk { +public class DdiChunk { @NotNull - private final String part; + private String part; @NotNull - private final String version; + private String version; @NotNull - private final String name; + private String name; - private final List artifacts; + private List artifacts; + + public DdiChunk() { + + } /** * Constructor. @@ -40,9 +43,8 @@ public class Chunk { * of the artifact * @param artifacts * download information - * */ - public Chunk(final String part, final String version, final String name, final List artifacts) { + public DdiChunk(final String part, final String version, final String name, final List artifacts) { super(); this.part = part; this.version = version; @@ -58,17 +60,11 @@ public class Chunk { return version; } - /** - * @return the name - */ public String getName() { return name; } - /** - * @return the artifacts - */ - public List getArtifacts() { + public List getArtifacts() { return artifacts; } diff --git a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/model/Config.java b/hawkbit-ddi-api/src/main/java/org/eclipse/hawkbit/ddi/json/model/DdiConfig.java similarity index 51% rename from hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/model/Config.java rename to hawkbit-ddi-api/src/main/java/org/eclipse/hawkbit/ddi/json/model/DdiConfig.java index 62907b26d..5ec1b4dde 100644 --- a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/model/Config.java +++ b/hawkbit-ddi-api/src/main/java/org/eclipse/hawkbit/ddi/json/model/DdiConfig.java @@ -6,15 +6,22 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.controller.model; +package org.eclipse.hawkbit.ddi.json.model; + +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; /** * Standard configuration for the target. - * */ -public class Config { +@JsonInclude(Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public class DdiConfig { - private final Polling polling; + @JsonProperty + private DdiPolling polling; /** * Constructor. @@ -22,12 +29,16 @@ public class Config { * @param polling * configuration of the SP target */ - public Config(final Polling polling) { + public DdiConfig(final DdiPolling polling) { super(); this.polling = polling; } - public Polling getPolling() { + public DdiConfig() { + + } + + public DdiPolling getPolling() { return polling; } diff --git a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/model/ConfigData.java b/hawkbit-ddi-api/src/main/java/org/eclipse/hawkbit/ddi/json/model/DdiConfigData.java similarity index 75% rename from hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/model/ConfigData.java rename to hawkbit-ddi-api/src/main/java/org/eclipse/hawkbit/ddi/json/model/DdiConfigData.java index b7c330167..a16ddf064 100644 --- a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/model/ConfigData.java +++ b/hawkbit-ddi-api/src/main/java/org/eclipse/hawkbit/ddi/json/model/DdiConfigData.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.controller.model; +package org.eclipse.hawkbit.ddi.json.model; import java.util.Map; @@ -17,9 +17,8 @@ import com.fasterxml.jackson.annotation.JsonProperty; /** * Feedback channel for ConfigData action. - * */ -public class ConfigData extends ActionFeedback { +public class DdiConfigData extends DdiActionFeedback { @NotEmpty private final Map data; @@ -35,28 +34,19 @@ public class ConfigData extends ActionFeedback { * is the feedback itself * @param data * contains the attributes. - * */ @JsonCreator - public ConfigData(@JsonProperty(value = "id") final Long id, @JsonProperty(value = "time") final String time, - @JsonProperty(value = "status") final Status status, + public DdiConfigData(@JsonProperty(value = "id") final Long id, @JsonProperty(value = "time") final String time, + @JsonProperty(value = "status") final DdiStatus status, @JsonProperty(value = "data") final Map data) { super(id, time, status); this.data = data; } - /** - * @return the data - */ public Map getData() { return data; } - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ @Override public String toString() { return "ConfigData [data=" + data + ", toString()=" + super.toString() + "]"; diff --git a/hawkbit-ddi-api/src/main/java/org/eclipse/hawkbit/ddi/json/model/DdiControllerBase.java b/hawkbit-ddi-api/src/main/java/org/eclipse/hawkbit/ddi/json/model/DdiControllerBase.java new file mode 100644 index 000000000..3f160157c --- /dev/null +++ b/hawkbit-ddi-api/src/main/java/org/eclipse/hawkbit/ddi/json/model/DdiControllerBase.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.ddi.json.model; + +import org.springframework.hateoas.ResourceSupport; + +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; + +/** + * {@link DdiControllerBase} resource content. + */ +@JsonInclude(Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public class DdiControllerBase extends ResourceSupport { + + @JsonProperty + private DdiConfig config; + + /** + * Constructor. + * + * @param config + * configuration of the SP target + */ + public DdiControllerBase(final DdiConfig config) { + super(); + this.config = config; + } + + public DdiControllerBase() { + + } + + public DdiConfig getConfig() { + return config; + } + +} diff --git a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/model/Deployment.java b/hawkbit-ddi-api/src/main/java/org/eclipse/hawkbit/ddi/json/model/DdiDeployment.java similarity index 72% rename from hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/model/Deployment.java rename to hawkbit-ddi-api/src/main/java/org/eclipse/hawkbit/ddi/json/model/DdiDeployment.java index 57ead963c..f72083d7a 100644 --- a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/model/Deployment.java +++ b/hawkbit-ddi-api/src/main/java/org/eclipse/hawkbit/ddi/json/model/DdiDeployment.java @@ -6,25 +6,26 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.controller.model; +package org.eclipse.hawkbit.ddi.json.model; import java.util.List; -import org.eclipse.hawkbit.repository.model.Action; - import com.fasterxml.jackson.annotation.JsonValue; /** - * Detailed {@link UpdateAction} information. - * + * Detailed update action information. */ -public class Deployment { +public class DdiDeployment { - private final HandlingType download; + private HandlingType download; - private final HandlingType update; + private HandlingType update; - private final List chunks; + private List chunks; + + public DdiDeployment() { + + } /** * Constructor. @@ -36,7 +37,7 @@ public class Deployment { * @param chunks * to handle. */ - public Deployment(final HandlingType download, final HandlingType update, final List chunks) { + public DdiDeployment(final HandlingType download, final HandlingType update, final List chunks) { super(); this.download = download; this.update = update; @@ -51,15 +52,15 @@ public class Deployment { return update; } - public List getChunks() { + public List getChunks() { return chunks; } /** - * The handling type for the update {@link Action}. - * + * The handling type for the update action. */ public enum HandlingType { + /** * Not necessary for the command. */ @@ -81,20 +82,12 @@ public class Deployment { this.name = name; } - /** - * @return the name - */ @JsonValue public String getName() { return name; } } - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ @Override public String toString() { return "Deployment [download=" + download + ", update=" + update + ", chunks=" + chunks + "]"; diff --git a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/model/DeploymentBase.java b/hawkbit-ddi-api/src/main/java/org/eclipse/hawkbit/ddi/json/model/DdiDeploymentBase.java similarity index 66% rename from hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/model/DeploymentBase.java rename to hawkbit-ddi-api/src/main/java/org/eclipse/hawkbit/ddi/json/model/DdiDeploymentBase.java index ea3e1caa5..8f1116b1b 100644 --- a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/model/DeploymentBase.java +++ b/hawkbit-ddi-api/src/main/java/org/eclipse/hawkbit/ddi/json/model/DdiDeploymentBase.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.controller.model; +package org.eclipse.hawkbit.ddi.json.model; import javax.validation.constraints.NotNull; @@ -15,40 +15,38 @@ import org.springframework.hateoas.ResourceSupport; import com.fasterxml.jackson.annotation.JsonProperty; /** - * {@link UpdateAction} resource. - * + * Update action resource. */ -public class DeploymentBase extends ResourceSupport { +public class DdiDeploymentBase extends ResourceSupport { @JsonProperty("id") @NotNull - private final String deplyomentId; + private String deplyomentId; @NotNull - private final Deployment deployment; + private DdiDeployment deployment; /** * Constructor. * * @param id - * of the {@link UpdateAction} + * of the update action * @param deployment * details. */ - public DeploymentBase(final String id, final Deployment deployment) { + public DdiDeploymentBase(final String id, final DdiDeployment deployment) { deplyomentId = id; this.deployment = deployment; } - public Deployment getDeployment() { + public DdiDeploymentBase() { + + } + + public DdiDeployment getDeployment() { return deployment; } - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ @Override public String toString() { return "DeploymentBase [id=" + deplyomentId + ", deployment=" + deployment + "]"; diff --git a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/model/Polling.java b/hawkbit-ddi-api/src/main/java/org/eclipse/hawkbit/ddi/json/model/DdiPolling.java similarity index 53% rename from hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/model/Polling.java rename to hawkbit-ddi-api/src/main/java/org/eclipse/hawkbit/ddi/json/model/DdiPolling.java index 4e0854d98..489178be8 100644 --- a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/model/Polling.java +++ b/hawkbit-ddi-api/src/main/java/org/eclipse/hawkbit/ddi/json/model/DdiPolling.java @@ -6,15 +6,22 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.controller.model; +package org.eclipse.hawkbit.ddi.json.model; + +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; /** * Polling interval for the SP target. - * */ -public class Polling { +@JsonInclude(Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public class DdiPolling { - private final String sleep; + @JsonProperty + private String sleep; /** * Constructor. @@ -22,11 +29,14 @@ public class Polling { * @param sleep * between polls */ - public Polling(final String sleep) { + public DdiPolling(final String sleep) { super(); this.sleep = sleep; } + public DdiPolling() { + } + public String getSleep() { return sleep; } diff --git a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/model/Progress.java b/hawkbit-ddi-api/src/main/java/org/eclipse/hawkbit/ddi/json/model/DdiProgress.java similarity index 81% rename from hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/model/Progress.java rename to hawkbit-ddi-api/src/main/java/org/eclipse/hawkbit/ddi/json/model/DdiProgress.java index 096231c7b..cf73fc5c0 100644 --- a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/model/Progress.java +++ b/hawkbit-ddi-api/src/main/java/org/eclipse/hawkbit/ddi/json/model/DdiProgress.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.controller.model; +package org.eclipse.hawkbit.ddi.json.model; import javax.validation.constraints.NotNull; @@ -16,9 +16,8 @@ import com.fasterxml.jackson.annotation.JsonProperty; /** * Action fulfillment progress by means of gives the achieved amount of maximal * of possible levels. - * */ -public class Progress { +public class DdiProgress { @NotNull private final Integer cnt; @@ -34,7 +33,7 @@ public class Progress { * maximum levels */ @JsonCreator - public Progress(@JsonProperty("cnt") final Integer cnt, @JsonProperty("of") final Integer of) { + public DdiProgress(@JsonProperty("cnt") final Integer cnt, @JsonProperty("of") final Integer of) { super(); this.cnt = cnt; this.of = of; @@ -48,11 +47,6 @@ public class Progress { return of; } - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ @Override public String toString() { return "Progress [cnt=" + cnt + ", of=" + of + "]"; diff --git a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/model/Result.java b/hawkbit-ddi-api/src/main/java/org/eclipse/hawkbit/ddi/json/model/DdiResult.java similarity index 81% rename from hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/model/Result.java rename to hawkbit-ddi-api/src/main/java/org/eclipse/hawkbit/ddi/json/model/DdiResult.java index b5dd22aaa..36f0d134c 100644 --- a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/model/Result.java +++ b/hawkbit-ddi-api/src/main/java/org/eclipse/hawkbit/ddi/json/model/DdiResult.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.controller.model; +package org.eclipse.hawkbit.ddi.json.model; import org.hibernate.validator.constraints.NotEmpty; @@ -17,15 +17,13 @@ import com.fasterxml.jackson.annotation.JsonValue; /** * Result information of the action progress which can by an intermediate or * final update. - * - * */ -public class Result { +public class DdiResult { @NotEmpty private final FinalResult finished; - private final Progress progress; + private final DdiProgress progress; /** * Constructor. @@ -36,8 +34,8 @@ public class Result { * if not yet finished */ @JsonCreator - public Result(@JsonProperty("finished") final FinalResult finished, - @JsonProperty("progress") final Progress progress) { + public DdiResult(@JsonProperty("finished") final FinalResult finished, + @JsonProperty("progress") final DdiProgress progress) { super(); this.finished = finished; this.progress = progress; @@ -47,7 +45,7 @@ public class Result { return finished; } - public Progress getProgress() { + public DdiProgress getProgress() { return progress; } @@ -77,21 +75,12 @@ public class Result { this.name = name; } - /** - * @return the name - */ @JsonValue public String getName() { return name; } - } - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ @Override public String toString() { return "Result [finished=" + finished + ", progress=" + progress + "]"; diff --git a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/model/Status.java b/hawkbit-ddi-api/src/main/java/org/eclipse/hawkbit/ddi/json/model/DdiStatus.java similarity index 84% rename from hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/model/Status.java rename to hawkbit-ddi-api/src/main/java/org/eclipse/hawkbit/ddi/json/model/DdiStatus.java index df1622e31..cb9b57187 100644 --- a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/model/Status.java +++ b/hawkbit-ddi-api/src/main/java/org/eclipse/hawkbit/ddi/json/model/DdiStatus.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.controller.model; +package org.eclipse.hawkbit.ddi.json.model; import java.util.List; @@ -18,15 +18,14 @@ import com.fasterxml.jackson.annotation.JsonValue; /** * Details status information concerning the action processing. - * */ -public class Status { +public class DdiStatus { @NotNull private final ExecutionStatus execution; @NotNull - private final Result result; + private final DdiResult result; private final List details; @@ -41,8 +40,8 @@ public class Status { * as optional addition */ @JsonCreator - public Status(@JsonProperty("execution") final ExecutionStatus execution, - @JsonProperty("result") final Result result, @JsonProperty("details") final List details) { + public DdiStatus(@JsonProperty("execution") final ExecutionStatus execution, + @JsonProperty("result") final DdiResult result, @JsonProperty("details") final List details) { super(); this.execution = execution; this.result = result; @@ -53,7 +52,7 @@ public class Status { return execution; } - public Result getResult() { + public DdiResult getResult() { return result; } @@ -103,20 +102,12 @@ public class Status { this.name = name; } - /** - * @return the name - */ @JsonValue public String getName() { return name; } } - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ @Override public String toString() { return "Status [execution=" + execution + ", result=" + result + ", details=" + details + "]"; diff --git a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/ControllerConstants.java b/hawkbit-ddi-api/src/main/java/org/eclipse/hawkbit/ddi/rest/api/DdiRestConstants.java similarity index 57% rename from hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/ControllerConstants.java rename to hawkbit-ddi-api/src/main/java/org/eclipse/hawkbit/ddi/rest/api/DdiRestConstants.java index fd7f125c5..25be5b1f8 100644 --- a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/ControllerConstants.java +++ b/hawkbit-ddi-api/src/main/java/org/eclipse/hawkbit/ddi/rest/api/DdiRestConstants.java @@ -6,24 +6,18 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.controller; +package org.eclipse.hawkbit.ddi.rest.api; /** - * - * - * + * Constants for the direct device integration rest resources. */ -public final class ControllerConstants { +public final class DdiRestConstants { + /** * The base URL mapping of the direct device integration rest resources. */ public static final String BASE_V1_REQUEST_MAPPING = "/{tenant}/controller/v1"; - /** - * The base URL mapping of the artifact repository rest resources. - */ - public static final String ARTIFACTS_V1_REQUEST_MAPPING = "/{tenant}/controller/artifacts/v1"; - /** * Deployment action resources. */ @@ -37,30 +31,19 @@ public final class ControllerConstants { /** * Feedback channel. */ - static final String FEEDBACK = "feedback"; + public static final String FEEDBACK = "feedback"; + + /** + * File suffix for MDH hash download (see Linux md5sum). + */ + public static final String ARTIFACT_MD5_DWNL_SUFFIX = ".MD5SUM"; /** * Config data action resources. */ public static final String CONFIG_DATA_ACTION = "configData"; - /** - * The artifact URL mapping rest resource. - */ - static final String ARTIFACT_DOWNLOAD = "artifact"; - - /** - * The artifact by filename URL mapping rest resource. - */ - static final String ARTIFACT_DOWNLOAD_BY_FILENAME = "/filename"; - - /** - * File suffix for MDH hash download (see Linux md5sum). - */ - static final String ARTIFACT_MD5_DWNL_SUFFIX = ".MD5SUM"; - - // constant class, private constructor. - private ControllerConstants() { - + private DdiRestConstants() { + // constant class, private constructor. } } diff --git a/hawkbit-ddi-api/src/main/java/org/eclipse/hawkbit/ddi/rest/api/DdiRootControllerRestApi.java b/hawkbit-ddi-api/src/main/java/org/eclipse/hawkbit/ddi/rest/api/DdiRootControllerRestApi.java new file mode 100644 index 000000000..67436c3ca --- /dev/null +++ b/hawkbit-ddi-api/src/main/java/org/eclipse/hawkbit/ddi/rest/api/DdiRootControllerRestApi.java @@ -0,0 +1,212 @@ +/** + * 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.ddi.rest.api; + +import java.io.InputStream; +import java.lang.annotation.Target; +import java.util.List; + +import javax.validation.Valid; + +import org.eclipse.hawkbit.ddi.json.model.DdiActionFeedback; +import org.eclipse.hawkbit.ddi.json.model.DdiArtifact; +import org.eclipse.hawkbit.ddi.json.model.DdiCancel; +import org.eclipse.hawkbit.ddi.json.model.DdiConfigData; +import org.eclipse.hawkbit.ddi.json.model.DdiControllerBase; +import org.eclipse.hawkbit.ddi.json.model.DdiDeploymentBase; +import org.hibernate.validator.constraints.NotEmpty; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; + +/** + * REST resource handling for root controller CRUD operations. + */ +@RequestMapping(DdiRestConstants.BASE_V1_REQUEST_MAPPING) +public interface DdiRootControllerRestApi { + + /** + * Returns all artifacts of a given software module and target. + * + * @param targetid + * of the target that matches to controller id + * @param softwareModuleId + * of the software module + * @return the response + */ + @RequestMapping(method = RequestMethod.GET, value = "/{targetid}/softwaremodules/{softwareModuleId}/artifacts", produces = { + "application/hal+json", MediaType.APPLICATION_JSON_VALUE }) + ResponseEntity> getSoftwareModulesArtifacts( + @PathVariable("targetid") final String targetid, + @PathVariable("softwareModuleId") final Long softwareModuleId); + + /** + * Root resource for an individual {@link Target}. + * + * @param targetid + * of the target that matches to controller id + * @param request + * the HTTP request injected by spring + * @return the response + */ + @RequestMapping(method = RequestMethod.GET, value = "/{targetid}", produces = { "application/hal+json", + MediaType.APPLICATION_JSON_VALUE }) + ResponseEntity getControllerBase(@PathVariable("targetid") final String targetid); + + /** + * Handles GET {@link DdiArtifact} download request. This could be full or + * partial (as specified by RFC7233 (Range Requests)) download request. + * + * @param targetid + * of the related target + * @param softwareModuleId + * of the parent software module + * @param fileName + * of the related local artifact + * @param response + * of the servlet + * @param request + * from the client + * + * @return response of the servlet which in case of success is status code + * {@link HttpStatus#OK} or in case of partial download + * {@link HttpStatus#PARTIAL_CONTENT}. + */ + @RequestMapping(method = RequestMethod.GET, value = "/{targetid}/softwaremodules/{softwareModuleId}/artifacts/{fileName}") + ResponseEntity downloadArtifact(@PathVariable("targetid") final String targetid, + @PathVariable("softwareModuleId") final Long softwareModuleId, + @PathVariable("fileName") final String fileName); + + /** + * Handles GET {@link DdiArtifact} MD5 checksum file download request. + * + * @param targetid + * of the related target + * @param softwareModuleId + * of the parent software module + * @param fileName + * of the related local artifact + * @param response + * of the servlet + * @param request + * the HTTP request injected by spring + * + * @return {@link ResponseEntity} with status {@link HttpStatus#OK} if + * successful + */ + @RequestMapping(method = RequestMethod.GET, value = "/{targetid}/softwaremodules/{softwareModuleId}/artifacts/{fileName}" + + DdiRestConstants.ARTIFACT_MD5_DWNL_SUFFIX, produces = MediaType.TEXT_PLAIN_VALUE) + ResponseEntity downloadArtifactMd5(@PathVariable("targetid") final String targetid, + @PathVariable("softwareModuleId") final Long softwareModuleId, + @PathVariable("fileName") final String fileName); + + /** + * Resource for software module. + * + * @param targetid + * of the target that matches to controller id + * @param actionId + * of the {@link DdiDeploymentBase} that matches to active + * actions. + * @param resource + * an hashcode of the resource which indicates if the action has + * been changed, e.g. from 'soft' to 'force' and the eTag needs + * to be re-generated + * @param request + * the HTTP request injected by spring + * @return the response + */ + @RequestMapping(value = "/{targetid}/" + DdiRestConstants.DEPLOYMENT_BASE_ACTION + + "/{actionId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) + ResponseEntity getControllerBasedeploymentAction( + @PathVariable("targetid") @NotEmpty final String targetid, + @PathVariable("actionId") @NotEmpty final Long actionId, + @RequestParam(value = "c", required = false, defaultValue = "-1") final int resource); + + /** + * This is the feedback channel for the {@link DdiDeploymentBase} action. + * + * @param feedback + * to provide + * @param targetid + * of the target that matches to controller id + * @param actionId + * of the action we have feedback for + * @param request + * the HTTP request injected by spring + * + * @return the response + */ + @RequestMapping(value = "/{targetid}/" + DdiRestConstants.DEPLOYMENT_BASE_ACTION + "/{actionId}/" + + DdiRestConstants.FEEDBACK, method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE) + ResponseEntity postBasedeploymentActionFeedback(@Valid @RequestBody final DdiActionFeedback feedback, + @PathVariable("targetid") final String targetid, @PathVariable("actionId") @NotEmpty final Long actionId); + + /** + * This is the feedback channel for the config data action. + * + * @param configData + * as body + * @param targetid + * to provide data for + * @param request + * the HTTP request injected by spring + * + * @return status of the request + */ + @RequestMapping(value = "/{targetid}/" + + DdiRestConstants.CONFIG_DATA_ACTION, method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE) + ResponseEntity putConfigData(@Valid @RequestBody final DdiConfigData configData, + @PathVariable("targetid") final String targetid); + + /** + * RequestMethod.GET method for the {@link DdiCancel} action. + * + * @param targetid + * ID of the calling target + * @param actionId + * of the action + * @param request + * the HTTP request injected by spring + * + * @return the {@link DdiCancel} response + */ + @RequestMapping(value = "/{targetid}/" + DdiRestConstants.CANCEL_ACTION + + "/{actionId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) + ResponseEntity getControllerCancelAction(@PathVariable("targetid") @NotEmpty final String targetid, + @PathVariable("actionId") @NotEmpty final Long actionId); + + /** + * RequestMethod.POST method receiving the {@link DdiActionFeedback} from + * the target. + * + * @param feedback + * the {@link DdiActionFeedback} from the target. + * @param targetid + * the ID of the calling target + * @param actionId + * of the action we have feedback for + * @param request + * the HTTP request injected by spring + * + * @return the {@link DdiActionFeedback} response + */ + + @RequestMapping(value = "/{targetid}/" + DdiRestConstants.CANCEL_ACTION + "/{actionId}/" + + DdiRestConstants.FEEDBACK, method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE) + ResponseEntity postCancelActionFeedback(@Valid @RequestBody final DdiActionFeedback feedback, + @PathVariable("targetid") @NotEmpty final String targetid, + @PathVariable("actionId") @NotEmpty final Long actionId); + +} diff --git a/hawkbit-ddi-dl-api/README.md b/hawkbit-ddi-dl-api/README.md new file mode 100644 index 000000000..703ef2916 --- /dev/null +++ b/hawkbit-ddi-dl-api/README.md @@ -0,0 +1,12 @@ +# Eclipse.IoT hawkBit - DDI Download API + +This module is part of the Direct Device Integration (DDI) API and is used by devices/targets for downloading artifacts through HTTP. + +# Compile + +#### Build hawkbit-ddi-dl-api + +``` +$ cd hawkbit/hawkbit-ddi-dl-api +$ mvn clean install +``` diff --git a/hawkbit-ddi-dl-api/pom.xml b/hawkbit-ddi-dl-api/pom.xml new file mode 100644 index 000000000..704267927 --- /dev/null +++ b/hawkbit-ddi-dl-api/pom.xml @@ -0,0 +1,28 @@ + + + 4.0.0 + + org.eclipse.hawkbit + hawkbit-parent + 0.2.0-SNAPSHOT + + hawkbit-ddi-dl-api + hawkBit :: DDI Download Server (DL) API + + + + org.springframework.security + spring-security-web + + + diff --git a/hawkbit-ddi-dl-api/src/main/java/org/eclipse/hawkbit/ddi/dl/rest/api/DdiDlArtifactStoreControllerRestApi.java b/hawkbit-ddi-dl-api/src/main/java/org/eclipse/hawkbit/ddi/dl/rest/api/DdiDlArtifactStoreControllerRestApi.java new file mode 100644 index 000000000..53d5940fe --- /dev/null +++ b/hawkbit-ddi-dl-api/src/main/java/org/eclipse/hawkbit/ddi/dl/rest/api/DdiDlArtifactStoreControllerRestApi.java @@ -0,0 +1,59 @@ +/** + * 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.ddi.dl.rest.api; + +import java.io.InputStream; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.web.bind.annotation.AuthenticationPrincipal; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; + +/** + * REST resource handling for artifact download operations. + */ +@RequestMapping(DdiDlRestConstants.ARTIFACTS_V1_REQUEST_MAPPING) +public interface DdiDlArtifactStoreControllerRestApi { + + /** + * Handles GET download request. This could be full or partial download + * request. + * + * @param fileName + * to search for + * @param targetid + * of authenticated target + * + * @return response of the servlet which in case of success is status code + * {@link HttpStatus#OK} or in case of partial download + * {@link HttpStatus#PARTIAL_CONTENT}. + */ + @RequestMapping(method = RequestMethod.GET, value = DdiDlRestConstants.ARTIFACT_DOWNLOAD_BY_FILENAME + + "/{fileName}") + @ResponseBody + public ResponseEntity downloadArtifactByFilename(@PathVariable("fileName") final String fileName, + @AuthenticationPrincipal final String targetid); + + /** + * Handles GET MD5 checksum file download request. + * + * @param fileName + * to search for + * + * @return response of the servlet + */ + @RequestMapping(method = RequestMethod.GET, value = DdiDlRestConstants.ARTIFACT_DOWNLOAD_BY_FILENAME + "/{fileName}" + + DdiDlRestConstants.ARTIFACT_MD5_DWNL_SUFFIX) + @ResponseBody + public ResponseEntity downloadArtifactMD5ByFilename(@PathVariable("fileName") final String fileName); + +} diff --git a/hawkbit-ddi-dl-api/src/main/java/org/eclipse/hawkbit/ddi/dl/rest/api/DdiDlRestConstants.java b/hawkbit-ddi-dl-api/src/main/java/org/eclipse/hawkbit/ddi/dl/rest/api/DdiDlRestConstants.java new file mode 100644 index 000000000..40ba5050f --- /dev/null +++ b/hawkbit-ddi-dl-api/src/main/java/org/eclipse/hawkbit/ddi/dl/rest/api/DdiDlRestConstants.java @@ -0,0 +1,40 @@ +/** + * Copyright (c) 2015 Bosch Software Innovations GmbH and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + */ +package org.eclipse.hawkbit.ddi.dl.rest.api; + +/** + * Constants for the direct device integration rest resources. + */ +public final class DdiDlRestConstants { + + /** + * The base URL mapping of the artifact repository rest resources. + */ + public static final String ARTIFACTS_V1_REQUEST_MAPPING = "/{tenant}/controller/artifacts/v1"; + + /** + * The artifact URL mapping rest resource. + */ + public static final String ARTIFACT_DOWNLOAD = "artifact"; + + /** + * The artifact by filename URL mapping rest resource. + */ + public static final String ARTIFACT_DOWNLOAD_BY_FILENAME = "/filename"; + + /** + * File suffix for MDH hash download (see Linux md5sum). + */ + public static final String ARTIFACT_MD5_DWNL_SUFFIX = ".MD5SUM"; + + // constant class, private constructor. + private DdiDlRestConstants() { + + } +} diff --git a/hawkbit-ddi-resource/README.md b/hawkbit-ddi-resource/README.md new file mode 100644 index 000000000..3cfb443cd --- /dev/null +++ b/hawkbit-ddi-resource/README.md @@ -0,0 +1,13 @@ +# Eclipse.IoT hawkBit - DDI Resource + +This is the server-side implementation of the hawkBit DDI API and the hawkBit DDI Download API that is used by devices for communicating with the HawkBit Update Server through HTTP. + +# Compile + +#### Build hawkbit-ddi-resource + +``` +$ cd hawkbit/hawkbit-ddi-resource +$ mvn clean install +``` + diff --git a/hawkbit-ddi-resource/pom.xml b/hawkbit-ddi-resource/pom.xml new file mode 100644 index 000000000..f3eb5c2c7 --- /dev/null +++ b/hawkbit-ddi-resource/pom.xml @@ -0,0 +1,163 @@ + + + + 4.0.0 + + org.eclipse.hawkbit + hawkbit-parent + 0.2.0-SNAPSHOT + + hawkbit-ddi-resource + hawkBit :: DDI Resources + + + + org.eclipse.hawkbit + hawkbit-ddi-api + ${project.version} + + + org.eclipse.hawkbit + hawkbit-ddi-dl-api + ${project.version} + + + org.eclipse.hawkbit + hawkbit-rest-core + ${project.version} + + + org.eclipse.hawkbit + hawkbit-repository + ${project.version} + + + org.springframework.plugin + spring-plugin-core + + + + + + org.eclipse.hawkbit + hawkbit-rest-core + ${project.version} + tests + test + + + org.springframework.boot + spring-boot-starter + + + org.springframework.boot + spring-boot-starter-logging + + + test + + + org.springframework.boot + spring-boot-starter-log4j2 + test + + + com.h2database + h2 + test + + + org.mariadb.jdbc + mariadb-java-client + test + + + javax.el + javax.el-api + test + + + org.springframework.security + spring-security-config + test + + + org.eclipse.hawkbit + hawkbit-repository + ${project.version} + tests + test + + + org.eclipse.hawkbit + hawkbit-http-security + ${project.version} + test + + + com.jayway.jsonpath + json-path + test + + + org.json + json + test + + + com.fasterxml.jackson.core + jackson-databind + test + + + com.fasterxml.jackson.core + jackson-core + test + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.security + spring-security-aspects + test + + + org.easytesting + fest-assert-core + test + + + org.easytesting + fest-assert + test + + + de.flapdoodle.embed + de.flapdoodle.embed.mongo + test + + + ru.yandex.qatools.allure + allure-junit-adaptor + test + + + org.springframework + spring-context-support + test + + + diff --git a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/EnableDirectDeviceApi.java b/hawkbit-ddi-resource/src/main/java/org/eclipse/hawkbit/ddi/EnableDdiApi.java similarity index 80% rename from hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/EnableDirectDeviceApi.java rename to hawkbit-ddi-resource/src/main/java/org/eclipse/hawkbit/ddi/EnableDdiApi.java index 846e1e8d2..d9572166a 100644 --- a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/EnableDirectDeviceApi.java +++ b/hawkbit-ddi-resource/src/main/java/org/eclipse/hawkbit/ddi/EnableDdiApi.java @@ -6,28 +6,28 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.controller; +package org.eclipse.hawkbit.ddi; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import org.eclipse.hawkbit.rest.configuration.RestConfiguration; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; import org.springframework.stereotype.Controller; /** * Annotation to enable {@link ComponentScan} in the resource package to setup * all {@link Controller} annotated classes and setup the Direct Device API. - * - * - * */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Configuration @ComponentScan -public @interface EnableDirectDeviceApi { +@Import(RestConfiguration.class) +public @interface EnableDdiApi { } diff --git a/hawkbit-ddi-resource/src/main/java/org/eclipse/hawkbit/ddi/rest/resource/DataConversionHelper.java b/hawkbit-ddi-resource/src/main/java/org/eclipse/hawkbit/ddi/rest/resource/DataConversionHelper.java new file mode 100644 index 000000000..b07e2557c --- /dev/null +++ b/hawkbit-ddi-resource/src/main/java/org/eclipse/hawkbit/ddi/rest/resource/DataConversionHelper.java @@ -0,0 +1,164 @@ +/** + * 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.ddi.rest.resource; + +import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; +import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +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.ddi.dl.rest.api.DdiDlRestConstants; +import org.eclipse.hawkbit.ddi.json.model.DdiArtifact; +import org.eclipse.hawkbit.ddi.json.model.DdiArtifactHash; +import org.eclipse.hawkbit.ddi.json.model.DdiChunk; +import org.eclipse.hawkbit.ddi.json.model.DdiConfig; +import org.eclipse.hawkbit.ddi.json.model.DdiControllerBase; +import org.eclipse.hawkbit.ddi.json.model.DdiPolling; +import org.eclipse.hawkbit.ddi.rest.api.DdiRestConstants; +import org.eclipse.hawkbit.repository.model.Action; +import org.eclipse.hawkbit.repository.model.Action.Status; +import org.eclipse.hawkbit.repository.model.LocalArtifact; +import org.eclipse.hawkbit.repository.model.Target; +import org.eclipse.hawkbit.tenancy.TenantAware; +import org.springframework.hateoas.Link; + +import com.google.common.base.Charsets; + +/** + * Utility class for the DDI API. + */ +public final class DataConversionHelper { + // utility class, private constructor. + private DataConversionHelper() { + + } + + static List createChunks(final String targetid, final Action uAction, + final ArtifactUrlHandler artifactUrlHandler) { + return uAction.getDistributionSet().getModules().stream() + .map(module -> new DdiChunk(mapChunkLegacyKeys(module.getType().getKey()), module.getVersion(), + module.getName(), createArtifacts(targetid, module, artifactUrlHandler))) + .collect(Collectors.toList()); + + } + + private static String mapChunkLegacyKeys(final String key) { + if ("application".equals(key)) { + return "bApp"; + } + if ("runtime".equals(key)) { + return "jvm"; + } + + return key; + } + + /** + * Creates all (rest) artifacts for a given software module. + * + * @param targetid + * of the target + * @param module + * the software module + * @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 ArtifactUrlHandler artifactUrlHandler) { + final List files = new ArrayList<>(); + + module.getLocalArtifacts() + .forEach(artifact -> files.add(createArtifact(targetid, artifactUrlHandler, artifact))); + return files; + } + + private static DdiArtifact createArtifact(final String targetid, final ArtifactUrlHandler artifactUrlHandler, + final LocalArtifact artifact) { + final DdiArtifact file = new DdiArtifact(); + file.setHashes(new DdiArtifactHash(artifact.getSha1Hash(), artifact.getMd5Hash())); + file.setFilename(artifact.getFilename()); + file.setSize(artifact.getSize()); + + if (artifactUrlHandler.protocolSupported(UrlProtocol.HTTP)) { + final String linkHttp = artifactUrlHandler.getUrl(targetid, artifact.getSoftwareModule().getId(), + artifact.getFilename(), artifact.getSha1Hash(), UrlProtocol.HTTP); + file.add(new Link(linkHttp).withRel("download-http")); + file.add(new Link(linkHttp + DdiDlRestConstants.ARTIFACT_MD5_DWNL_SUFFIX).withRel("md5sum-http")); + } + + if (artifactUrlHandler.protocolSupported(UrlProtocol.HTTPS)) { + 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 + DdiDlRestConstants.ARTIFACT_MD5_DWNL_SUFFIX).withRel("md5sum")); + } + return file; + } + + static DdiControllerBase fromTarget(final Target target, final List actions, + final String defaultControllerPollTime, final TenantAware tenantAware) { + final DdiControllerBase result = new DdiControllerBase( + new DdiConfig(new DdiPolling(defaultControllerPollTime))); + + boolean addedUpdate = false; + boolean addedCancel = false; + final long countCancelingActions = actions.stream().filter(a -> a.getStatus() == Status.CANCELING).count(); + for (final Action action : actions) { + if (countCancelingActions <= 0 && !action.isCancelingOrCanceled() && !addedUpdate) { + // we need to add the hashcode here of the actionWithStatus + // because the action might + // have changed from 'soft' to 'forced' type and we need to + // change the payload of the + // response because of eTags. + result.add(linkTo(methodOn(DdiRootController.class, tenantAware.getCurrentTenant()) + .getControllerBasedeploymentAction(target.getControllerId(), action.getId(), + actions.hashCode())).withRel(DdiRestConstants.DEPLOYMENT_BASE_ACTION)); + addedUpdate = true; + } else if (action.isCancelingOrCanceled() && !addedCancel) { + result.add(linkTo(methodOn(DdiRootController.class, tenantAware.getCurrentTenant()) + .getControllerCancelAction(target.getControllerId(), action.getId())) + .withRel(DdiRestConstants.CANCEL_ACTION)); + addedCancel = true; + } + } + + if (target.getTargetInfo().isRequestControllerAttributes()) { + result.add(linkTo(methodOn(DdiRootController.class, tenantAware.getCurrentTenant()).putConfigData(null, + target.getControllerId())).withRel(DdiRestConstants.CONFIG_DATA_ACTION)); + } + return result; + } + + static void writeMD5FileResponse(final String fileName, final HttpServletResponse response, + final LocalArtifact artifact) throws IOException { + final StringBuilder builder = new StringBuilder(); + builder.append(artifact.getMd5Hash()); + builder.append(" "); + builder.append(fileName); + final byte[] content = builder.toString().getBytes(Charsets.US_ASCII); + + final StringBuilder header = new StringBuilder(); + header.append("attachment;filename="); + header.append(fileName); + header.append(DdiDlRestConstants.ARTIFACT_MD5_DWNL_SUFFIX); + + response.setContentLength(content.length); + response.setHeader("Content-Disposition", header.toString()); + + response.getOutputStream().write(content, 0, content.length); + } + +} diff --git a/hawkbit-ddi-resource/src/main/java/org/eclipse/hawkbit/ddi/rest/resource/DdiArtifactStoreController.java b/hawkbit-ddi-resource/src/main/java/org/eclipse/hawkbit/ddi/rest/resource/DdiArtifactStoreController.java new file mode 100644 index 000000000..9c51cf8f4 --- /dev/null +++ b/hawkbit-ddi-resource/src/main/java/org/eclipse/hawkbit/ddi/rest/resource/DdiArtifactStoreController.java @@ -0,0 +1,157 @@ +/** + * 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.ddi.rest.resource; + +import java.io.IOException; +import java.io.InputStream; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; + +import org.eclipse.hawkbit.artifact.repository.model.DbArtifact; +import org.eclipse.hawkbit.cache.CacheWriteNotify; +import org.eclipse.hawkbit.ddi.dl.rest.api.DdiDlArtifactStoreControllerRestApi; +import org.eclipse.hawkbit.repository.ArtifactManagement; +import org.eclipse.hawkbit.repository.ControllerManagement; +import org.eclipse.hawkbit.repository.model.Action; +import org.eclipse.hawkbit.repository.model.Action.Status; +import org.eclipse.hawkbit.repository.model.ActionStatus; +import org.eclipse.hawkbit.repository.model.LocalArtifact; +import org.eclipse.hawkbit.repository.model.Target; +import org.eclipse.hawkbit.rest.util.RequestResponseContextHolder; +import org.eclipse.hawkbit.rest.util.RestResourceConversionHelper; +import org.eclipse.hawkbit.security.HawkbitSecurityProperties; +import org.eclipse.hawkbit.util.IpUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Scope; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.web.bind.annotation.AuthenticationPrincipal; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.context.WebApplicationContext; + +/** + * The {@link DdiArtifactStoreController} of the HawkBit server controller API + * that is queried by the HawkBit target in order to download artifacts + * independent of their own individual resource. This is offered in addition to + * the {@link DdiRootController#downloadArtifact(String, Long, String)} for + * legacy controllers that can not be fed with a download URI at runtime. + */ +@RestController +@Scope(WebApplicationContext.SCOPE_REQUEST) +public class DdiArtifactStoreController implements DdiDlArtifactStoreControllerRestApi { + + private static final Logger LOG = LoggerFactory.getLogger(DdiArtifactStoreController.class); + + @Autowired + private ArtifactManagement artifactManagement; + + @Autowired + private ControllerManagement controllerManagement; + + @Autowired + private CacheWriteNotify cacheWriteNotify; + + @Autowired + private HawkbitSecurityProperties securityProperties; + + @Autowired + private RequestResponseContextHolder requestResponseContextHolder; + + @Override + public ResponseEntity downloadArtifactByFilename(@PathVariable("fileName") final String fileName, + @AuthenticationPrincipal final String targetid) { + final List foundArtifacts = artifactManagement.findLocalArtifactByFilename(fileName); + + if (foundArtifacts.isEmpty()) { + LOG.warn("Software artifact with name {} could not be found.", fileName); + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } + + if (foundArtifacts.size() > 1) { + LOG.warn("Software artifact name {} is not unique. We will use the first entry.", fileName); + } + ResponseEntity result; + final LocalArtifact artifact = foundArtifacts.get(0); + + final String ifMatch = requestResponseContextHolder.getHttpServletRequest().getHeader("If-Match"); + if (ifMatch != null && !RestResourceConversionHelper.matchesHttpHeader(ifMatch, artifact.getSha1Hash())) { + result = new ResponseEntity<>(HttpStatus.PRECONDITION_FAILED); + } else { + final DbArtifact file = artifactManagement.loadLocalArtifactBinary(artifact); + + // we set a download status only if we are aware of the + // targetid, i.e. authenticated and not anonymous + if (targetid != null && !"anonymous".equals(targetid)) { + final Action action = checkAndReportDownloadByTarget( + requestResponseContextHolder.getHttpServletRequest(), targetid, artifact); + result = RestResourceConversionHelper.writeFileResponse(artifact, + requestResponseContextHolder.getHttpServletResponse(), + requestResponseContextHolder.getHttpServletRequest(), file, cacheWriteNotify, action.getId()); + } else { + result = RestResourceConversionHelper.writeFileResponse(artifact, + requestResponseContextHolder.getHttpServletResponse(), + requestResponseContextHolder.getHttpServletRequest(), file); + } + + } + return result; + } + + @Override + public ResponseEntity downloadArtifactMD5ByFilename(@PathVariable("fileName") final String fileName) { + final List foundArtifacts = artifactManagement.findLocalArtifactByFilename(fileName); + + if (foundArtifacts.isEmpty()) { + LOG.warn("Softeare artifact with name {} could not be found.", fileName); + return new ResponseEntity<>(HttpStatus.NOT_FOUND); + } else if (foundArtifacts.size() > 1) { + LOG.error("Softeare artifact name {} is not unique.", fileName); + } + + try { + DataConversionHelper.writeMD5FileResponse(fileName, requestResponseContextHolder.getHttpServletResponse(), + foundArtifacts.get(0)); + } catch (final IOException e) { + LOG.error("Failed to stream MD5 File", e); + return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); + } + + return new ResponseEntity<>(HttpStatus.OK); + } + + private Action checkAndReportDownloadByTarget(final HttpServletRequest request, final String targetid, + final LocalArtifact artifact) { + final Target target = controllerManagement.updateLastTargetQuery(targetid, + IpUtil.getClientIpFromRequest(request, securityProperties.getClients().getRemoteIpHeader())); + + final Action action = controllerManagement + .getActionForDownloadByTargetAndSoftwareModule(target.getControllerId(), artifact.getSoftwareModule()); + final String range = request.getHeader("Range"); + + final ActionStatus actionStatus = new ActionStatus(); + actionStatus.setAction(action); + actionStatus.setOccurredAt(System.currentTimeMillis()); + actionStatus.setStatus(Status.DOWNLOAD); + + if (range != null) { + actionStatus.addMessage(ControllerManagement.SERVER_MESSAGE_PREFIX + "Target downloads range " + range + + " of: " + request.getRequestURI()); + } else { + actionStatus.addMessage( + ControllerManagement.SERVER_MESSAGE_PREFIX + "Target downloads: " + request.getRequestURI()); + } + controllerManagement.addActionStatusMessage(actionStatus); + return action; + } + +} diff --git a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/RootController.java b/hawkbit-ddi-resource/src/main/java/org/eclipse/hawkbit/ddi/rest/resource/DdiRootController.java similarity index 55% rename from hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/RootController.java rename to hawkbit-ddi-resource/src/main/java/org/eclipse/hawkbit/ddi/rest/resource/DdiRootController.java index ff1e26f8b..3bf70ccfd 100644 --- a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/RootController.java +++ b/hawkbit-ddi-resource/src/main/java/org/eclipse/hawkbit/ddi/rest/resource/DdiRootController.java @@ -6,27 +6,29 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.controller; +package org.eclipse.hawkbit.ddi.rest.resource; import java.io.IOException; +import java.io.InputStream; import java.util.List; 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; -import org.eclipse.hawkbit.controller.model.Cancel; -import org.eclipse.hawkbit.controller.model.CancelActionToStop; -import org.eclipse.hawkbit.controller.model.Chunk; -import org.eclipse.hawkbit.controller.model.ConfigData; -import org.eclipse.hawkbit.controller.model.ControllerBase; -import org.eclipse.hawkbit.controller.model.Deployment; -import org.eclipse.hawkbit.controller.model.Deployment.HandlingType; -import org.eclipse.hawkbit.controller.model.DeploymentBase; -import org.eclipse.hawkbit.controller.model.Result.FinalResult; +import org.eclipse.hawkbit.ddi.json.model.DdiActionFeedback; +import org.eclipse.hawkbit.ddi.json.model.DdiCancel; +import org.eclipse.hawkbit.ddi.json.model.DdiCancelActionToStop; +import org.eclipse.hawkbit.ddi.json.model.DdiChunk; +import org.eclipse.hawkbit.ddi.json.model.DdiConfigData; +import org.eclipse.hawkbit.ddi.json.model.DdiControllerBase; +import org.eclipse.hawkbit.ddi.json.model.DdiDeployment; +import org.eclipse.hawkbit.ddi.json.model.DdiDeployment.HandlingType; +import org.eclipse.hawkbit.ddi.json.model.DdiDeploymentBase; +import org.eclipse.hawkbit.ddi.json.model.DdiResult.FinalResult; +import org.eclipse.hawkbit.ddi.rest.api.DdiRootControllerRestApi; import org.eclipse.hawkbit.repository.ArtifactManagement; import org.eclipse.hawkbit.repository.ControllerManagement; import org.eclipse.hawkbit.repository.SoftwareManagement; @@ -34,12 +36,12 @@ import org.eclipse.hawkbit.repository.exception.EntityNotFoundException; import org.eclipse.hawkbit.repository.model.Action; import org.eclipse.hawkbit.repository.model.Action.Status; import org.eclipse.hawkbit.repository.model.ActionStatus; -import org.eclipse.hawkbit.repository.model.Artifact; import org.eclipse.hawkbit.repository.model.LocalArtifact; import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.repository.model.TargetUpdateStatus; -import org.eclipse.hawkbit.rest.resource.helper.RestResourceConversionHelper; +import org.eclipse.hawkbit.rest.util.RequestResponseContextHolder; +import org.eclipse.hawkbit.rest.util.RestResourceConversionHelper; import org.eclipse.hawkbit.security.HawkbitSecurityProperties; import org.eclipse.hawkbit.tenancy.TenantAware; import org.eclipse.hawkbit.util.IpUtil; @@ -47,33 +49,27 @@ import org.hibernate.validator.constraints.NotEmpty; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Scope; import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.context.WebApplicationContext; /** - * The {@link RootController} of the SP server controller API that is queried by - * the SP controller in order to pull {@link Action}s that have to be fullfilled - * and report status updates concerning the {@link Action} processing. + * The {@link DdiRootController} of the hawkBit server DDI API that is queried + * by the hawkBit controller in order to pull {@link Action}s that have to be + * fulfilled and report status updates concerning the {@link Action} processing. * * Transactional (read-write) as all queries at least update the last poll time. - * - * - * - * - * */ @RestController -@RequestMapping(ControllerConstants.BASE_V1_REQUEST_MAPPING) -public class RootController { +@Scope(value = WebApplicationContext.SCOPE_REQUEST) +public class DdiRootController implements DdiRootControllerRestApi { - private static final Logger LOG = LoggerFactory.getLogger(RootController.class); + private static final Logger LOG = LoggerFactory.getLogger(DdiRootController.class); private static final String GIVEN_ACTION_IS_NOT_ASSIGNED_TO_GIVEN_TARGET = "given action ({}) is not assigned to given target ({})."; @Autowired @@ -88,26 +84,22 @@ public class RootController { @Autowired private CacheWriteNotify cacheWriteNotify; + @Autowired + private HawkbitSecurityProperties securityProperties; + @Autowired private TenantAware tenantAware; @Autowired - private HawkbitSecurityProperties securityProperties; + private ArtifactUrlHandler artifactUrlHandler; - /** - * Returns all artifacts of a given software module and target. - * - * @param targetid - * of the {@link Target} that matches to - * {@link Target#getControllerId()} - * @param softwareModuleId - * of the {@link SoftwareModule} - * @return the response - */ - @RequestMapping(method = RequestMethod.GET, value = "/{targetid}/softwaremodules/{softwareModuleId}/artifacts", produces = { - "application/hal+json", MediaType.APPLICATION_JSON_VALUE }) - public ResponseEntity> getSoftwareModulesArtifacts( - @PathVariable final String targetid, @PathVariable final Long softwareModuleId) { + @Autowired + private RequestResponseContextHolder requestResponseContextHolder; + + @Override + public ResponseEntity> getSoftwareModulesArtifacts( + @PathVariable("targetid") final String targetid, + @PathVariable("softwareModuleId") final Long softwareModuleId) { LOG.debug("getSoftwareModulesArtifacts({})", targetid); final SoftwareModule softwareModule = softwareManagement.findSoftwareModuleById(softwareModuleId); @@ -118,34 +110,24 @@ public class RootController { } - return new ResponseEntity<>(DataConversionHelper.createArtifacts(targetid, softwareModule, tenantAware), + return new ResponseEntity<>(DataConversionHelper.createArtifacts(targetid, softwareModule, artifactUrlHandler), HttpStatus.OK); } - /** - * Root resource for an individual {@link Target}. - * - * @param targetid - * of the {@link Target} that matches to - * {@link Target#getControllerId()} - * @param request - * the HTTP request injected by spring - * @return the response - */ - @RequestMapping(method = RequestMethod.GET, value = "/{targetid}", produces = { "application/hal+json", - MediaType.APPLICATION_JSON_VALUE }) - public ResponseEntity getControllerBase(@PathVariable final String targetid, - final HttpServletRequest request) { + @Override + public ResponseEntity getControllerBase(@PathVariable("targetid") final String targetid) { LOG.debug("getControllerBase({})", targetid); final Target target = controllerManagement.findOrRegisterTargetIfItDoesNotexist(targetid, - IpUtil.getClientIpFromRequest(request, securityProperties.getClients().getRemoteIpHeader())); + IpUtil.getClientIpFromRequest(requestResponseContextHolder.getHttpServletRequest(), + securityProperties.getClients().getRemoteIpHeader())); if (target.getTargetInfo().getUpdateStatus() == TargetUpdateStatus.UNKNOWN) { LOG.debug("target with {} extsisted but was in status UNKNOWN -> REGISTERED)", targetid); controllerManagement.updateTargetStatus(target.getTargetInfo(), TargetUpdateStatus.REGISTERED, System.currentTimeMillis(), - IpUtil.getClientIpFromRequest(request, securityProperties.getClients().getRemoteIpHeader())); + IpUtil.getClientIpFromRequest(requestResponseContextHolder.getHttpServletRequest(), + securityProperties.getClients().getRemoteIpHeader())); } return new ResponseEntity<>( @@ -154,33 +136,15 @@ public class RootController { HttpStatus.OK); } - /** - * Handles GET {@link Artifact} download request. This could be full or - * partial (as specified by RFC7233 (Range Requests)) download request. - * - * @param targetid - * of the related - * @param softwareModuleId - * of the parent {@link SoftwareModule} - * @param fileName - * of the related {@link LocalArtifact} - * @param response - * of the servlet - * @param request - * from the client - * - * @return response of the servlet which in case of success is status code - * {@link HttpStatus#OK} or in case of partial download - * {@link HttpStatus#PARTIAL_CONTENT}. - */ - @RequestMapping(method = RequestMethod.GET, value = "/{targetid}/softwaremodules/{softwareModuleId}/artifacts/{fileName}") - public ResponseEntity downloadArtifact(@PathVariable final String targetid, - @PathVariable final Long softwareModuleId, @PathVariable final String fileName, - final HttpServletResponse response, final HttpServletRequest request) { - ResponseEntity result; + @Override + public ResponseEntity downloadArtifact(@PathVariable("targetid") final String targetid, + @PathVariable("softwareModuleId") final Long softwareModuleId, + @PathVariable("fileName") final String fileName) { + ResponseEntity result; final Target target = controllerManagement.updateLastTargetQuery(targetid, - IpUtil.getClientIpFromRequest(request, securityProperties.getClients().getRemoteIpHeader())); + IpUtil.getClientIpFromRequest(requestResponseContextHolder.getHttpServletRequest(), + securityProperties.getClients().getRemoteIpHeader())); final SoftwareModule module = softwareManagement.findSoftwareModuleById(softwareModuleId); if (checkModule(fileName, module)) { @@ -190,17 +154,17 @@ public class RootController { final LocalArtifact artifact = module.getLocalArtifactByFilename(fileName).get(); final DbArtifact file = artifactManagement.loadLocalArtifactBinary(artifact); - final String ifMatch = request.getHeader("If-Match"); + final String ifMatch = requestResponseContextHolder.getHttpServletRequest().getHeader("If-Match"); if (ifMatch != null && !RestResourceConversionHelper.matchesHttpHeader(ifMatch, artifact.getSha1Hash())) { result = new ResponseEntity<>(HttpStatus.PRECONDITION_FAILED); } else { - final Action action = checkAndLogDownload(request, target, module); - result = RestResourceConversionHelper.writeFileResponse(artifact, response, request, file, - cacheWriteNotify, action.getId()); + final Action action = checkAndLogDownload(requestResponseContextHolder.getHttpServletRequest(), target, + module); + result = RestResourceConversionHelper.writeFileResponse(artifact, + requestResponseContextHolder.getHttpServletResponse(), + requestResponseContextHolder.getHttpServletRequest(), file, cacheWriteNotify, action.getId()); } - } - return result; } @@ -216,9 +180,11 @@ public class RootController { statusMessage.setStatus(Status.DOWNLOAD); if (range != null) { - statusMessage.addMessage("It is a partial download request: " + range); + statusMessage.addMessage(ControllerManagement.SERVER_MESSAGE_PREFIX + "Target downloads range " + range + + " of: " + request.getRequestURI()); } else { - statusMessage.addMessage("Controller downloads"); + statusMessage.addMessage( + ControllerManagement.SERVER_MESSAGE_PREFIX + "Target downloads " + request.getRequestURI()); } controllerManagement.addActionStatusMessage(statusMessage); return action; @@ -228,30 +194,13 @@ public class RootController { return null == module || !module.getLocalArtifactByFilename(fileName).isPresent(); } - /** - * Handles GET {@link Artifact} MD5 checksum file download request. - * - * @param targetid - * of the related - * @param softwareModuleId - * of the parent {@link SoftwareModule} - * @param fileName - * of the related {@link LocalArtifact} - * @param response - * of the servlet - * @param request - * the HTTP request injected by spring - * - * @return {@link ResponseEntity} with status {@link HttpStatus#OK} if - * successful - */ - @RequestMapping(method = RequestMethod.GET, value = "/{targetid}/softwaremodules/{softwareModuleId}/artifacts/{fileName}" - + ControllerConstants.ARTIFACT_MD5_DWNL_SUFFIX, produces = MediaType.TEXT_PLAIN_VALUE) - public ResponseEntity downloadArtifactMd5(@PathVariable final String targetid, - @PathVariable final Long softwareModuleId, @PathVariable final String fileName, - final HttpServletResponse response, final HttpServletRequest request) { + @Override + public ResponseEntity downloadArtifactMd5(@PathVariable("targetid") final String targetid, + @PathVariable("softwareModuleId") final Long softwareModuleId, + @PathVariable("fileName") final String fileName) { controllerManagement.updateLastTargetQuery(targetid, - IpUtil.getClientIpFromRequest(request, securityProperties.getClients().getRemoteIpHeader())); + IpUtil.getClientIpFromRequest(requestResponseContextHolder.getHttpServletRequest(), + securityProperties.getClients().getRemoteIpHeader())); final SoftwareModule module = softwareManagement.findSoftwareModuleById(softwareModuleId); @@ -261,7 +210,7 @@ public class RootController { } try { - DataConversionHelper.writeMD5FileResponse(fileName, response, + DataConversionHelper.writeMD5FileResponse(fileName, requestResponseContextHolder.getHttpServletResponse(), module.getLocalArtifactByFilename(fileName).get()); } catch (final IOException e) { LOG.error("Failed to stream MD5 File", e); @@ -271,33 +220,15 @@ public class RootController { return new ResponseEntity<>(HttpStatus.OK); } - /** - * Resource for {@link SoftwareModule} {@link UpdateAction}s. - * - * @param targetid - * of the {@link Target} that matches to - * {@link Target#getControllerId()} - * @param actionId - * of the {@link DeploymentBase} that matches to - * {@link Target#getActiveActions()} - * @param resource - * an hashcode of the resource which indicates if the action has - * been changed, e.g. from 'soft' to 'force' and the eTag needs - * to be re-generated - * @param request - * the HTTP request injected by spring - * @return the response - */ - @RequestMapping(value = "/{targetid}/" + ControllerConstants.DEPLOYMENT_BASE_ACTION - + "/{actionId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity getControllerBasedeploymentAction( - @PathVariable @NotEmpty final String targetid, @PathVariable @NotEmpty final Long actionId, - @RequestParam(value = "c", required = false, defaultValue = "-1") final int resource, - final HttpServletRequest request) { + @Override + public ResponseEntity getControllerBasedeploymentAction( + @PathVariable("targetid") final String targetid, @PathVariable("actionId") final Long actionId, + @RequestParam(value = "c", required = false, defaultValue = "-1") final int resource) { LOG.debug("getControllerBasedeploymentAction({},{})", targetid, resource); final Target target = controllerManagement.updateLastTargetQuery(targetid, - IpUtil.getClientIpFromRequest(request, securityProperties.getClients().getRemoteIpHeader())); + IpUtil.getClientIpFromRequest(requestResponseContextHolder.getHttpServletRequest(), + securityProperties.getClients().getRemoteIpHeader())); final Action action = findActionWithExceptionIfNotFound(actionId); if (!action.getTarget().getId().equals(target.getId())) { @@ -307,17 +238,18 @@ public class RootController { if (!action.isCancelingOrCanceled()) { - final List chunks = DataConversionHelper.createChunks(targetid, action, tenantAware); + final List chunks = DataConversionHelper.createChunks(targetid, action, artifactUrlHandler); final HandlingType handlingType = action.isForce() ? HandlingType.FORCED : HandlingType.ATTEMPT; - final DeploymentBase base = new DeploymentBase(Long.toString(action.getId()), - new Deployment(handlingType, handlingType, chunks)); + final DdiDeploymentBase base = new DdiDeploymentBase(Long.toString(action.getId()), + new DdiDeployment(handlingType, handlingType, chunks)); LOG.debug("Found an active UpdateAction for target {}. returning deyploment: {}", targetid, base); controllerManagement.registerRetrieved(action, - "Controller retrieved update action and should start now the download."); + ControllerManagement.SERVER_MESSAGE_PREFIX + + "Target retrieved update action and should start now the download."); return new ResponseEntity<>(base, HttpStatus.OK); } @@ -325,30 +257,14 @@ public class RootController { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } - /** - * This is the feedback channel for the {@link DeploymentBase} action. - * - * @param feedback - * to provide - * @param targetid - * of the {@link Target} that matches to - * {@link Target#getControllerId()} - * @param actionId - * of the action we have feedback for - * @param request - * the HTTP request injected by spring - * - * @return the response - */ - @RequestMapping(value = "/{targetid}/" + ControllerConstants.DEPLOYMENT_BASE_ACTION + "/{actionId}/" - + ControllerConstants.FEEDBACK, method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity postBasedeploymentActionFeedback(@Valid @RequestBody final ActionFeedback feedback, - @PathVariable final String targetid, @PathVariable @NotEmpty final Long actionId, - final HttpServletRequest request) { + @Override + public ResponseEntity postBasedeploymentActionFeedback(@Valid @RequestBody final DdiActionFeedback feedback, + @PathVariable("targetid") final String targetid, @PathVariable("actionId") @NotEmpty final Long actionId) { LOG.debug("provideBasedeploymentActionFeedback for target [{},{}]: {}", targetid, actionId, feedback); final Target target = controllerManagement.updateLastTargetQuery(targetid, - IpUtil.getClientIpFromRequest(request, securityProperties.getClients().getRemoteIpHeader())); + IpUtil.getClientIpFromRequest(requestResponseContextHolder.getHttpServletRequest(), + securityProperties.getClients().getRemoteIpHeader())); if (!actionId.equals(feedback.getId())) { LOG.warn( @@ -369,15 +285,15 @@ public class RootController { return new ResponseEntity<>(HttpStatus.GONE); } - controllerManagement.addUpdateActionStatus(generateUpdateStatus(feedback, targetid, feedback.getId(), action), - action); + controllerManagement.addUpdateActionStatus( + generateUpdateStatus(feedback, targetid, feedback.getId(), action), action); return new ResponseEntity<>(HttpStatus.OK); } - private ActionStatus generateUpdateStatus(final ActionFeedback feedback, final String targetid, final Long actionid, - final Action action) { + private ActionStatus generateUpdateStatus(final DdiActionFeedback feedback, final String targetid, + final Long actionid, final Action action) { final ActionStatus actionStatus = new ActionStatus(); actionStatus.setAction(action); @@ -388,13 +304,13 @@ public class RootController { LOG.debug("Controller confirmed cancel (actionid: {}, targetid: {}) as we got {} report.", actionid, targetid, feedback.getStatus().getExecution()); actionStatus.setStatus(Status.CANCELED); - actionStatus.addMessage("Controller confirmed cancelation"); + actionStatus.addMessage(ControllerManagement.SERVER_MESSAGE_PREFIX + "Target confirmed cancelation."); break; case REJECTED: LOG.info("Controller reported internal error (actionid: {}, targetid: {}) as we got {} report.", actionid, targetid, feedback.getStatus().getExecution()); actionStatus.setStatus(Status.WARNING); - actionStatus.addMessage("Controller reported internal ERROR and REJECTED update."); + actionStatus.addMessage(ControllerManagement.SERVER_MESSAGE_PREFIX + "Target REJECTED update."); break; case CLOSED: handleClosedUpdateStatus(feedback, targetid, actionid, actionStatus); @@ -416,71 +332,49 @@ public class RootController { return actionStatus; } - private static void handleDefaultUpdateStatus(final ActionFeedback feedback, final String targetid, + private static void handleDefaultUpdateStatus(final DdiActionFeedback feedback, final String targetid, final Long actionid, final ActionStatus actionStatus) { LOG.debug("Controller reported intermediate status (actionid: {}, targetid: {}) as we got {} report.", actionid, targetid, feedback.getStatus().getExecution()); actionStatus.setStatus(Status.RUNNING); - actionStatus.addMessage("Controller reported: " + feedback.getStatus().getExecution()); + actionStatus.addMessage( + ControllerManagement.SERVER_MESSAGE_PREFIX + "Target reported " + feedback.getStatus().getExecution()); } - private static void handleClosedUpdateStatus(final ActionFeedback feedback, final String targetid, + private static void handleClosedUpdateStatus(final DdiActionFeedback feedback, final String targetid, final Long actionid, final ActionStatus actionStatus) { LOG.debug("Controller reported closed (actionid: {}, targetid: {}) as we got {} report.", actionid, targetid, feedback.getStatus().getExecution()); if (feedback.getStatus().getResult().getFinished() == FinalResult.FAILURE) { actionStatus.setStatus(Status.ERROR); - actionStatus.addMessage("Controller reported CLOSED with ERROR!"); + actionStatus.addMessage(ControllerManagement.SERVER_MESSAGE_PREFIX + "Target reported CLOSED with ERROR!"); } else { actionStatus.setStatus(Status.FINISHED); - actionStatus.addMessage("Controller reported CLOSED with OK!"); + actionStatus.addMessage(ControllerManagement.SERVER_MESSAGE_PREFIX + "Target reported CLOSED with OK!"); } } - /** - * This is the feedback channel for the config data action. - * - * @param configData - * as body - * @param targetid - * to provide data for - * @param request - * the HTTP request injected by spring - * - * @return status of the request - */ - @RequestMapping(value = "/{targetid}/" - + ControllerConstants.CONFIG_DATA_ACTION, method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity putConfigData(@Valid @RequestBody final ConfigData configData, - @PathVariable final String targetid, final HttpServletRequest request) { + @Override + public ResponseEntity putConfigData(@Valid @RequestBody final DdiConfigData configData, + @PathVariable("targetid") final String targetid) { controllerManagement.updateLastTargetQuery(targetid, - IpUtil.getClientIpFromRequest(request, securityProperties.getClients().getRemoteIpHeader())); + IpUtil.getClientIpFromRequest(requestResponseContextHolder.getHttpServletRequest(), + securityProperties.getClients().getRemoteIpHeader())); controllerManagement.updateControllerAttributes(targetid, configData.getData()); return new ResponseEntity<>(HttpStatus.OK); } - /** - * {@link RequestMethod.GET} method for the {@link Cancel} action. - * - * @param targetid - * ID of the calling target - * @param actionId - * of the action - * @param request - * the HTTP request injected by spring - * - * @return the {@link Cancel} response - */ - @RequestMapping(value = "/{targetid}/" + ControllerConstants.CANCEL_ACTION - + "/{actionId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity getControllerCancelAction(@PathVariable @NotEmpty final String targetid, - @PathVariable @NotEmpty final Long actionId, final HttpServletRequest request) { + @Override + public ResponseEntity getControllerCancelAction( + @PathVariable("targetid") @NotEmpty final String targetid, + @PathVariable("actionId") @NotEmpty final Long actionId) { LOG.debug("getControllerCancelAction({})", targetid); final Target target = controllerManagement.updateLastTargetQuery(targetid, - IpUtil.getClientIpFromRequest(request, securityProperties.getClients().getRemoteIpHeader())); + IpUtil.getClientIpFromRequest(requestResponseContextHolder.getHttpServletRequest(), + securityProperties.getClients().getRemoteIpHeader())); final Action action = findActionWithExceptionIfNotFound(actionId); if (!action.getTarget().getId().equals(target.getId())) { @@ -489,13 +383,13 @@ public class RootController { } if (action.isCancelingOrCanceled()) { - final Cancel cancel = new Cancel(String.valueOf(action.getId()), - new CancelActionToStop(String.valueOf(action.getId()))); + final DdiCancel cancel = new DdiCancel(String.valueOf(action.getId()), + new DdiCancelActionToStop(String.valueOf(action.getId()))); LOG.debug("Found an active CancelAction for target {}. returning cancel: {}", targetid, cancel); - controllerManagement.registerRetrieved(action, - "Controller retrieved cancel action and should start now the cancelation."); + controllerManagement.registerRetrieved(action, ControllerManagement.SERVER_MESSAGE_PREFIX + + "Target retrieved cancel action and should start now the cancelation."); return new ResponseEntity<>(cancel, HttpStatus.OK); } @@ -503,31 +397,15 @@ public class RootController { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } - /** - * {@link RequestMethod.POST} method receiving the {@link ActionFeedback} - * from the target. - * - * @param feedback - * the {@link ActionFeedback} from the target. - * @param targetid - * the ID of the calling target - * @param actionId - * of the action we have feedback for - * @param request - * the HTTP request injected by spring - * - * @return the {@link ActionFeedback} response - */ - - @RequestMapping(value = "/{targetid}/" + ControllerConstants.CANCEL_ACTION + "/{actionId}/" - + ControllerConstants.FEEDBACK, method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity postCancelActionFeedback(@Valid @RequestBody final ActionFeedback feedback, - @PathVariable @NotEmpty final String targetid, @PathVariable @NotEmpty final Long actionId, - final HttpServletRequest request) { + @Override + public ResponseEntity postCancelActionFeedback(@Valid @RequestBody final DdiActionFeedback feedback, + @PathVariable("targetid") @NotEmpty final String targetid, + @PathVariable("actionId") @NotEmpty final Long actionId) { LOG.debug("provideCancelActionFeedback for target [{}]: {}", targetid, feedback); final Target target = controllerManagement.updateLastTargetQuery(targetid, - IpUtil.getClientIpFromRequest(request, securityProperties.getClients().getRemoteIpHeader())); + IpUtil.getClientIpFromRequest(requestResponseContextHolder.getHttpServletRequest(), + securityProperties.getClients().getRemoteIpHeader())); if (!actionId.equals(feedback.getId())) { LOG.warn( @@ -547,7 +425,7 @@ public class RootController { return new ResponseEntity<>(HttpStatus.OK); } - private static ActionStatus generateActionCancelStatus(final ActionFeedback feedback, final Target target, + private static ActionStatus generateActionCancelStatus(final DdiActionFeedback feedback, final Target target, final Long actionid, final Action action) { final ActionStatus actionStatus = new ActionStatus(); @@ -587,7 +465,7 @@ public class RootController { } - private static void handleClosedCancelStatus(final ActionFeedback feedback, final ActionStatus actionStatus) { + private static void handleClosedCancelStatus(final DdiActionFeedback feedback, final ActionStatus actionStatus) { if (feedback.getStatus().getResult().getFinished() == FinalResult.FAILURE) { actionStatus.setStatus(Status.ERROR); } else { @@ -602,5 +480,4 @@ public class RootController { } return findAction; } - } diff --git a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/controller/ArtifactDownloadTest.java b/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiArtifactDownloadTest.java similarity index 98% rename from hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/controller/ArtifactDownloadTest.java rename to hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiArtifactDownloadTest.java index b49f34b5f..6c3bdea4e 100644 --- a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/controller/ArtifactDownloadTest.java +++ b/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiArtifactDownloadTest.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.controller; +package org.eclipse.hawkbit.ddi.rest.resource; import static org.fest.assertions.api.Assertions.assertThat; import static org.junit.Assert.assertTrue; @@ -26,7 +26,6 @@ import java.util.Arrays; import java.util.List; import org.apache.commons.lang3.RandomUtils; -import org.eclipse.hawkbit.AbstractIntegrationTestWithMongoDB; import org.eclipse.hawkbit.TestDataUtil; import org.eclipse.hawkbit.WithUser; import org.eclipse.hawkbit.eventbus.event.DownloadProgressEvent; @@ -36,13 +35,13 @@ 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.Target; +import org.eclipse.hawkbit.rest.AbstractRestIntegrationTestWithMongoDB; import org.junit.Test; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort.Direction; import org.springframework.http.MediaType; -import org.springframework.test.context.ActiveProfiles; import org.springframework.test.web.servlet.MvcResult; import com.google.common.base.Charsets; @@ -56,21 +55,16 @@ import ru.yandex.qatools.allure.annotations.Stories; /** * Test artifact downloads from the controller. - * */ - -@ActiveProfiles({ "im", "test" }) @Features("Component Tests - Direct Device Integration API") @Stories("Artifact Download Resource") -public class ArtifactDownloadTest extends AbstractIntegrationTestWithMongoDB { +public class DdiArtifactDownloadTest extends AbstractRestIntegrationTestWithMongoDB { - private static final String AUTH_ANOYM = "ROLE_CONTROLLER_ANONYMOUS"; - - public ArtifactDownloadTest() { - LOG = LoggerFactory.getLogger(ArtifactDownloadTest.class); + public DdiArtifactDownloadTest() { + LOG = LoggerFactory.getLogger(DdiArtifactDownloadTest.class); } - private int downLoadProgress = 0; + private volatile int downLoadProgress = 0; @Autowired private EventBus eventBus; @@ -364,7 +358,7 @@ public class ArtifactDownloadTest extends AbstractIntegrationTestWithMongoDB { // create target Target target = new Target("4712"); target = targetManagement.createTarget(target); - final List targets = new ArrayList(); + final List targets = new ArrayList<>(); targets.add(target); // create ds diff --git a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/controller/CancelActionTest.java b/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiCancelActionTest.java similarity index 98% rename from hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/controller/CancelActionTest.java rename to hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiCancelActionTest.java index d7e0351cf..9913d5e51 100644 --- a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/controller/CancelActionTest.java +++ b/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiCancelActionTest.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.controller; +package org.eclipse.hawkbit.ddi.rest.resource; import static org.fest.assertions.api.Assertions.assertThat; import static org.hamcrest.CoreMatchers.equalTo; @@ -22,27 +22,28 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. import java.util.ArrayList; import java.util.List; -import org.eclipse.hawkbit.AbstractIntegrationTest; -import org.eclipse.hawkbit.MockMvcResultPrinter; import org.eclipse.hawkbit.TestDataUtil; import org.eclipse.hawkbit.repository.model.Action; import org.eclipse.hawkbit.repository.model.Action.Status; import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.Target; -import org.eclipse.hawkbit.rest.resource.JsonBuilder; +import org.eclipse.hawkbit.rest.AbstractRestIntegrationTest; +import org.eclipse.hawkbit.rest.util.JsonBuilder; +import org.eclipse.hawkbit.rest.util.MockMvcResultPrinter; import org.junit.Test; import org.springframework.hateoas.MediaTypes; import org.springframework.http.MediaType; -import org.springframework.test.context.ActiveProfiles; import ru.yandex.qatools.allure.annotations.Description; import ru.yandex.qatools.allure.annotations.Features; import ru.yandex.qatools.allure.annotations.Stories; -@ActiveProfiles({ "im", "test" }) +/** + * Test cancel action from the controller. + */ @Features("Component Tests - Direct Device Integration API") @Stories("Cancel Action Resource") -public class CancelActionTest extends AbstractIntegrationTest { +public class DdiCancelActionTest extends AbstractRestIntegrationTest { @Test @Description("Test of the controller can continue a started update even after a cancel command if it so desires.") diff --git a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/controller/ConfigDataTest.java b/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiConfigDataTest.java similarity index 97% rename from hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/controller/ConfigDataTest.java rename to hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiConfigDataTest.java index a2b26c218..4a86cfe8c 100644 --- a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/controller/ConfigDataTest.java +++ b/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiConfigDataTest.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.controller; +package org.eclipse.hawkbit.ddi.rest.resource; import static org.fest.assertions.api.Assertions.assertThat; import static org.hamcrest.CoreMatchers.equalTo; @@ -22,9 +22,9 @@ import java.util.HashMap; import java.util.Map; import org.eclipse.hawkbit.AbstractIntegrationTest; -import org.eclipse.hawkbit.MockMvcResultPrinter; import org.eclipse.hawkbit.repository.model.Target; -import org.eclipse.hawkbit.rest.resource.JsonBuilder; +import org.eclipse.hawkbit.rest.util.JsonBuilder; +import org.eclipse.hawkbit.rest.util.MockMvcResultPrinter; import org.junit.Test; import org.springframework.hateoas.MediaTypes; import org.springframework.http.MediaType; @@ -34,10 +34,13 @@ import ru.yandex.qatools.allure.annotations.Description; import ru.yandex.qatools.allure.annotations.Features; import ru.yandex.qatools.allure.annotations.Stories; +/** + * Test config data from the controller. + */ @ActiveProfiles({ "im", "test" }) @Features("Component Tests - Direct Device Integration API") @Stories("Config Data Resource") -public class ConfigDataTest extends AbstractIntegrationTest { +public class DdiConfigDataTest extends AbstractIntegrationTest { @Test @Description("We verify that the config data (i.e. device attributes like serial number, hardware revision etc.) " diff --git a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/controller/DeploymentBaseTest.java b/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiDeploymentBaseTest.java similarity index 91% rename from hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/controller/DeploymentBaseTest.java rename to hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiDeploymentBaseTest.java index 2b2b7e597..eb3ed8844 100644 --- a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/controller/DeploymentBaseTest.java +++ b/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiDeploymentBaseTest.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.controller; +package org.eclipse.hawkbit.ddi.rest.resource; import static org.fest.assertions.api.Assertions.assertThat; import static org.hamcrest.CoreMatchers.equalTo; @@ -25,8 +25,6 @@ import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.RandomUtils; -import org.eclipse.hawkbit.AbstractIntegrationTestWithMongoDB; -import org.eclipse.hawkbit.MockMvcResultPrinter; import org.eclipse.hawkbit.TestDataUtil; import org.eclipse.hawkbit.repository.model.Action; import org.eclipse.hawkbit.repository.model.Action.ActionType; @@ -36,7 +34,9 @@ import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.LocalArtifact; import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.repository.model.TargetUpdateStatus; -import org.eclipse.hawkbit.rest.resource.JsonBuilder; +import org.eclipse.hawkbit.rest.AbstractRestIntegrationTestWithMongoDB; +import org.eclipse.hawkbit.rest.util.JsonBuilder; +import org.eclipse.hawkbit.rest.util.MockMvcResultPrinter; import org.fest.assertions.core.Condition; import org.junit.Test; import org.springframework.data.domain.PageRequest; @@ -45,16 +45,20 @@ import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort.Direction; import org.springframework.hateoas.MediaTypes; import org.springframework.http.MediaType; -import org.springframework.test.context.ActiveProfiles; import ru.yandex.qatools.allure.annotations.Description; import ru.yandex.qatools.allure.annotations.Features; import ru.yandex.qatools.allure.annotations.Stories; -@ActiveProfiles({ "im", "test" }) +/** + * Test deployment base from the controller. + */ @Features("Component Tests - Direct Device Integration API") @Stories("Deployment Action Resource") -public class DeploymentBaseTest extends AbstractIntegrationTestWithMongoDB { +public class DdiDeploymentBaseTest extends AbstractRestIntegrationTestWithMongoDB { + + private static final String HTTP_LOCALHOST = "http://localhost:8080/"; + private static final String HTTPS_LOCALHOST = "https://localhost:8080/"; @Test() @Description("Ensures that artifacts are not found, when softare module does not exists.") @@ -114,12 +118,12 @@ public class DeploymentBaseTest extends AbstractIntegrationTestWithMongoDB { assertThat(actionStatusRepository.findAll()).isEmpty(); List saved = deploymentManagement.assignDistributionSet(ds.getId(), ActionType.FORCED, - Action.NO_FORCE_TIME, savedTarget.getControllerId()).getAssignedTargets(); + Action.NO_FORCE_TIME, savedTarget.getControllerId()).getAssignedEntity(); assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(1); final Action action = deploymentManagement.findActiveActionsByTarget(savedTarget).get(0); assertThat(actionRepository.findAll()).hasSize(1); - saved = deploymentManagement.assignDistributionSet(ds2, saved).getAssignedTargets(); + saved = deploymentManagement.assignDistributionSet(ds2, saved).getAssignedEntity(); assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(2); assertThat(actionRepository.findAll()).hasSize(2); @@ -170,15 +174,25 @@ 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"))) + + .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,15 +202,23 @@ 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("http://localhost/" + tenantAware.getCurrentTenant() + 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", @@ -236,12 +258,12 @@ public class DeploymentBaseTest extends AbstractIntegrationTestWithMongoDB { List saved = deploymentManagement .assignDistributionSet(ds.getId(), ActionType.SOFT, Action.NO_FORCE_TIME, savedTarget.getControllerId()) - .getAssignedTargets(); + .getAssignedEntity(); assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(1); final Action action = deploymentManagement.findActiveActionsByTarget(savedTarget).get(0); assertThat(actionRepository.findAll()).hasSize(1); - saved = deploymentManagement.assignDistributionSet(ds2, saved).getAssignedTargets(); + saved = deploymentManagement.assignDistributionSet(ds2, saved).getAssignedEntity(); assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(2); assertThat(actionRepository.findAll()).hasSize(2); @@ -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,15 +333,23 @@ 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("http://localhost/" + tenantAware.getCurrentTenant() + 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", @@ -358,12 +388,12 @@ public class DeploymentBaseTest extends AbstractIntegrationTestWithMongoDB { assertThat(actionStatusRepository.findAll()).isEmpty(); List saved = deploymentManagement.assignDistributionSet(ds.getId(), ActionType.TIMEFORCED, - System.currentTimeMillis(), savedTarget.getControllerId()).getAssignedTargets(); + System.currentTimeMillis(), savedTarget.getControllerId()).getAssignedEntity(); assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(1); final Action action = deploymentManagement.findActiveActionsByTarget(savedTarget).get(0); assertThat(actionRepository.findAll()).hasSize(1); - saved = deploymentManagement.assignDistributionSet(ds2, saved).getAssignedTargets(); + saved = deploymentManagement.assignDistributionSet(ds2, saved).getAssignedEntity(); assertThat(deploymentManagement.findActiveActionsByTarget(savedTarget)).hasSize(2); assertThat(actionRepository.findAll()).hasSize(2); @@ -409,19 +439,27 @@ 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("http://localhost/" + tenantAware.getCurrentTenant() + 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"))) @@ -431,15 +469,25 @@ 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("http://localhost/" + tenantAware.getCurrentTenant() + 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", @@ -887,7 +935,7 @@ public class DeploymentBaseTest extends AbstractIntegrationTestWithMongoDB { assertThat(targetManagement.findTargetByControllerID("4712").getTargetInfo().getUpdateStatus()) .isEqualTo(TargetUpdateStatus.UNKNOWN); - savedTarget = deploymentManagement.assignDistributionSet(savedSet, toAssign).getAssignedTargets().iterator() + savedTarget = deploymentManagement.assignDistributionSet(savedSet, toAssign).getAssignedEntity().iterator() .next(); deploymentManagement.assignDistributionSet(savedSet2, toAssign2); diff --git a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/controller/RootControllerTest.java b/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiRootControllerTest.java similarity index 97% rename from hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/controller/RootControllerTest.java rename to hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiRootControllerTest.java index a6e457f3a..8041e8b36 100644 --- a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/controller/RootControllerTest.java +++ b/hawkbit-ddi-resource/src/test/java/org/eclipse/hawkbit/ddi/rest/resource/DdiRootControllerTest.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.controller; +package org.eclipse.hawkbit.ddi.rest.resource; import static org.fest.assertions.api.Assertions.assertThat; import static org.hamcrest.CoreMatchers.equalTo; @@ -22,8 +22,6 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. import java.util.ArrayList; import java.util.List; -import org.eclipse.hawkbit.AbstractIntegrationTestWithMongoDB; -import org.eclipse.hawkbit.MockMvcResultPrinter; import org.eclipse.hawkbit.TestDataUtil; import org.eclipse.hawkbit.WithSpringAuthorityRule; import org.eclipse.hawkbit.WithUser; @@ -33,22 +31,25 @@ import org.eclipse.hawkbit.repository.model.Action; import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.repository.model.TargetUpdateStatus; -import org.eclipse.hawkbit.rest.resource.JsonBuilder; +import org.eclipse.hawkbit.rest.AbstractRestIntegrationTestWithMongoDB; +import org.eclipse.hawkbit.rest.util.JsonBuilder; +import org.eclipse.hawkbit.rest.util.MockMvcResultPrinter; import org.eclipse.hawkbit.tenancy.configuration.TenantConfigurationKey; import org.eclipse.hawkbit.util.IpUtil; import org.junit.Test; import org.springframework.hateoas.MediaTypes; import org.springframework.http.MediaType; -import org.springframework.test.context.ActiveProfiles; import ru.yandex.qatools.allure.annotations.Description; import ru.yandex.qatools.allure.annotations.Features; import ru.yandex.qatools.allure.annotations.Stories; -@ActiveProfiles({ "im", "test" }) +/** + * Test the root controller resources. + */ @Features("Component Tests - Direct Device Integration API") @Stories("Root Poll Resource") -public class RootControllerTest extends AbstractIntegrationTestWithMongoDB { +public class DdiRootControllerTest extends AbstractRestIntegrationTestWithMongoDB { @Test @Description("Ensures that targets cannot be created e.g. in plug'n play scenarios when tenant does not exists but can be created if the tenant exists.") @@ -270,7 +271,7 @@ public class RootControllerTest extends AbstractIntegrationTestWithMongoDB { Target savedTarget = targetManagement.createTarget(target); final List toAssign = new ArrayList(); toAssign.add(savedTarget); - savedTarget = deploymentManagement.assignDistributionSet(ds, toAssign).getAssignedTargets().iterator().next(); + savedTarget = deploymentManagement.assignDistributionSet(ds, toAssign).getAssignedEntity().iterator().next(); final Action savedAction = deploymentManagement.findActiveActionsByTarget(savedTarget).get(0); mvc.perform(post("/{tenant}/controller/v1/911/deploymentBase/" + savedAction.getId() + "/feedback", tenantAware.getCurrentTenant()) 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/AmqpConfiguration.java b/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpConfiguration.java index acbcb453b..20a11713f 100644 --- a/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpConfiguration.java +++ b/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpConfiguration.java @@ -8,9 +8,6 @@ */ package org.eclipse.hawkbit.amqp; -import java.util.HashMap; -import java.util.Map; - import org.eclipse.hawkbit.dmf.amqp.api.AmqpSettings; import org.springframework.amqp.core.Binding; import org.springframework.amqp.core.BindingBuilder; @@ -18,6 +15,7 @@ import org.springframework.amqp.core.FanoutExchange; import org.springframework.amqp.core.Queue; import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory; import org.springframework.amqp.rabbit.connection.ConnectionFactory; +import org.springframework.amqp.rabbit.core.RabbitAdmin; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer; import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter; @@ -31,15 +29,31 @@ import org.springframework.context.annotation.Bean; * {@code amqp} to use a AMQP for communication with SP enabled devices. * */ -@EnableConfigurationProperties(AmqpProperties.class) +@EnableConfigurationProperties({ AmqpProperties.class, AmqpDeadletterProperties.class }) public class AmqpConfiguration { @Autowired protected AmqpProperties amqpProperties; + @Autowired + protected AmqpDeadletterProperties amqpDeadletterProperties; + @Autowired private ConnectionFactory connectionFactory; + /** + * Create a {@link RabbitAdmin} and ignore declaration exceptions. + * {@link RabbitAdmin#setIgnoreDeclarationExceptions(boolean)} + * + * @return the bean + */ + @Bean + public RabbitAdmin rabbitAdmin() { + final RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory); + rabbitAdmin.setIgnoreDeclarationExceptions(true); + return rabbitAdmin; + } + /** * Method to set the Jackson2JsonMessageConverter. * @@ -59,7 +73,8 @@ public class AmqpConfiguration { */ @Bean public Queue receiverQueue() { - return new Queue(amqpProperties.getReceiverQueue(), true, false, false, getDeadLetterExchangeArgs()); + return new Queue(amqpProperties.getReceiverQueue(), true, false, false, + amqpDeadletterProperties.getDeadLetterExchangeArgs(amqpProperties.getDeadLetterExchange())); } /** @@ -79,7 +94,7 @@ public class AmqpConfiguration { */ @Bean public Queue deadLetterQueue() { - return new Queue(amqpProperties.getDeadLetterQueue()); + return amqpDeadletterProperties.createDeadletterQueue(amqpProperties.getDeadLetterQueue()); } /** @@ -149,10 +164,4 @@ public class AmqpConfiguration { return containerFactory; } - private Map getDeadLetterExchangeArgs() { - final Map args = new HashMap<>(); - args.put("x-dead-letter-exchange", amqpProperties.getDeadLetterExchange()); - return args; - } - } 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..91d07de37 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,12 +13,13 @@ 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; -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,7 +91,11 @@ public class AmqpControllerAuthentfication { tenantConfigurationManagement, controllerManagement, tenantAware, systemSecurityContext); filterChain.add(securityTokenFilter); - filterChain.add(new CoapAnonymousPreAuthenticatedFilter()); + final ControllerPreAuthenticatedAnonymousDownload anonymousDownloadFilter = new ControllerPreAuthenticatedAnonymousDownload( + tenantConfigurationManagement, tenantAware, systemSecurityContext); + filterChain.add(anonymousDownloadFilter); + + filterChain.add(new ControllerPreAuthenticatedAnonymousFilter(ddiSecruityProperties)); } /** @@ -100,7 +105,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 +120,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/AmqpDeadletterProperties.java b/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpDeadletterProperties.java new file mode 100644 index 000000000..7ed5e90c1 --- /dev/null +++ b/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpDeadletterProperties.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.amqp; + +import java.time.Duration; +import java.util.HashMap; +import java.util.Map; + +import org.springframework.amqp.core.Queue; +import org.springframework.boot.context.properties.ConfigurationProperties; + +/** + * Bean which holds the necessary properties for configuring the AMQP deadletter + * queue. + */ +@ConfigurationProperties("hawkbit.dmf.rabbitmq.deadLetter") +public class AmqpDeadletterProperties { + + /** + * Message time to live (ttl) for the deadletter queue. Default ttl is 3 + * weeks. + */ + private long ttl = Duration.ofDays(21).toMillis(); + + /** + * Return the deadletter arguments. + * + * @param exchange + * the deadletter exchange + * @return map which holds the properties + */ + public Map getDeadLetterExchangeArgs(final String exchange) { + final Map args = new HashMap<>(); + args.put("x-dead-letter-exchange", exchange); + return args; + } + + /** + * Create a deadletter queue with ttl for messages + * + * @param queueName + * the deadlette queue name + * @return the deadletter queue + */ + public Queue createDeadletterQueue(final String queueName) { + return new Queue(queueName, true, false, false, getTTLArgs()); + } + + private Map getTTLArgs() { + final Map args = new HashMap<>(); + args.put("x-message-ttl", getTtl()); + return args; + } + + public long getTtl() { + return ttl; + } + + public void setTtl(final long ttl) { + this.ttl = ttl; + } + +} 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..dae5772e6 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; @@ -81,6 +82,7 @@ public class AmqpMessageDispatcherService extends BaseAmqpService { .getSoftwareModules(); final DownloadAndUpdateRequest downloadAndUpdateRequest = new DownloadAndUpdateRequest(); downloadAndUpdateRequest.setActionId(targetAssignDistributionSetEvent.getActionId()); + downloadAndUpdateRequest.setTargetSecurityToken(targetAssignDistributionSetEvent.getTargetToken()); for (final org.eclipse.hawkbit.repository.model.SoftwareModule softwareModule : modules) { final SoftwareModule amqpSoftwareModule = convertToAmqpSoftwareModule(controllerId, softwareModule); @@ -152,15 +154,27 @@ 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)); - artifact.getUrls().put(Artifact.UrlProtocol.HTTP, - artifactUrlHandler.getUrl(targetId, localArtifact, Artifact.UrlProtocol.HTTP)); - artifact.getUrls().put(Artifact.UrlProtocol.HTTPS, - artifactUrlHandler.getUrl(targetId, localArtifact, Artifact.UrlProtocol.HTTPS)); + + if (artifactUrlHandler.protocolSupported(UrlProtocol.COAP)) { + artifact.getUrls().put(Artifact.UrlProtocol.COAP, + artifactUrlHandler.getUrl(targetId, localArtifact.getSoftwareModule().getId(), + localArtifact.getFilename(), localArtifact.getSha1Hash(), UrlProtocol.COAP)); + } + + if (artifactUrlHandler.protocolSupported(UrlProtocol.HTTP)) { + artifact.getUrls().put(Artifact.UrlProtocol.HTTP, + artifactUrlHandler.getUrl(targetId, localArtifact.getSoftwareModule().getId(), + localArtifact.getFilename(), localArtifact.getSha1Hash(), UrlProtocol.HTTP)); + } + + if (artifactUrlHandler.protocolSupported(UrlProtocol.HTTPS)) { + artifact.getUrls().put(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)); + artifact.setHashes(new ArtifactHash(localArtifact.getSha1Hash(), localArtifact.getMd5Hash())); artifact.setSize(localArtifact.getSize()); return artifact; } 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..f26d7f3f7 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 @@ -28,7 +28,8 @@ 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.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.im.authentication.SpPermission.SpringEvalExpressions; import org.eclipse.hawkbit.im.authentication.TenantAwareAuthenticationDetails; @@ -157,25 +158,20 @@ 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) { + LOG.info("target {} requested file resource {} which does not exists to download", + secruityToken.getControllerId(), fileResource); 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()); + checkIfArtifactIsAssignedToTarget(secruityToken, localArtifact); final Artifact artifact = convertDbArtifact(artifactManagement.loadLocalArtifactBinary(localArtifact)); if (artifact == null) { @@ -183,7 +179,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 +196,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 +205,50 @@ public class AmqpMessageHandlerService extends BaseAmqpService { return getMessageConverter().toMessage(authentificationResponse, messageProperties); } + /** + * 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. Otherwise no controllerId is set = anonymous download + * + * @param secruityToken + * the security token which holds the target ID to check on + * @param localArtifact + * the local artifact to verify if the given target is allowed to + * download this artifact + */ + private void checkIfArtifactIsAssignedToTarget(final TenantSecurityToken secruityToken, + final LocalArtifact localArtifact) { + final String controllerId = secruityToken.getControllerId(); + if (controllerId == null) { + LOG.info("anonymous download no authentication check for artifact {}", localArtifact); + return; + } + LOG.debug("no anonymous download request, doing authentication check for target {} and artifact {}", + controllerId, localArtifact); + if (!controllerManagement.hasTargetArtifactAssigned(controllerId, localArtifact)) { + LOG.info("target {} tried to download artifact {} which is not assigned to the target", controllerId, + localArtifact); + throw new EntityNotFoundException(); + } + LOG.info("download security check for target {} and artifact {} granted", controllerId, localArtifact); + } + + private LocalArtifact findLocalArtifactByFileResource(final FileResource fileResource) { + if (fileResource.getSha1() != null) { + return artifactManagement.findFirstLocalArtifactsBySHA1(fileResource.getSha1()); + } else if (fileResource.getFilename() != null) { + return artifactManagement.findLocalArtifactByFilename(fileResource.getFilename()).stream().findFirst() + .orElse(null); + } else if (fileResource.getSoftwareModuleFilenameResource() != null) { + return artifactManagement + .findByFilenameAndSoftwareModule(fileResource.getSoftwareModuleFilenameResource().getFilename(), + fileResource.getSoftwareModuleFilenameResource().getSoftwareModuleId()) + .stream().findFirst().orElse(null); + } + return null; + } + private static Artifact convertDbArtifact(final DbArtifact dbArtifact) { final Artifact artifact = new Artifact(); artifact.setSize(dbArtifact.getSize()); @@ -263,7 +305,8 @@ public class AmqpMessageHandlerService extends BaseAmqpService { final List softwareModuleList = controllerManagement .findSoftwareModulesByDistributionSet(distributionSet); eventBus.post(new TargetAssignDistributionSetEvent(target.getOptLockRevision(), target.getTenant(), - target.getControllerId(), action.getId(), softwareModuleList, target.getTargetInfo().getAddress())); + target.getControllerId(), action.getId(), softwareModuleList, target.getTargetInfo().getAddress(), + target.getSecurityToken())); } @@ -294,9 +337,8 @@ public class AmqpMessageHandlerService extends BaseAmqpService { final Action action = checkActionExist(message, actionUpdateStatus); final ActionStatus actionStatus = new ActionStatus(); - final List messageText = actionUpdateStatus.getMessage(); - final String messageString = String.join(", ", messageText); - actionStatus.addMessage(messageString); + actionUpdateStatus.getMessage().forEach(actionStatus::addMessage); + actionStatus.setAction(action); actionStatus.setOccurredAt(System.currentTimeMillis()); diff --git a/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpProperties.java b/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpProperties.java index 38c6d34b3..ce6068ce8 100644 --- a/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpProperties.java +++ b/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpProperties.java @@ -21,7 +21,7 @@ public class AmqpProperties { /** * DMF API dead letter queue. */ - private String deadLetterQueue = "dmf_connector_deadletter"; + private String deadLetterQueue = "dmf_connector_deadletter_ttl"; /** * DMF API dead letter exchange. diff --git a/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpSenderService.java b/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpSenderService.java index 6cb3dd9be..f44e2e9bb 100644 --- a/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpSenderService.java +++ b/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/AmqpSenderService.java @@ -24,10 +24,10 @@ public interface AmqpSenderService { * * @param message * the amqp message - * @param uri + * @param replyTo * the reply to uri */ - void sendMessage(Message message, URI uri); + void sendMessage(Message message, URI replyTo); /** * Extract the exchange from the uri. Default implementation removes the diff --git a/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/BaseAmqpService.java b/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/BaseAmqpService.java index 8a054165b..76870ac93 100644 --- a/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/BaseAmqpService.java +++ b/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/BaseAmqpService.java @@ -59,7 +59,7 @@ public class BaseAmqpService { */ @SuppressWarnings("unchecked") public T convertMessage(final Message message, final Class clazz) { - if (message == null || message.getBody() == null) { + if (isMessageBodyEmpty(message)) { return null; } message.getMessageProperties().getHeaders().put(AbstractJavaTypeMapper.DEFAULT_CLASSID_FIELD_NAME, @@ -67,6 +67,10 @@ public class BaseAmqpService { return (T) rabbitTemplate.getMessageConverter().fromMessage(message); } + private boolean isMessageBodyEmpty(final Message message) { + return message == null || message.getBody() == null || message.getBody().length == 0; + } + /** * Is needed to convert a incoming message to is originally list object * type. @@ -79,7 +83,7 @@ public class BaseAmqpService { */ @SuppressWarnings("unchecked") public List convertMessageList(final Message message, final Class clazz) { - if (message == null || message.getBody() == null) { + if (isMessageBodyEmpty(message)) { return Collections.emptyList(); } message.getMessageProperties().getHeaders().put(AbstractJavaTypeMapper.DEFAULT_CLASSID_FIELD_NAME, @@ -105,7 +109,7 @@ public class BaseAmqpService { } protected final void logAndThrowMessageError(final Message message, final String error) { - LOGGER.error("Error \"{}\" reported by message {}", error, message.getMessageProperties().getMessageId()); + LOGGER.warn("Error \"{}\" reported by message: {}", error, message); throw new IllegalArgumentException(error); } diff --git a/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/DefaultAmqpSenderService.java b/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/DefaultAmqpSenderService.java index 9586633bf..244544b64 100644 --- a/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/DefaultAmqpSenderService.java +++ b/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/amqp/DefaultAmqpSenderService.java @@ -10,6 +10,7 @@ package org.eclipse.hawkbit.amqp; import java.net.URI; +import org.eclipse.hawkbit.util.IpUtil; import org.springframework.amqp.core.Message; import org.springframework.amqp.rabbit.core.RabbitTemplate; @@ -33,8 +34,12 @@ public class DefaultAmqpSenderService implements AmqpSenderService { } @Override - public void sendMessage(final Message message, final URI uri) { - internalAmqpTemplate.send(extractExchange(uri), null, message); + public void sendMessage(final Message message, final URI replyTo) { + if (!IpUtil.isAmqpUri(replyTo)) { + return; + } + + internalAmqpTemplate.send(extractExchange(replyTo), null, message); } } diff --git a/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/util/ArtifactUrlHandler.java b/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/util/ArtifactUrlHandler.java deleted file mode 100644 index f477da03a..000000000 --- a/hawkbit-dmf-amqp/src/main/java/org/eclipse/hawkbit/util/ArtifactUrlHandler.java +++ /dev/null @@ -1,35 +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.util; - -import org.eclipse.hawkbit.dmf.json.model.Artifact; -import org.eclipse.hawkbit.repository.model.LocalArtifact; - -/** - * Interface declaration of the {@link ArtifactUrlHandler} which generates the - * URLs to specific artifacts. - * - */ -@FunctionalInterface -public interface ArtifactUrlHandler { - - /** - * Returns a generated URL for a given artifact for a specific protocol. - * - * @param controllerId - * the authentifacted 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); - -} 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..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 @@ -19,12 +19,14 @@ 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; 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; @@ -79,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); @@ -105,7 +113,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 +127,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 +145,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 +160,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 +179,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 +202,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/AmqpMessageDispatcherServiceTest.java b/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/AmqpMessageDispatcherServiceTest.java index 46ddd35cc..9164e655d 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 @@ -8,11 +8,12 @@ */ package org.eclipse.hawkbit.amqp; +import static org.fest.assertions.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; -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; @@ -22,9 +23,11 @@ import static org.mockito.Mockito.when; import java.net.URI; import java.util.ArrayList; import java.util.List; +import java.util.Optional; 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 +39,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; @@ -57,6 +59,12 @@ import ru.yandex.qatools.allure.annotations.Stories; @Stories("AmqpMessage Dispatcher Service Test") public class AmqpMessageDispatcherServiceTest extends AbstractIntegrationTestWithMongoDB { + private static final String TENANT = "default"; + + private static final URI AMQP_URI = IpUtil.createAmqpUri("vHost", "mytest"); + + private static final String TEST_TOKEN = "testToken"; + private AmqpMessageDispatcherService amqpMessageDispatcherService; private RabbitTemplate rabbitTemplate; @@ -77,7 +85,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); @@ -87,11 +96,11 @@ public class AmqpMessageDispatcherServiceTest extends AbstractIntegrationTestWit @Description("Verfies that download and install event with no software modul works") public void testSendDownloadRequesWithEmptySoftwareModules() { final TargetAssignDistributionSetEvent targetAssignDistributionSetEvent = new TargetAssignDistributionSetEvent( - 1L, "default", CONTROLLER_ID, 1l, new ArrayList(), - IpUtil.createAmqpUri("vHost", "mytest")); + 1L, TENANT, CONTROLLER_ID, 1L, new ArrayList(), AMQP_URI, TEST_TOKEN); amqpMessageDispatcherService.targetAssignDistributionSet(targetAssignDistributionSetEvent); final Message sendMessage = createArgumentCapture(targetAssignDistributionSetEvent.getTargetAdress()); final DownloadAndUpdateRequest downloadAndUpdateRequest = assertDownloadAndInstallMessage(sendMessage); + assertThat(downloadAndUpdateRequest.getTargetSecurityToken()).isEqualTo(TEST_TOKEN); assertTrue("No softwaremmodule should be contained in the request", downloadAndUpdateRequest.getSoftwareModules().isEmpty()); } @@ -102,12 +111,13 @@ public class AmqpMessageDispatcherServiceTest extends AbstractIntegrationTestWit final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement, distributionSetManagement); final TargetAssignDistributionSetEvent targetAssignDistributionSetEvent = new TargetAssignDistributionSetEvent( - 1L, "default", CONTROLLER_ID, 1l, dsA.getModules(), IpUtil.createAmqpUri("vHost", "mytest")); + 1L, TENANT, CONTROLLER_ID, 1L, dsA.getModules(), AMQP_URI, TEST_TOKEN); amqpMessageDispatcherService.targetAssignDistributionSet(targetAssignDistributionSetEvent); final Message sendMessage = createArgumentCapture(targetAssignDistributionSetEvent.getTargetAdress()); final DownloadAndUpdateRequest downloadAndUpdateRequest = assertDownloadAndInstallMessage(sendMessage); assertEquals("Expecting a size of 3 software modules in the reuqest", 3, downloadAndUpdateRequest.getSoftwareModules().size()); + assertThat(downloadAndUpdateRequest.getTargetSecurityToken()).isEqualTo(TEST_TOKEN); for (final org.eclipse.hawkbit.dmf.json.model.SoftwareModule softwareModule : downloadAndUpdateRequest .getSoftwareModules()) { assertTrue("Artifact list for softwaremodule should be empty", softwareModule.getArtifacts().isEmpty()); @@ -141,18 +151,32 @@ public class AmqpMessageDispatcherServiceTest extends AbstractIntegrationTestWit Mockito.when(rabbitTemplate.convertSendAndReceive(any())).thenReturn(receivedList); final TargetAssignDistributionSetEvent targetAssignDistributionSetEvent = new TargetAssignDistributionSetEvent( - 1L, "default", CONTROLLER_ID, 1l, dsA.getModules(), IpUtil.createAmqpUri("vHost", "mytest")); + 1L, TENANT, CONTROLLER_ID, 1L, dsA.getModules(), AMQP_URI, TEST_TOKEN); amqpMessageDispatcherService.targetAssignDistributionSet(targetAssignDistributionSetEvent); final Message sendMessage = createArgumentCapture(targetAssignDistributionSetEvent.getTargetAdress()); final DownloadAndUpdateRequest downloadAndUpdateRequest = assertDownloadAndInstallMessage(sendMessage); assertEquals("DownloadAndUpdateRequest event should contains 3 software modules", 3, downloadAndUpdateRequest.getSoftwareModules().size()); + assertThat(downloadAndUpdateRequest.getTargetSecurityToken()).isEqualTo(TEST_TOKEN); + for (final org.eclipse.hawkbit.dmf.json.model.SoftwareModule softwareModule : downloadAndUpdateRequest .getSoftwareModules()) { if (!softwareModule.getModuleId().equals(module.getId())) { continue; } - assertFalse("The software module artifacts should not be empty", softwareModule.getArtifacts().isEmpty()); + assertThat(softwareModule.getArtifacts().size()).isEqualTo(module.getArtifacts().size()).isGreaterThan(0); + + module.getArtifacts().forEach(dbArtifact -> { + final Optional found = softwareModule.getArtifacts() + .stream().filter(dmfartifact -> dmfartifact.getFilename() + .equals(((LocalArtifact) dbArtifact).getFilename())) + .findFirst(); + + assertTrue("The artifact should exist in message", found.isPresent()); + assertThat(found.get().getSize()).isEqualTo(dbArtifact.getSize()); + assertThat(found.get().getHashes().getMd5()).isEqualTo(dbArtifact.getMd5Hash()); + assertThat(found.get().getHashes().getSha1()).isEqualTo(dbArtifact.getSha1Hash()); + }); } } @@ -160,7 +184,7 @@ public class AmqpMessageDispatcherServiceTest extends AbstractIntegrationTestWit @Description("Verfies that send cancel event works") public void testSendCancelRequest() { final CancelTargetAssignmentEvent cancelTargetAssignmentDistributionSetEvent = new CancelTargetAssignmentEvent( - 1L, "default", CONTROLLER_ID, 1l, IpUtil.createAmqpUri("vHost", "mytest")); + 1L, TENANT, CONTROLLER_ID, 1L, AMQP_URI); amqpMessageDispatcherService .targetCancelAssignmentToDistributionSet(cancelTargetAssignmentDistributionSetEvent); final Message sendMessage = createArgumentCapture(cancelTargetAssignmentDistributionSetEvent.getTargetAdress()); @@ -185,13 +209,12 @@ public class AmqpMessageDispatcherServiceTest extends AbstractIntegrationTestWit downloadAndUpdateRequest.getActionId(), Long.valueOf(1)); assertEquals("The topic of the event shuold contain DOWNLOAD_AND_INSTALL", EventTopic.DOWNLOAD_AND_INSTALL, sendMessage.getMessageProperties().getHeaders().get(MessageHeaderKey.TOPIC)); + assertEquals("Security token of target", downloadAndUpdateRequest.getTargetSecurityToken(), TEST_TOKEN); + return downloadAndUpdateRequest; } - /** - * @param sendMessage - */ private void assertEventMessage(final Message sendMessage) { assertNotNull("The message should not be null", sendMessage); 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..3051e4e22 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,17 +307,16 @@ 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); // mock final LocalArtifact localArtifactMock = mock(LocalArtifact.class); - final Action actionMock = mock(Action.class); final DbArtifact dbArtifactMock = mock(DbArtifact.class); when(artifactManagementMock.findFirstLocalArtifactsBySHA1(anyString())).thenReturn(localArtifactMock); - when(controllerManagementMock.getActionForDownloadByTargetAndSoftwareModule(anyObject(), anyObject())) - .thenReturn(actionMock); + when(controllerManagementMock.hasTargetArtifactAssigned(securityToken.getControllerId(), localArtifactMock)) + .thenReturn(true); when(artifactManagementMock.loadLocalArtifactBinary(localArtifactMock)).thenReturn(dbArtifactMock); when(dbArtifactMock.getArtifactId()).thenReturn("artifactId"); when(dbArtifactMock.getSize()).thenReturn(1L); @@ -333,20 +333,22 @@ public class AmqpMessageHandlerServiceTest { assertThat(downloadResponse.getResponseCode()).as("Message body response code is wrong") .isEqualTo(HttpStatus.OK.value()); assertThat(downloadResponse.getArtifact().getSize()).as("Wrong artifact size in message body").isEqualTo(1L); + assertThat(downloadResponse.getArtifact().getHashes().getSha1()).as("Wrong sha1 hash").isEqualTo("sha1"); + assertThat(downloadResponse.getArtifact().getHashes().getMd5()).as("Wrong md5 hash").isEqualTo("md5"); assertThat(downloadResponse.getDownloadUrl()).as("download url is wrong") .startsWith("http://localhost/api/v1/downloadserver/downloadId/"); } @Test @Description("Tests TODO") - public void lookupNextUpdateActionAfterFinished() throws IllegalArgumentException, IllegalAccessException { + public void lookupNextUpdateActionAfterFinished() throws IllegalAccessException { // Mock final Action action = createActionWithTarget(22L, Status.FINISHED); when(controllerManagementMock.findActionWithDetails(Matchers.any())).thenReturn(action); when(controllerManagementMock.addUpdateActionStatus(Matchers.any(), Matchers.any())).thenReturn(action); // for the test the same action can be used - final List actionList = new ArrayList(); + final List actionList = new ArrayList<>(); actionList.add(action); when(controllerManagementMock.findActionByTargetAndActive(Matchers.any())).thenReturn(actionList); @@ -372,6 +374,8 @@ public class AmqpMessageHandlerServiceTest { assertThat(targetAssignDistributionSetEvent.getControllerId()).as("event has wrong controller id") .isEqualTo("target1"); + assertThat(targetAssignDistributionSetEvent.getTargetToken()).as("targetoken not filled correctly") + .isEqualTo(action.getTarget().getSecurityToken()); assertThat(targetAssignDistributionSetEvent.getActionId()).as("event has wrong action id").isEqualTo(22L); assertThat(targetAssignDistributionSetEvent.getSoftwareModules()).as("event has wrong sofware modules") .isEqualTo(softwareModuleList); @@ -379,7 +383,7 @@ public class AmqpMessageHandlerServiceTest { } private ActionUpdateStatus createActionUpdateStatus(final ActionStatus status) { - return createActionUpdateStatus(status, 2l); + return createActionUpdateStatus(status, 2L); } private ActionUpdateStatus createActionUpdateStatus(final ActionStatus status, final Long id) { @@ -404,15 +408,14 @@ public class AmqpMessageHandlerServiceTest { } private List createSoftwareModuleList() { - final List softwareModuleList = new ArrayList(); + final List softwareModuleList = new ArrayList<>(); final SoftwareModule softwareModule = new SoftwareModule(); softwareModule.setId(777L); softwareModuleList.add(softwareModule); return softwareModuleList; } - private Action createActionWithTarget(final Long targetId, final Status status) - throws IllegalArgumentException, IllegalAccessException { + private Action createActionWithTarget(final Long targetId, final Status status) throws IllegalAccessException { // is needed for the creation of targets initalizeSecurityTokenGenerator(); @@ -427,7 +430,7 @@ public class AmqpMessageHandlerServiceTest { return action; } - private void initalizeSecurityTokenGenerator() throws IllegalArgumentException, IllegalAccessException { + private void initalizeSecurityTokenGenerator() throws IllegalAccessException { final SecurityTokenGeneratorHolder instance = SecurityTokenGeneratorHolder.getInstance(); final Field[] fields = instance.getClass().getDeclaredFields(); for (final Field field : fields) { diff --git a/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/BaseAmqpServiceTest.java b/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/BaseAmqpServiceTest.java index 0bd8c164b..20d03bdd6 100644 --- a/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/BaseAmqpServiceTest.java +++ b/hawkbit-dmf-amqp/src/test/java/org/eclipse/hawkbit/amqp/BaseAmqpServiceTest.java @@ -52,6 +52,8 @@ public class BaseAmqpServiceTest { final ActionUpdateStatus actionUpdateStatus = new ActionUpdateStatus(); actionUpdateStatus.setActionId(1L); actionUpdateStatus.setSoftwareModuleId(2L); + actionUpdateStatus.getMessage().add("Message 1"); + actionUpdateStatus.getMessage().add("Message 2"); final Message message = rabbitTemplate.getMessageConverter().toMessage(actionUpdateStatus, new MessageProperties()); 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..f9a2ea316 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") @@ -39,12 +39,17 @@ import ru.yandex.qatools.allure.annotations.Stories; AmqpTestConfiguration.class }) public class PropertyBasedArtifactUrlHandlerTest extends AbstractIntegrationTestWithMongoDB { + private static final String HTTPS_LOCALHOST = "https://localhost:8080/"; + private static final String HTTP_LOCALHOST = "http://localhost:8080/"; @Autowired private ArtifactUrlHandler urlHandlerProperties; @Autowired 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,25 +58,31 @@ 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/" - + localArtifact.getFilename(), + HTTP_LOCALHOST + tenantAware.getCurrentTenant() + "/controller/v1/" + controllerId + "/softwaremodules/" + + localArtifact.getSoftwareModule().getId() + "/artifacts/" + localArtifact.getFilename(), url); } @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 + HTTPS_LOCALHOST + tenantAware.getCurrentTenant() + "/controller/v1/" + controllerId + "/softwaremodules/" + localArtifact.getSoftwareModule().getId() + "/artifacts/" + localArtifact.getFilename(), url); @@ -80,7 +91,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-dmf-api/src/main/java/org/eclipse/hawkbit/dmf/json/model/ArtifactHash.java b/hawkbit-dmf-api/src/main/java/org/eclipse/hawkbit/dmf/json/model/ArtifactHash.java index 5ddb48e4f..6f86fe4a4 100644 --- a/hawkbit-dmf-api/src/main/java/org/eclipse/hawkbit/dmf/json/model/ArtifactHash.java +++ b/hawkbit-dmf-api/src/main/java/org/eclipse/hawkbit/dmf/json/model/ArtifactHash.java @@ -13,10 +13,6 @@ import com.fasterxml.jackson.annotation.JsonProperty; /** * JSON representation of artifact hash. - * - * - * - * */ public class ArtifactHash { diff --git a/hawkbit-dmf-api/src/main/java/org/eclipse/hawkbit/dmf/json/model/DownloadAndUpdateRequest.java b/hawkbit-dmf-api/src/main/java/org/eclipse/hawkbit/dmf/json/model/DownloadAndUpdateRequest.java index 4344c5416..88cb80975 100644 --- a/hawkbit-dmf-api/src/main/java/org/eclipse/hawkbit/dmf/json/model/DownloadAndUpdateRequest.java +++ b/hawkbit-dmf-api/src/main/java/org/eclipse/hawkbit/dmf/json/model/DownloadAndUpdateRequest.java @@ -19,15 +19,16 @@ import com.fasterxml.jackson.annotation.JsonProperty; /** * JSON representation of download and update request. * - * - * - * */ @JsonInclude(Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) public class DownloadAndUpdateRequest { @JsonProperty private Long actionId; + + @JsonProperty + private String targetSecurityToken; + @JsonProperty private final List softwareModules = new LinkedList<>(); @@ -39,6 +40,14 @@ public class DownloadAndUpdateRequest { this.actionId = correlator; } + public String getTargetSecurityToken() { + return targetSecurityToken; + } + + public void setTargetSecurityToken(final String targetSecurityToken) { + this.targetSecurityToken = targetSecurityToken; + } + public List getSoftwareModules() { return softwareModules; } 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..e4f41bc46 --- /dev/null +++ b/hawkbit-dmf-api/src/main/java/org/eclipse/hawkbit/dmf/json/model/TenantSecurityToken.java @@ -0,0 +1,224 @@ +/** + * 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"; + + @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 SoftwareModuleFilenameResource softwareModuleFilenameResource; + + 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 SoftwareModuleFilenameResource getSoftwareModuleFilenameResource() { + return softwareModuleFilenameResource; + } + + public void setSoftwareModuleFilenameResource( + final SoftwareModuleFilenameResource softwareModuleFilenameResource) { + this.softwareModuleFilenameResource = softwareModuleFilenameResource; + } + + /** + * 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 softwaremodule + + * filename lookup, because an filename is not globally unique but + * within a softwaremodule. + * + * @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 softwareModuleFilename(final Long softwareModuleId, final String filename) { + final FileResource resource = new FileResource(); + resource.softwareModuleFilenameResource = new SoftwareModuleFilenameResource(softwareModuleId, filename); + return resource; + } + + @Override + 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 Long softwareModuleId; + @JsonProperty(required = false) + private 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; + } + + public void setSoftwareModuleId(final Long softwareModuleId) { + this.softwareModuleId = softwareModuleId; + } + + public void setFilename(final String filename) { + this.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..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,14 +18,19 @@ 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.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; 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; @@ -79,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 { @@ -96,7 +95,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; @@ -112,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. * @@ -121,7 +132,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 +164,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 +174,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 +183,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-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-http-security/src/test/java/org/eclipse/hawkbit/security/PreAuthTokenSourceTrustAuthenticationProviderTest.java b/hawkbit-http-security/src/test/java/org/eclipse/hawkbit/security/PreAuthTokenSourceTrustAuthenticationProviderTest.java index fb961f9b2..eb4cacf33 100644 --- a/hawkbit-http-security/src/test/java/org/eclipse/hawkbit/security/PreAuthTokenSourceTrustAuthenticationProviderTest.java +++ b/hawkbit-http-security/src/test/java/org/eclipse/hawkbit/security/PreAuthTokenSourceTrustAuthenticationProviderTest.java @@ -9,6 +9,7 @@ package org.eclipse.hawkbit.security; import static org.fest.assertions.Assertions.assertThat; +import static org.junit.Assert.fail; import static org.mockito.Mockito.when; import org.junit.Test; @@ -20,6 +21,7 @@ import org.springframework.security.authentication.InsufficientAuthenticationExc import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken; +import ru.yandex.qatools.allure.annotations.Description; import ru.yandex.qatools.allure.annotations.Features; import ru.yandex.qatools.allure.annotations.Stories; @@ -38,11 +40,8 @@ public class PreAuthTokenSourceTrustAuthenticationProviderTest { @Mock private TenantAwareWebAuthenticationDetails webAuthenticationDetailsMock; - /** - * Testing in case the containing controllerId in the URI request path does - * not accord with the controllerId in the request header. - */ - @Test(expected = BadCredentialsException.class) + @Test + @Description("Testing in case the containing controllerId in the URI request path does not accord with the controllerId in the request header.") public void principalAndCredentialsNotTheSameThrowsAuthenticationException() { final String principal = "controllerIdURL"; final String credentials = "controllerIdHeader"; @@ -51,15 +50,17 @@ public class PreAuthTokenSourceTrustAuthenticationProviderTest { token.setDetails(webAuthenticationDetailsMock); // test, should throw authentication exception - underTestWithoutSourceIpCheck.authenticate(token); + try { + underTestWithoutSourceIpCheck.authenticate(token); + fail("Should not work with wrong credentials"); + } catch (final BadCredentialsException e) { + + } + } - /** - * Testing that the controllerId within the URI request path is the same - * with the controllerId within the request header and no source IP check is - * in place. - */ @Test + @Description("Testing that the controllerId within the URI request path is the same with the controllerId within the request header and no source IP check is in place.") public void principalAndCredentialsAreTheSameWithNoSourceIpCheckIsSuccessful() { final String principal = "controllerId"; final String credentials = "controllerId"; @@ -71,12 +72,8 @@ public class PreAuthTokenSourceTrustAuthenticationProviderTest { assertThat(authenticate.isAuthenticated()).isTrue(); } - /** - * Testing that the controllerId in the URI request match with the - * controllerId in the request header but the request are not coming from a - * trustful source. - */ - @Test(expected = InsufficientAuthenticationException.class) + @Test + @Description("Testing that the controllerId in the URI request match with the controllerId in the request header but the request are not coming from a trustful source.") public void priniciapAndCredentialsAreTheSameButSourceIpRequestNotMatching() { final String remoteAddress = "192.168.1.1"; final String principal = "controllerId"; @@ -88,16 +85,17 @@ public class PreAuthTokenSourceTrustAuthenticationProviderTest { when(webAuthenticationDetailsMock.getRemoteAddress()).thenReturn(remoteAddress); // test, should throw authentication exception - final Authentication authenticate = underTestWithSourceIpCheck.authenticate(token); - assertThat(authenticate.isAuthenticated()).isTrue(); + + try { + underTestWithSourceIpCheck.authenticate(token); + fail("as source is not trusted."); + } catch (final InsufficientAuthenticationException e) { + + } } - /** - * Testing that the controllerId in the URI request match with the - * controllerId in the request header and the source Ip is matching the - * allowed remote IP address. - */ - @Test() + @Test + @Description("Testing that the controllerId in the URI request match with the controllerId in the request header and the source Ip is matching the allowed remote IP address.") public void priniciapAndCredentialsAreTheSameAndSourceIpIsTrusted() { final String principal = "controllerId"; final String credentials = "controllerId"; @@ -112,7 +110,7 @@ public class PreAuthTokenSourceTrustAuthenticationProviderTest { assertThat(authenticate.isAuthenticated()).isTrue(); } - @Test() + @Test public void priniciapAndCredentialsAreTheSameAndSourceIpIsWithinList() { final String[] trustedIPAddresses = new String[] { "192.168.1.1", "192.168.1.2", REQUEST_SOURCE_IP, "192.168.1.3" }; @@ -148,6 +146,11 @@ public class PreAuthTokenSourceTrustAuthenticationProviderTest { // test, should throw authentication exception final Authentication authenticate = underTestWithList.authenticate(token); - assertThat(authenticate.isAuthenticated()).isTrue(); + try { + assertThat(authenticate.isAuthenticated()).isTrue(); + fail("as source is not trusted."); + } catch (final InsufficientAuthenticationException e) { + + } } } diff --git a/hawkbit-mgmt-api/README.md b/hawkbit-mgmt-api/README.md new file mode 100644 index 000000000..eeb51c145 --- /dev/null +++ b/hawkbit-mgmt-api/README.md @@ -0,0 +1,14 @@ +# Eclipse.IoT hawkBit - Mgmt API + +This Management (Mgmt) API is used to manage and monitor the HawkBit Update Server via HTTP. This API allows Create/Read/Update/Delete operations for provisioning targets (i.e. devices) and repository content (i.e. software). + + +# Compile + +#### Build hawkbit-mgmt-api + +``` +$ cd hawkbit/hawkbit-mgmt-api +$ mvn clean install +``` + diff --git a/hawkbit-rest-api/pom.xml b/hawkbit-mgmt-api/pom.xml similarity index 66% rename from hawkbit-rest-api/pom.xml rename to hawkbit-mgmt-api/pom.xml index be9abafac..4c99cd7bc 100644 --- a/hawkbit-rest-api/pom.xml +++ b/hawkbit-mgmt-api/pom.xml @@ -16,16 +16,10 @@ hawkbit-parent 0.2.0-SNAPSHOT - hawkbit-rest-api - hawkBit :: REST API - + hawkbit-mgmt-api + hawkBit :: Mgmt REST API - - javax.validation - validation-api - 1.1.0.Final - org.springframework.hateoas spring-hateoas @@ -34,5 +28,26 @@ com.fasterxml.jackson.core jackson-annotations + + javax.validation + validation-api + + + javax.servlet + javax.servlet-api + provided + + + + + org.easytesting + fest-assert + test + + + ru.yandex.qatools.allure + allure-junit-adaptor + test + \ No newline at end of file diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/BaseEntityRest.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/MgmtBaseEntity.java similarity index 94% rename from hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/BaseEntityRest.java rename to hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/MgmtBaseEntity.java index 6d80a407c..728734050 100644 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/BaseEntityRest.java +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/MgmtBaseEntity.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource.model; +package org.eclipse.hawkbit.mgmt.json.model; import org.springframework.hateoas.ResourceSupport; @@ -17,7 +17,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; * A json annotated rest model for BaseEntity to RESTful API representation. * */ -public abstract class BaseEntityRest extends ResourceSupport { +public abstract class MgmtBaseEntity extends ResourceSupport { @JsonProperty private String createdBy; diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/IdRest.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/MgmtId.java similarity index 92% rename from hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/IdRest.java rename to hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/MgmtId.java index d15114d4e..e83c43d52 100644 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/IdRest.java +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/MgmtId.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource.model; +package org.eclipse.hawkbit.mgmt.json.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; @@ -18,7 +18,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; * */ @JsonIgnoreProperties(ignoreUnknown = true) -public class IdRest { +public class MgmtId { @JsonProperty private Long id; diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/MetadataRest.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/MgmtMetadata.java similarity index 94% rename from hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/MetadataRest.java rename to hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/MgmtMetadata.java index a5c24c4a9..6a6371d6b 100644 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/MetadataRest.java +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/MgmtMetadata.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource.model; +package org.eclipse.hawkbit.mgmt.json.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; @@ -19,7 +19,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; */ @JsonInclude(Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) -public class MetadataRest { +public class MgmtMetadata { @JsonProperty(required = true) private String key; diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/NamedEntityRest.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/MgmtNamedEntity.java similarity index 91% rename from hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/NamedEntityRest.java rename to hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/MgmtNamedEntity.java index d82d14f75..d335261ad 100644 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/NamedEntityRest.java +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/MgmtNamedEntity.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource.model; +package org.eclipse.hawkbit.mgmt.json.model; import com.fasterxml.jackson.annotation.JsonProperty; @@ -14,7 +14,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; * A json annotated rest model for NamedEntity to RESTful API representation. * */ -public abstract class NamedEntityRest extends BaseEntityRest { +public abstract class MgmtNamedEntity extends MgmtBaseEntity { @JsonProperty(required = true) private String name; diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/PollStatusRest.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/MgmtPollStatus.java similarity index 95% rename from hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/PollStatusRest.java rename to hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/MgmtPollStatus.java index d66d02512..5e5163a6a 100644 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/PollStatusRest.java +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/MgmtPollStatus.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource.model; +package org.eclipse.hawkbit.mgmt.json.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; @@ -22,7 +22,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; */ @JsonInclude(Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) -public class PollStatusRest { +public class MgmtPollStatus { @JsonProperty private Long lastRequestAt; diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/PagedList.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/PagedList.java similarity index 70% rename from hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/PagedList.java rename to hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/PagedList.java index 082015b5c..173f3ce31 100644 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/PagedList.java +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/PagedList.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource.model; +package org.eclipse.hawkbit.mgmt.json.model; import java.util.List; @@ -14,26 +14,29 @@ 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 - * total elements. The content of the acutal list is stored in the - * {@link #content} field. + * total elements and size of content. The content of the actual list is stored + * in the {@link #content} field. * * @param * the type of elements in this list * - * - * */ @JsonIgnoreProperties(ignoreUnknown = true) @JsonInclude(Include.NON_NULL) public class PagedList extends ResourceSupport { - private final long totalElements; + @JsonProperty + private final List content; + @JsonProperty + private final long total; private final int size; /** @@ -47,9 +50,11 @@ public class PagedList extends ResourceSupport { * @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("total") final long total) { this.size = content.size(); - this.totalElements = total; + this.total = total; + this.content = content; } /** @@ -63,6 +68,11 @@ public class PagedList extends ResourceSupport { * @return the total amount of elements */ public long getTotal() { - return totalElements; + return total; } + + public List getContent() { + return content; + } + } diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/action/ActionRest.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/action/MgmtAction.java similarity index 87% rename from hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/action/ActionRest.java rename to hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/action/MgmtAction.java index 3bd57ab20..234e282a0 100644 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/action/ActionRest.java +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/action/MgmtAction.java @@ -6,9 +6,9 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource.model.action; +package org.eclipse.hawkbit.mgmt.json.model.action; -import org.eclipse.hawkbit.rest.resource.model.BaseEntityRest; +import org.eclipse.hawkbit.mgmt.json.model.MgmtBaseEntity; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; @@ -18,21 +18,18 @@ import com.fasterxml.jackson.annotation.JsonProperty; /** * A json annotated rest model for Action to RESTful API representation. * - * - * - * */ @JsonInclude(Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) -public class ActionRest extends BaseEntityRest { +public class MgmtAction extends MgmtBaseEntity { /** - * API definition for {@link UpdateAction}. + * API definition for update action}. */ public static final String ACTION_UPDATE = "update"; /** - * API definition for {@link CancelAction}. + * API definition for cancel action. */ public static final String ACTION_CANCEL = "cancel"; diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/action/ActionStatusRest.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/action/MgmtActionStatus.java similarity index 96% rename from hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/action/ActionStatusRest.java rename to hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/action/MgmtActionStatus.java index 1f08afe49..26120d2d5 100644 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/action/ActionStatusRest.java +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/action/MgmtActionStatus.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource.model.action; +package org.eclipse.hawkbit.mgmt.json.model.action; import java.util.List; @@ -18,13 +18,10 @@ import com.fasterxml.jackson.annotation.JsonProperty; /** * A json annotated rest model for ActionStatus to RESTful API representation. * - * - * - * */ @JsonInclude(Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) -public class ActionStatusRest { +public class MgmtActionStatus { /** * Action is finished successfully for this target. diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/artifact/ArtifactRest.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/artifact/MgmtArtifact.java similarity index 86% rename from hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/artifact/ArtifactRest.java rename to hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/artifact/MgmtArtifact.java index f32a32ed8..afb2d204a 100644 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/artifact/ArtifactRest.java +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/artifact/MgmtArtifact.java @@ -6,9 +6,9 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource.model.artifact; +package org.eclipse.hawkbit.mgmt.json.model.artifact; -import org.eclipse.hawkbit.rest.resource.model.BaseEntityRest; +import org.eclipse.hawkbit.mgmt.json.model.MgmtBaseEntity; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @@ -22,7 +22,8 @@ import com.fasterxml.jackson.annotation.JsonValue; */ @JsonInclude(Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) -public class ArtifactRest extends BaseEntityRest { +public class MgmtArtifact extends MgmtBaseEntity { + @JsonProperty(required = true) private ArtifactType type; @@ -30,7 +31,7 @@ public class ArtifactRest extends BaseEntityRest { private Long artifactId; @JsonProperty - private ArtifactHash hashes; + private MgmtArtifactHash hashes; @JsonProperty private String providedFilename; @@ -38,6 +39,11 @@ public class ArtifactRest extends BaseEntityRest { @JsonProperty private Long size; + public MgmtArtifact() { + super(); + // need for json encoder + } + /** * @param type * the type to set @@ -51,7 +57,7 @@ public class ArtifactRest extends BaseEntityRest { * the hashes to set */ @JsonIgnore - public void setHashes(final ArtifactHash hashes) { + public void setHashes(final MgmtArtifactHash hashes) { this.hashes = hashes; } @@ -81,7 +87,7 @@ public class ArtifactRest extends BaseEntityRest { /** * @return the hashes */ - public ArtifactHash getHashes() { + public MgmtArtifactHash getHashes() { return hashes; } @@ -102,11 +108,7 @@ public class ArtifactRest extends BaseEntityRest { } /** - * Type maps to either {@link LocalArtifact} or {@link ExternalArtifact}. - * - * - * - * + * Type maps to either local artifact} or external artifact. */ public enum ArtifactType { LOCAL("local"), EXTERNAL("external"); diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/artifact/ArtifactHash.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/artifact/MgmtArtifactHash.java similarity index 83% rename from hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/artifact/ArtifactHash.java rename to hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/artifact/MgmtArtifactHash.java index 58b81d8fd..d43ae4339 100644 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/artifact/ArtifactHash.java +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/artifact/MgmtArtifactHash.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource.model.artifact; +package org.eclipse.hawkbit.mgmt.json.model.artifact; import com.fasterxml.jackson.annotation.JsonProperty; @@ -15,7 +15,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; * * */ -public class ArtifactHash { +public class MgmtArtifactHash { @JsonProperty private String sha1; @@ -26,7 +26,7 @@ public class ArtifactHash { /** * Default constructor. */ - public ArtifactHash() { + public MgmtArtifactHash() { } /** @@ -35,7 +35,7 @@ public class ArtifactHash { * @param sha1 * @param md5 */ - public ArtifactHash(final String sha1, final String md5) { + public MgmtArtifactHash(final String sha1, final String md5) { super(); this.sha1 = sha1; this.md5 = md5; diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/distributionset/ActionTypeRest.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/distributionset/MgmtActionType.java similarity index 74% rename from hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/distributionset/ActionTypeRest.java rename to hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/distributionset/MgmtActionType.java index bf6a649a0..d95375f5a 100644 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/distributionset/ActionTypeRest.java +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/distributionset/MgmtActionType.java @@ -6,18 +6,15 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource.model.distributionset; +package org.eclipse.hawkbit.mgmt.json.model.distributionset; import com.fasterxml.jackson.annotation.JsonValue; /** - * Definition of the {@link ActionType} for the REST management API. - * - * - * + * Definition of the Action type for the REST management API. * */ -public enum ActionTypeRest { +public enum MgmtActionType { /** * The soft action type. */ @@ -35,13 +32,10 @@ public enum ActionTypeRest { private final String name; - private ActionTypeRest(final String name) { + private MgmtActionType(final String name) { this.name = name; } - /** - * @return the name - */ @JsonValue public String getName() { return name; diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/distributionset/DistributionSetRest.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/distributionset/MgmtDistributionSet.java similarity index 86% rename from hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/distributionset/DistributionSetRest.java rename to hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/distributionset/MgmtDistributionSet.java index 2ff764eba..7caaf4cdd 100644 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/distributionset/DistributionSetRest.java +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/distributionset/MgmtDistributionSet.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.rest.resource.model.distributionset; +package org.eclipse.hawkbit.mgmt.json.model.distributionset; import java.util.ArrayList; import java.util.List; -import org.eclipse.hawkbit.rest.resource.model.NamedEntityRest; -import org.eclipse.hawkbit.rest.resource.model.softwaremodule.SoftwareModuleRest; +import org.eclipse.hawkbit.mgmt.json.model.MgmtNamedEntity; +import org.eclipse.hawkbit.mgmt.json.model.softwaremodule.MgmtSoftwareModule; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @@ -30,7 +30,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; */ @JsonInclude(Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) -public class DistributionSetRest extends NamedEntityRest { +public class MgmtDistributionSet extends MgmtNamedEntity { @JsonProperty(value = "id", required = true) private Long dsId; @@ -39,7 +39,7 @@ public class DistributionSetRest extends NamedEntityRest { private String version; @JsonProperty - private List modules = new ArrayList<>(); + private List modules = new ArrayList<>(); @JsonProperty private boolean requiredMigrationStep; @@ -99,7 +99,7 @@ public class DistributionSetRest extends NamedEntityRest { /** * @return the modules */ - public List getModules() { + public List getModules() { return modules; } @@ -107,7 +107,7 @@ public class DistributionSetRest extends NamedEntityRest { * @param modules * the modules to set */ - public void setModules(final List modules) { + public void setModules(final List modules) { this.modules = modules; } diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/distributionset/DistributionSetRequestBodyPost.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/distributionset/MgmtDistributionSetRequestBodyPost.java similarity index 67% rename from hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/distributionset/DistributionSetRequestBodyPost.java rename to hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/distributionset/MgmtDistributionSetRequestBodyPost.java index bf5470d72..a56b5aaba 100644 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/distributionset/DistributionSetRequestBodyPost.java +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/distributionset/MgmtDistributionSetRequestBodyPost.java @@ -6,11 +6,11 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource.model.distributionset; +package org.eclipse.hawkbit.mgmt.json.model.distributionset; import java.util.List; -import org.eclipse.hawkbit.rest.resource.model.softwaremodule.SoftwareModuleAssigmentRest; +import org.eclipse.hawkbit.mgmt.json.model.softwaremodule.MgmtSoftwareModuleAssigment; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; @@ -23,22 +23,22 @@ import com.fasterxml.jackson.annotation.JsonProperty; */ @JsonInclude(Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) -public class DistributionSetRequestBodyPost extends DistributionSetRequestBodyPut { +public class MgmtDistributionSetRequestBodyPost extends MgmtDistributionSetRequestBodyPut { // deprecated format from the time where os, application and runtime where // statically defined @JsonProperty - private SoftwareModuleAssigmentRest os; + private MgmtSoftwareModuleAssigment os; @JsonProperty - private SoftwareModuleAssigmentRest runtime; + private MgmtSoftwareModuleAssigment runtime; @JsonProperty - private SoftwareModuleAssigmentRest application; + private MgmtSoftwareModuleAssigment application; // deprecated format - END @JsonProperty - private List modules; + private List modules; @JsonProperty private boolean requiredMigrationStep; @@ -49,7 +49,7 @@ public class DistributionSetRequestBodyPost extends DistributionSetRequestBodyPu /** * @return the os */ - public SoftwareModuleAssigmentRest getOs() { + public MgmtSoftwareModuleAssigment getOs() { return os; } @@ -59,7 +59,7 @@ public class DistributionSetRequestBodyPost extends DistributionSetRequestBodyPu * * @return updated body */ - public DistributionSetRequestBodyPost setOs(final SoftwareModuleAssigmentRest os) { + public MgmtDistributionSetRequestBodyPost setOs(final MgmtSoftwareModuleAssigment os) { this.os = os; return this; } @@ -67,7 +67,7 @@ public class DistributionSetRequestBodyPost extends DistributionSetRequestBodyPu /** * @return the runtime */ - public SoftwareModuleAssigmentRest getRuntime() { + public MgmtSoftwareModuleAssigment getRuntime() { return runtime; } @@ -77,7 +77,7 @@ public class DistributionSetRequestBodyPost extends DistributionSetRequestBodyPu * * @return updated body */ - public DistributionSetRequestBodyPost setRuntime(final SoftwareModuleAssigmentRest runtime) { + public MgmtDistributionSetRequestBodyPost setRuntime(final MgmtSoftwareModuleAssigment runtime) { this.runtime = runtime; return this; @@ -86,7 +86,7 @@ public class DistributionSetRequestBodyPost extends DistributionSetRequestBodyPu /** * @return the application */ - public SoftwareModuleAssigmentRest getApplication() { + public MgmtSoftwareModuleAssigment getApplication() { return application; } @@ -96,7 +96,7 @@ public class DistributionSetRequestBodyPost extends DistributionSetRequestBodyPu * * @return updated body */ - public DistributionSetRequestBodyPost setApplication(final SoftwareModuleAssigmentRest application) { + public MgmtDistributionSetRequestBodyPost setApplication(final MgmtSoftwareModuleAssigment application) { this.application = application; return this; @@ -115,7 +115,7 @@ public class DistributionSetRequestBodyPost extends DistributionSetRequestBodyPu * * @return updated body */ - public DistributionSetRequestBodyPost setRequiredMigrationStep(final boolean requiredMigrationStep) { + public MgmtDistributionSetRequestBodyPost setRequiredMigrationStep(final boolean requiredMigrationStep) { this.requiredMigrationStep = requiredMigrationStep; return this; @@ -124,7 +124,7 @@ public class DistributionSetRequestBodyPost extends DistributionSetRequestBodyPu /** * @return the modules */ - public List getModules() { + public List getModules() { return modules; } @@ -134,7 +134,7 @@ public class DistributionSetRequestBodyPost extends DistributionSetRequestBodyPu * * @return updated body */ - public DistributionSetRequestBodyPost setModules(final List modules) { + public MgmtDistributionSetRequestBodyPost setModules(final List modules) { this.modules = modules; return this; @@ -153,7 +153,7 @@ public class DistributionSetRequestBodyPost extends DistributionSetRequestBodyPu * * @return updated body */ - public DistributionSetRequestBodyPost setType(final String type) { + public MgmtDistributionSetRequestBodyPost setType(final String type) { this.type = type; return this; diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/distributionset/DistributionSetRequestBodyPut.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/distributionset/MgmtDistributionSetRequestBodyPut.java similarity index 82% rename from hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/distributionset/DistributionSetRequestBodyPut.java rename to hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/distributionset/MgmtDistributionSetRequestBodyPut.java index 2f19625f3..4494dd8a8 100644 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/distributionset/DistributionSetRequestBodyPut.java +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/distributionset/MgmtDistributionSetRequestBodyPut.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource.model.distributionset; +package org.eclipse.hawkbit.mgmt.json.model.distributionset; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; @@ -19,7 +19,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; */ @JsonInclude(Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) -public class DistributionSetRequestBodyPut { +public class MgmtDistributionSetRequestBodyPut { @JsonProperty private String name; @@ -43,7 +43,7 @@ public class DistributionSetRequestBodyPut { * * @return updated body */ - public DistributionSetRequestBodyPut setName(final String name) { + public MgmtDistributionSetRequestBodyPut setName(final String name) { this.name = name; return this; } @@ -61,7 +61,7 @@ public class DistributionSetRequestBodyPut { * * @return updated body */ - public DistributionSetRequestBodyPut setDescription(final String description) { + public MgmtDistributionSetRequestBodyPut setDescription(final String description) { this.description = description; return this; @@ -80,7 +80,7 @@ public class DistributionSetRequestBodyPut { * * @return updated body */ - public DistributionSetRequestBodyPut setVersion(final String version) { + public MgmtDistributionSetRequestBodyPut setVersion(final String version) { this.version = version; return this; diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/distributionset/TargetAssignmentRequestBody.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/distributionset/MgmtTargetAssignmentRequestBody.java similarity index 85% rename from hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/distributionset/TargetAssignmentRequestBody.java rename to hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/distributionset/MgmtTargetAssignmentRequestBody.java index 5135a977c..46c43ac8b 100644 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/distributionset/TargetAssignmentRequestBody.java +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/distributionset/MgmtTargetAssignmentRequestBody.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource.model.distributionset; +package org.eclipse.hawkbit.mgmt.json.model.distributionset; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; @@ -16,14 +16,14 @@ import com.fasterxml.jackson.annotation.JsonProperty; * */ @JsonIgnoreProperties(ignoreUnknown = true) -public class TargetAssignmentRequestBody { +public class MgmtTargetAssignmentRequestBody { @JsonProperty private String id; private long forcetime; - private ActionTypeRest type; + private MgmtActionType type; /** * @return the id @@ -43,7 +43,7 @@ public class TargetAssignmentRequestBody { /** * @return the type */ - public ActionTypeRest getType() { + public MgmtActionType getType() { return type; } @@ -51,7 +51,7 @@ public class TargetAssignmentRequestBody { * @param type * the type to set */ - public void setType(final ActionTypeRest type) { + public void setType(final MgmtActionType type) { this.type = type; } diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/distributionset/TargetAssignmentResponseBody.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/distributionset/MgmtTargetAssignmentResponseBody.java similarity index 93% rename from hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/distributionset/TargetAssignmentResponseBody.java rename to hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/distributionset/MgmtTargetAssignmentResponseBody.java index 77676f844..d5247c577 100644 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/distributionset/TargetAssignmentResponseBody.java +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/distributionset/MgmtTargetAssignmentResponseBody.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource.model.distributionset; +package org.eclipse.hawkbit.mgmt.json.model.distributionset; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; @@ -20,7 +20,7 @@ import com.fasterxml.jackson.annotation.JsonInclude.Include; */ @JsonInclude(Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) -public class TargetAssignmentResponseBody { +public class MgmtTargetAssignmentResponseBody { private int assigned; private int alreadyAssigned; diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/distributionsettype/DistributionSetTypeRest.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/distributionsettype/MgmtDistributionSetType.java similarity index 87% rename from hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/distributionsettype/DistributionSetTypeRest.java rename to hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/distributionsettype/MgmtDistributionSetType.java index e282b2924..acc4dbb59 100644 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/distributionsettype/DistributionSetTypeRest.java +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/distributionsettype/MgmtDistributionSetType.java @@ -6,9 +6,9 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource.model.distributionsettype; +package org.eclipse.hawkbit.mgmt.json.model.distributionsettype; -import org.eclipse.hawkbit.rest.resource.model.NamedEntityRest; +import org.eclipse.hawkbit.mgmt.json.model.MgmtNamedEntity; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; @@ -25,7 +25,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; */ @JsonInclude(Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) -public class DistributionSetTypeRest extends NamedEntityRest { +public class MgmtDistributionSetType extends MgmtNamedEntity { @JsonProperty(value = "id", required = true) private Long moduleId; diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/distributionsettype/DistributionSetTypeRequestBodyPost.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/distributionsettype/MgmtDistributionSetTypeRequestBodyPost.java similarity index 68% rename from hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/distributionsettype/DistributionSetTypeRequestBodyPost.java rename to hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/distributionsettype/MgmtDistributionSetTypeRequestBodyPost.java index ba0f548f6..82ecb2cc5 100644 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/distributionsettype/DistributionSetTypeRequestBodyPost.java +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/distributionsettype/MgmtDistributionSetTypeRequestBodyPost.java @@ -6,11 +6,11 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource.model.distributionsettype; +package org.eclipse.hawkbit.mgmt.json.model.distributionsettype; import java.util.List; -import org.eclipse.hawkbit.rest.resource.model.softwaremoduletype.SoftwareModuleTypeAssigmentRest; +import org.eclipse.hawkbit.mgmt.json.model.softwaremoduletype.MgmtSoftwareModuleTypeAssigment; import com.fasterxml.jackson.annotation.JsonProperty; @@ -18,7 +18,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; * Request Body for DistributionSetType POST. * */ -public class DistributionSetTypeRequestBodyPost { +public class MgmtDistributionSetTypeRequestBodyPost { @JsonProperty(required = true) private String name; @@ -30,10 +30,10 @@ public class DistributionSetTypeRequestBodyPost { private String key; @JsonProperty - private List mandatorymodules; + private List mandatorymodules; @JsonProperty - private List optionalmodules; + private List optionalmodules; /** * @return the name @@ -48,7 +48,7 @@ public class DistributionSetTypeRequestBodyPost { * * @return updated body */ - public DistributionSetTypeRequestBodyPost setName(final String name) { + public MgmtDistributionSetTypeRequestBodyPost setName(final String name) { this.name = name; return this; } @@ -66,7 +66,7 @@ public class DistributionSetTypeRequestBodyPost { * * @return updated body */ - public DistributionSetTypeRequestBodyPost setDescription(final String description) { + public MgmtDistributionSetTypeRequestBodyPost setDescription(final String description) { this.description = description; return this; } @@ -84,7 +84,7 @@ public class DistributionSetTypeRequestBodyPost { * * @return updated body */ - public DistributionSetTypeRequestBodyPost setKey(final String key) { + public MgmtDistributionSetTypeRequestBodyPost setKey(final String key) { this.key = key; return this; } @@ -92,7 +92,7 @@ public class DistributionSetTypeRequestBodyPost { /** * @return the mandatory modules */ - public List getMandatorymodules() { + public List getMandatorymodules() { return mandatorymodules; } @@ -102,8 +102,8 @@ public class DistributionSetTypeRequestBodyPost { * * @return updated body */ - public DistributionSetTypeRequestBodyPost setMandatorymodules( - final List mandatorymodules) { + public MgmtDistributionSetTypeRequestBodyPost setMandatorymodules( + final List mandatorymodules) { this.mandatorymodules = mandatorymodules; return this; } @@ -111,7 +111,7 @@ public class DistributionSetTypeRequestBodyPost { /** * @return the optional modules */ - public List getOptionalmodules() { + public List getOptionalmodules() { return optionalmodules; } @@ -121,8 +121,8 @@ public class DistributionSetTypeRequestBodyPost { * * @return updated body */ - public DistributionSetTypeRequestBodyPost setOptionalmodules( - final List optionalmodules) { + public MgmtDistributionSetTypeRequestBodyPost setOptionalmodules( + final List optionalmodules) { this.optionalmodules = optionalmodules; return this; } diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/distributionsettype/DistributionSetTypeRequestBodyPut.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/distributionsettype/MgmtDistributionSetTypeRequestBodyPut.java similarity index 79% rename from hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/distributionsettype/DistributionSetTypeRequestBodyPut.java rename to hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/distributionsettype/MgmtDistributionSetTypeRequestBodyPut.java index 6bf21b93f..220f58e4d 100644 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/distributionsettype/DistributionSetTypeRequestBodyPut.java +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/distributionsettype/MgmtDistributionSetTypeRequestBodyPut.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource.model.distributionsettype; +package org.eclipse.hawkbit.mgmt.json.model.distributionsettype; import com.fasterxml.jackson.annotation.JsonProperty; @@ -14,7 +14,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; * Request Body for DistributionSetType PUT, i.e. update. * */ -public class DistributionSetTypeRequestBodyPut { +public class MgmtDistributionSetTypeRequestBodyPut { @JsonProperty private String description; @@ -32,7 +32,7 @@ public class DistributionSetTypeRequestBodyPut { * * @return updated body */ - public DistributionSetTypeRequestBodyPut setDescription(final String description) { + public MgmtDistributionSetTypeRequestBodyPut setDescription(final String description) { this.description = description; return this; } diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/rollout/RolloutCondition.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/rollout/MgmtRolloutCondition.java similarity index 84% rename from hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/rollout/RolloutCondition.java rename to hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/rollout/MgmtRolloutCondition.java index 914a5d5c2..d83585415 100644 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/rollout/RolloutCondition.java +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/rollout/MgmtRolloutCondition.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource.model.rollout; +package org.eclipse.hawkbit.mgmt.json.model.rollout; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; @@ -17,7 +17,7 @@ import com.fasterxml.jackson.annotation.JsonInclude.Include; */ @JsonInclude(Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) -public class RolloutCondition { +public class MgmtRolloutCondition { private Condition condition = Condition.THRESHOLD; private String expression = "100"; @@ -25,10 +25,11 @@ public class RolloutCondition { /** * */ - public RolloutCondition() { + public MgmtRolloutCondition() { + // needed for jackson json creator. } - public RolloutCondition(final Condition condition, final String expression) { + public MgmtRolloutCondition(final Condition condition, final String expression) { this.condition = condition; this.expression = expression; } diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/rollout/RolloutErrorAction.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/rollout/MgmtRolloutErrorAction.java similarity index 93% rename from hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/rollout/RolloutErrorAction.java rename to hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/rollout/MgmtRolloutErrorAction.java index 2ed6077e6..71fdf3ac9 100644 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/rollout/RolloutErrorAction.java +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/rollout/MgmtRolloutErrorAction.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource.model.rollout; +package org.eclipse.hawkbit.mgmt.json.model.rollout; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; @@ -17,7 +17,7 @@ import com.fasterxml.jackson.annotation.JsonInclude.Include; */ @JsonInclude(Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) -public class RolloutErrorAction { +public class MgmtRolloutErrorAction { private ErrorAction action = ErrorAction.PAUSE; private String expression = null; diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/rollout/RolloutResponseBody.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/rollout/MgmtRolloutResponseBody.java similarity index 94% rename from hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/rollout/RolloutResponseBody.java rename to hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/rollout/MgmtRolloutResponseBody.java index dd1296cfd..79455f501 100644 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/rollout/RolloutResponseBody.java +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/rollout/MgmtRolloutResponseBody.java @@ -6,12 +6,12 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource.model.rollout; +package org.eclipse.hawkbit.mgmt.json.model.rollout; import java.util.HashMap; import java.util.Map; -import org.eclipse.hawkbit.rest.resource.model.NamedEntityRest; +import org.eclipse.hawkbit.mgmt.json.model.MgmtNamedEntity; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; @@ -23,7 +23,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; */ @JsonInclude(Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) -public class RolloutResponseBody extends NamedEntityRest { +public class MgmtRolloutResponseBody extends MgmtNamedEntity { private String targetFilterQuery; private Long distributionSetId; diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/rollout/RolloutRestRequestBody.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/rollout/MgmtRolloutRestRequestBody.java similarity index 72% rename from hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/rollout/RolloutRestRequestBody.java rename to hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/rollout/MgmtRolloutRestRequestBody.java index 0b83948ff..f3bdb2665 100644 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/rollout/RolloutRestRequestBody.java +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/rollout/MgmtRolloutRestRequestBody.java @@ -6,10 +6,10 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource.model.rollout; +package org.eclipse.hawkbit.mgmt.json.model.rollout; -import org.eclipse.hawkbit.rest.resource.model.NamedEntityRest; -import org.eclipse.hawkbit.rest.resource.model.distributionset.ActionTypeRest; +import org.eclipse.hawkbit.mgmt.json.model.MgmtNamedEntity; +import org.eclipse.hawkbit.mgmt.json.model.distributionset.MgmtActionType; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; @@ -21,26 +21,26 @@ import com.fasterxml.jackson.annotation.JsonInclude.Include; */ @JsonInclude(Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) -public class RolloutRestRequestBody extends NamedEntityRest { +public class MgmtRolloutRestRequestBody extends MgmtNamedEntity { private String targetFilterQuery; private long distributionSetId; private int amountGroups = 1; - private RolloutCondition successCondition = new RolloutCondition(); - private RolloutSuccessAction successAction = new RolloutSuccessAction(); - private RolloutCondition errorCondition = null; - private RolloutErrorAction errorAction = null; + private MgmtRolloutCondition successCondition = new MgmtRolloutCondition(); + private MgmtRolloutSuccessAction successAction = new MgmtRolloutSuccessAction(); + private MgmtRolloutCondition errorCondition = null; + private MgmtRolloutErrorAction errorAction = null; private Long forcetime; - private ActionTypeRest type; + private MgmtActionType type; /** * @return the finishCondition */ - public RolloutCondition getSuccessCondition() { + public MgmtRolloutCondition getSuccessCondition() { return successCondition; } @@ -48,14 +48,14 @@ public class RolloutRestRequestBody extends NamedEntityRest { * @param successCondition * the finishCondition to set */ - public void setSuccessCondition(final RolloutCondition successCondition) { + public void setSuccessCondition(final MgmtRolloutCondition successCondition) { this.successCondition = successCondition; } /** * @return the successAction */ - public RolloutSuccessAction getSuccessAction() { + public MgmtRolloutSuccessAction getSuccessAction() { return successAction; } @@ -63,14 +63,14 @@ public class RolloutRestRequestBody extends NamedEntityRest { * @param successAction * the successAction to set */ - public void setSuccessAction(final RolloutSuccessAction successAction) { + public void setSuccessAction(final MgmtRolloutSuccessAction successAction) { this.successAction = successAction; } /** * @return the errorCondition */ - public RolloutCondition getErrorCondition() { + public MgmtRolloutCondition getErrorCondition() { return errorCondition; } @@ -78,7 +78,7 @@ public class RolloutRestRequestBody extends NamedEntityRest { * @param errorCondition * the errorCondition to set */ - public void setErrorCondition(final RolloutCondition errorCondition) { + public void setErrorCondition(final MgmtRolloutCondition errorCondition) { this.errorCondition = errorCondition; } @@ -145,7 +145,7 @@ public class RolloutRestRequestBody extends NamedEntityRest { /** * @return the type */ - public ActionTypeRest getType() { + public MgmtActionType getType() { return type; } @@ -153,14 +153,14 @@ public class RolloutRestRequestBody extends NamedEntityRest { * @param type * the type to set */ - public void setType(final ActionTypeRest type) { + public void setType(final MgmtActionType type) { this.type = type; } /** * @return the errorAction */ - public RolloutErrorAction getErrorAction() { + public MgmtRolloutErrorAction getErrorAction() { return errorAction; } @@ -168,7 +168,7 @@ public class RolloutRestRequestBody extends NamedEntityRest { * @param errorAction * the errorAction to set */ - public void setErrorAction(final RolloutErrorAction errorAction) { + public void setErrorAction(final MgmtRolloutErrorAction errorAction) { this.errorAction = errorAction; } diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/rollout/RolloutSuccessAction.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/rollout/MgmtRolloutSuccessAction.java similarity index 84% rename from hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/rollout/RolloutSuccessAction.java rename to hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/rollout/MgmtRolloutSuccessAction.java index f14e9a8bf..174aa63fa 100644 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/rollout/RolloutSuccessAction.java +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/rollout/MgmtRolloutSuccessAction.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource.model.rollout; +package org.eclipse.hawkbit.mgmt.json.model.rollout; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; @@ -17,7 +17,7 @@ import com.fasterxml.jackson.annotation.JsonInclude.Include; */ @JsonInclude(Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) -public class RolloutSuccessAction { +public class MgmtRolloutSuccessAction { private SuccessAction action = SuccessAction.NEXTGROUP; private String expression = null; @@ -25,10 +25,11 @@ public class RolloutSuccessAction { /** * */ - public RolloutSuccessAction() { + public MgmtRolloutSuccessAction() { + // needed for json creator } - public RolloutSuccessAction(final SuccessAction action, final String expression) { + public MgmtRolloutSuccessAction(final SuccessAction action, final String expression) { this.action = action; this.expression = expression; } diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/rolloutgroup/RolloutGroupResponseBody.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/rolloutgroup/MgmtRolloutGroupResponseBody.java similarity index 88% rename from hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/rolloutgroup/RolloutGroupResponseBody.java rename to hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/rolloutgroup/MgmtRolloutGroupResponseBody.java index bb1b0116e..5e740a1fb 100644 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/rolloutgroup/RolloutGroupResponseBody.java +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/rolloutgroup/MgmtRolloutGroupResponseBody.java @@ -6,9 +6,9 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource.model.rolloutgroup; +package org.eclipse.hawkbit.mgmt.json.model.rolloutgroup; -import org.eclipse.hawkbit.rest.resource.model.NamedEntityRest; +import org.eclipse.hawkbit.mgmt.json.model.MgmtNamedEntity; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; @@ -21,7 +21,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; */ @JsonInclude(Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) -public class RolloutGroupResponseBody extends NamedEntityRest { +public class MgmtRolloutGroupResponseBody extends MgmtNamedEntity { @JsonProperty(value = "id", required = true) private Long rolloutGroupId; diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/softwaremodule/SoftwareModuleRest.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/softwaremodule/MgmtSoftwareModule.java similarity index 86% rename from hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/softwaremodule/SoftwareModuleRest.java rename to hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/softwaremodule/MgmtSoftwareModule.java index a5ab41c8b..ec4a48e89 100644 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/softwaremodule/SoftwareModuleRest.java +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/softwaremodule/MgmtSoftwareModule.java @@ -6,9 +6,9 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource.model.softwaremodule; +package org.eclipse.hawkbit.mgmt.json.model.softwaremodule; -import org.eclipse.hawkbit.rest.resource.model.NamedEntityRest; +import org.eclipse.hawkbit.mgmt.json.model.MgmtNamedEntity; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @@ -22,17 +22,17 @@ import com.fasterxml.jackson.annotation.JsonProperty; */ @JsonInclude(Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) -public class SoftwareModuleRest extends NamedEntityRest { +public class MgmtSoftwareModule extends MgmtNamedEntity { /** - * API definition for {@link SoftwareModule.Type#RUNTIME}. + * API definition for Software module type#RUNTIME. */ public static final String SM_RUNTIME = "runtime"; /** - * API definition for {@link SoftwareModule.Type#OS}. + * API definition for for Software module type#OS. */ public static final String SM_OS = "os"; /** - * API definition for {@link SoftwareModule.Type#APPLICATION}. + * API definition for for Software module type#APPLICATION. */ public static final String SM_APPLICATION = "application"; diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/softwaremodule/SoftwareModuleAssigmentRest.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/softwaremodule/MgmtSoftwareModuleAssigment.java similarity index 73% rename from hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/softwaremodule/SoftwareModuleAssigmentRest.java rename to hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/softwaremodule/MgmtSoftwareModuleAssigment.java index 3c866dca6..79bc31ad3 100644 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/softwaremodule/SoftwareModuleAssigmentRest.java +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/softwaremodule/MgmtSoftwareModuleAssigment.java @@ -6,20 +6,17 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource.model.softwaremodule; +package org.eclipse.hawkbit.mgmt.json.model.softwaremodule; -import org.eclipse.hawkbit.rest.resource.model.IdRest; +import org.eclipse.hawkbit.mgmt.json.model.MgmtId; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; /** * Request Body of SoftwareModule for assignment operations (ID only). * - * - * - * */ @JsonIgnoreProperties(ignoreUnknown = true) -public class SoftwareModuleAssigmentRest extends IdRest { +public class MgmtSoftwareModuleAssigment extends MgmtId { } diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/softwaremodule/SoftwareModuleRequestBodyPost.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/softwaremodule/MgmtSoftwareModuleRequestBodyPost.java similarity index 80% rename from hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/softwaremodule/SoftwareModuleRequestBodyPost.java rename to hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/softwaremodule/MgmtSoftwareModuleRequestBodyPost.java index 08638c10f..e39413915 100644 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/softwaremodule/SoftwareModuleRequestBodyPost.java +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/softwaremodule/MgmtSoftwareModuleRequestBodyPost.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource.model.softwaremodule; +package org.eclipse.hawkbit.mgmt.json.model.softwaremodule; import com.fasterxml.jackson.annotation.JsonProperty; @@ -14,7 +14,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; * Request Body for SoftwareModule POST. * */ -public class SoftwareModuleRequestBodyPost { +public class MgmtSoftwareModuleRequestBodyPost { @JsonProperty(required = true) private String name; @@ -44,7 +44,7 @@ public class SoftwareModuleRequestBodyPost { * * @return updated body */ - public SoftwareModuleRequestBodyPost setName(final String name) { + public MgmtSoftwareModuleRequestBodyPost setName(final String name) { this.name = name; return this; } @@ -62,7 +62,7 @@ public class SoftwareModuleRequestBodyPost { * * @return updated body */ - public SoftwareModuleRequestBodyPost setVersion(final String version) { + public MgmtSoftwareModuleRequestBodyPost setVersion(final String version) { this.version = version; return this; } @@ -80,7 +80,7 @@ public class SoftwareModuleRequestBodyPost { * * @return updated body */ - public SoftwareModuleRequestBodyPost setType(final String type) { + public MgmtSoftwareModuleRequestBodyPost setType(final String type) { this.type = type; return this; } @@ -98,7 +98,7 @@ public class SoftwareModuleRequestBodyPost { * * @return updated body */ - public SoftwareModuleRequestBodyPost setDescription(final String description) { + public MgmtSoftwareModuleRequestBodyPost setDescription(final String description) { this.description = description; return this; } @@ -116,7 +116,7 @@ public class SoftwareModuleRequestBodyPost { * * @return updated body */ - public SoftwareModuleRequestBodyPost setVendor(final String vendor) { + public MgmtSoftwareModuleRequestBodyPost setVendor(final String vendor) { this.vendor = vendor; return this; } diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/softwaremodule/SoftwareModuleRequestBodyPut.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/softwaremodule/MgmtSoftwareModuleRequestBodyPut.java similarity index 80% rename from hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/softwaremodule/SoftwareModuleRequestBodyPut.java rename to hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/softwaremodule/MgmtSoftwareModuleRequestBodyPut.java index 1ee547886..52c097e39 100644 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/softwaremodule/SoftwareModuleRequestBodyPut.java +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/softwaremodule/MgmtSoftwareModuleRequestBodyPut.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource.model.softwaremodule; +package org.eclipse.hawkbit.mgmt.json.model.softwaremodule; import com.fasterxml.jackson.annotation.JsonProperty; @@ -14,7 +14,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; * Request Body for SoftwareModule PUT. * */ -public class SoftwareModuleRequestBodyPut { +public class MgmtSoftwareModuleRequestBodyPut { @JsonProperty private String description; @@ -35,7 +35,7 @@ public class SoftwareModuleRequestBodyPut { * * @return updated body */ - public SoftwareModuleRequestBodyPut setDescription(final String description) { + public MgmtSoftwareModuleRequestBodyPut setDescription(final String description) { this.description = description; return this; } @@ -53,7 +53,7 @@ public class SoftwareModuleRequestBodyPut { * * @return updated body */ - public SoftwareModuleRequestBodyPut setVendor(final String vendor) { + public MgmtSoftwareModuleRequestBodyPut setVendor(final String vendor) { this.vendor = vendor; return this; } diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/softwaremoduletype/SoftwareModuleTypeRest.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/softwaremoduletype/MgmtSoftwareModuleType.java similarity index 89% rename from hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/softwaremoduletype/SoftwareModuleTypeRest.java rename to hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/softwaremoduletype/MgmtSoftwareModuleType.java index 6478eb790..c0cda4994 100644 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/softwaremoduletype/SoftwareModuleTypeRest.java +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/softwaremoduletype/MgmtSoftwareModuleType.java @@ -6,9 +6,9 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource.model.softwaremoduletype; +package org.eclipse.hawkbit.mgmt.json.model.softwaremoduletype; -import org.eclipse.hawkbit.rest.resource.model.NamedEntityRest; +import org.eclipse.hawkbit.mgmt.json.model.MgmtNamedEntity; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; @@ -19,13 +19,10 @@ import com.fasterxml.jackson.annotation.JsonProperty; * A json annotated rest model for SoftwareModuleType to RESTful API * representation. * - * - * - * */ @JsonInclude(Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) -public class SoftwareModuleTypeRest extends NamedEntityRest { +public class MgmtSoftwareModuleType extends MgmtNamedEntity { @JsonProperty(value = "id", required = true) private Long moduleId; diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/softwaremoduletype/SoftwareModuleTypeAssigmentRest.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/softwaremoduletype/MgmtSoftwareModuleTypeAssigment.java similarity index 73% rename from hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/softwaremoduletype/SoftwareModuleTypeAssigmentRest.java rename to hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/softwaremoduletype/MgmtSoftwareModuleTypeAssigment.java index 68709650b..43bdc157e 100644 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/softwaremoduletype/SoftwareModuleTypeAssigmentRest.java +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/softwaremoduletype/MgmtSoftwareModuleTypeAssigment.java @@ -6,9 +6,9 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource.model.softwaremoduletype; +package org.eclipse.hawkbit.mgmt.json.model.softwaremoduletype; -import org.eclipse.hawkbit.rest.resource.model.IdRest; +import org.eclipse.hawkbit.mgmt.json.model.MgmtId; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @@ -17,6 +17,6 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; * */ @JsonIgnoreProperties(ignoreUnknown = true) -public class SoftwareModuleTypeAssigmentRest extends IdRest { +public class MgmtSoftwareModuleTypeAssigment extends MgmtId { } diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/softwaremoduletype/SoftwareModuleTypeRequestBodyPost.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/softwaremoduletype/MgmtSoftwareModuleTypeRequestBodyPost.java similarity index 79% rename from hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/softwaremoduletype/SoftwareModuleTypeRequestBodyPost.java rename to hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/softwaremoduletype/MgmtSoftwareModuleTypeRequestBodyPost.java index 3528f6b98..836c39d19 100644 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/softwaremoduletype/SoftwareModuleTypeRequestBodyPost.java +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/softwaremoduletype/MgmtSoftwareModuleTypeRequestBodyPost.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource.model.softwaremoduletype; +package org.eclipse.hawkbit.mgmt.json.model.softwaremoduletype; import com.fasterxml.jackson.annotation.JsonProperty; @@ -14,7 +14,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; * Request Body for SoftwareModuleType POST. * */ -public class SoftwareModuleTypeRequestBodyPost { +public class MgmtSoftwareModuleTypeRequestBodyPost { @JsonProperty(required = true) private String name; @@ -41,7 +41,7 @@ public class SoftwareModuleTypeRequestBodyPost { * * @return updated body */ - public SoftwareModuleTypeRequestBodyPost setName(final String name) { + public MgmtSoftwareModuleTypeRequestBodyPost setName(final String name) { this.name = name; return this; } @@ -59,7 +59,7 @@ public class SoftwareModuleTypeRequestBodyPost { * * @return updated body */ - public SoftwareModuleTypeRequestBodyPost setDescription(final String description) { + public MgmtSoftwareModuleTypeRequestBodyPost setDescription(final String description) { this.description = description; return this; } @@ -76,7 +76,7 @@ public class SoftwareModuleTypeRequestBodyPost { * the key to set * @return updated body */ - public SoftwareModuleTypeRequestBodyPost setKey(final String key) { + public MgmtSoftwareModuleTypeRequestBodyPost setKey(final String key) { this.key = key; return this; } @@ -94,7 +94,7 @@ public class SoftwareModuleTypeRequestBodyPost { * * @return updated body */ - public SoftwareModuleTypeRequestBodyPost setMaxAssignments(final int maxAssignments) { + public MgmtSoftwareModuleTypeRequestBodyPost setMaxAssignments(final int maxAssignments) { this.maxAssignments = maxAssignments; return this; } diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/softwaremoduletype/SoftwareModuleTypeRequestBodyPut.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/softwaremoduletype/MgmtSoftwareModuleTypeRequestBodyPut.java similarity index 79% rename from hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/softwaremoduletype/SoftwareModuleTypeRequestBodyPut.java rename to hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/softwaremoduletype/MgmtSoftwareModuleTypeRequestBodyPut.java index 107a3cd2b..ecc8c9f65 100644 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/softwaremoduletype/SoftwareModuleTypeRequestBodyPut.java +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/softwaremoduletype/MgmtSoftwareModuleTypeRequestBodyPut.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource.model.softwaremoduletype; +package org.eclipse.hawkbit.mgmt.json.model.softwaremoduletype; import com.fasterxml.jackson.annotation.JsonProperty; @@ -14,7 +14,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; * Request Body for SoftwareModuleType PUT. * */ -public class SoftwareModuleTypeRequestBodyPut { +public class MgmtSoftwareModuleTypeRequestBodyPut { @JsonProperty private String description; @@ -32,7 +32,7 @@ public class SoftwareModuleTypeRequestBodyPut { * * @return updated body */ - public SoftwareModuleTypeRequestBodyPut setDescription(final String description) { + public MgmtSoftwareModuleTypeRequestBodyPut setDescription(final String description) { this.description = description; return this; } diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/system/TenantConfigurationValueRest.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/system/MgmtSystemTenantConfigurationValue.java similarity index 94% rename from hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/system/TenantConfigurationValueRest.java rename to hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/system/MgmtSystemTenantConfigurationValue.java index 47dcfebe0..776b69c09 100644 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/system/TenantConfigurationValueRest.java +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/system/MgmtSystemTenantConfigurationValue.java @@ -7,7 +7,7 @@ * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource.model.system; +package org.eclipse.hawkbit.mgmt.json.model.system; import org.springframework.hateoas.ResourceSupport; @@ -22,7 +22,7 @@ import com.fasterxml.jackson.annotation.JsonInclude.Include; */ @JsonInclude(Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) -public class TenantConfigurationValueRest extends ResourceSupport { +public class MgmtSystemTenantConfigurationValue extends ResourceSupport { @JsonInclude(Include.ALWAYS) private Object value; diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/system/TenantConfigurationValueRequest.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/system/MgmtSystemTenantConfigurationValueRequest.java similarity index 80% rename from hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/system/TenantConfigurationValueRequest.java rename to hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/system/MgmtSystemTenantConfigurationValueRequest.java index b0ae6e546..9a9aed209 100644 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/system/TenantConfigurationValueRequest.java +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/system/MgmtSystemTenantConfigurationValueRequest.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource.model.system; +package org.eclipse.hawkbit.mgmt.json.model.system; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; @@ -18,21 +18,21 @@ import com.fasterxml.jackson.annotation.JsonProperty; */ @JsonInclude(Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) -public class TenantConfigurationValueRequest { +public class MgmtSystemTenantConfigurationValueRequest { @JsonProperty(required = true) private Object value; /** * - * @return the value of the TenantConfigurationValueRequest + * @return the value of the MgmtSystemTenantConfigurationValueRequest */ public Object getValue() { return value; } /** - * Sets the TenantConfigurationValueRequest + * Sets the MgmtSystemTenantConfigurationValueRequest * * @param value */ diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/systemmanagement/CacheRest.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/systemmanagement/MgmtSystemCache.java similarity index 83% rename from hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/systemmanagement/CacheRest.java rename to hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/systemmanagement/MgmtSystemCache.java index 35d35c0b1..2876b11df 100644 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/systemmanagement/CacheRest.java +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/systemmanagement/MgmtSystemCache.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource.model.systemmanagement; +package org.eclipse.hawkbit.mgmt.json.model.systemmanagement; import java.util.Collection; @@ -16,14 +16,11 @@ import com.fasterxml.jackson.annotation.JsonInclude.Include; /** * Model representation of an Cache entry as json. - * - * - * * */ @JsonInclude(Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) -public class CacheRest { +public class MgmtSystemCache { private final String name; private final Collection keys; @@ -34,7 +31,7 @@ public class CacheRest { * @param cacheKeys * the keys which contains in the cache */ - public CacheRest(final String name, final Collection cacheKeys) { + public MgmtSystemCache(final String name, final Collection cacheKeys) { this.name = name; this.keys = cacheKeys; } @@ -60,6 +57,6 @@ public class CacheRest { */ @Override public String toString() { - return "CacheRest [name=" + name + ", keys=" + keys + "]"; + return "MgmtSystemCache [name=" + name + ", keys=" + keys + "]"; } } diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/systemmanagement/SystemStatisticsRest.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/systemmanagement/MgmtSystemStatisticsRest.java similarity index 69% rename from hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/systemmanagement/SystemStatisticsRest.java rename to hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/systemmanagement/MgmtSystemStatisticsRest.java index c69201d69..0c1b12fde 100644 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/systemmanagement/SystemStatisticsRest.java +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/systemmanagement/MgmtSystemStatisticsRest.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource.model.systemmanagement; +package org.eclipse.hawkbit.mgmt.json.model.systemmanagement; import java.util.List; @@ -20,7 +20,7 @@ import com.fasterxml.jackson.annotation.JsonInclude.Include; */ @JsonInclude(Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) -public class SystemStatisticsRest { +public class MgmtSystemStatisticsRest { private long overallTargets; private long overallArtifacts; @@ -28,13 +28,13 @@ public class SystemStatisticsRest { private long overallActions; private long overallTenants; - private List tenantStats; + private List tenantStats; public long getOverallTargets() { return overallTargets; } - public SystemStatisticsRest setOverallTargets(final long overallTargets) { + public MgmtSystemStatisticsRest setOverallTargets(final long overallTargets) { this.overallTargets = overallTargets; return this; } @@ -43,7 +43,7 @@ public class SystemStatisticsRest { return overallArtifacts; } - public SystemStatisticsRest setOverallArtifacts(final long overallArtifacts) { + public MgmtSystemStatisticsRest setOverallArtifacts(final long overallArtifacts) { this.overallArtifacts = overallArtifacts; return this; } @@ -52,7 +52,7 @@ public class SystemStatisticsRest { return overallArtifactVolumeInBytes; } - public SystemStatisticsRest setOverallArtifactVolumeInBytes(final long overallArtifactVolumeInBytes) { + public MgmtSystemStatisticsRest setOverallArtifactVolumeInBytes(final long overallArtifactVolumeInBytes) { this.overallArtifactVolumeInBytes = overallArtifactVolumeInBytes; return this; } @@ -61,7 +61,7 @@ public class SystemStatisticsRest { return overallActions; } - public SystemStatisticsRest setOverallActions(final long overallActions) { + public MgmtSystemStatisticsRest setOverallActions(final long overallActions) { this.overallActions = overallActions; return this; } @@ -70,16 +70,16 @@ public class SystemStatisticsRest { return overallTenants; } - public SystemStatisticsRest setOverallTenants(final long overallTenants) { + public MgmtSystemStatisticsRest setOverallTenants(final long overallTenants) { this.overallTenants = overallTenants; return this; } - public void setTenantStats(final List tenantStats) { + public void setTenantStats(final List tenantStats) { this.tenantStats = tenantStats; } - public List getTenantStats() { + public List getTenantStats() { return tenantStats; } diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/systemmanagement/TenantSystemUsageRest.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/systemmanagement/MgmtSystemTenantServiceUsage.java similarity index 90% rename from hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/systemmanagement/TenantSystemUsageRest.java rename to hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/systemmanagement/MgmtSystemTenantServiceUsage.java index bc8653b36..8cce4314b 100644 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/systemmanagement/TenantSystemUsageRest.java +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/systemmanagement/MgmtSystemTenantServiceUsage.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource.model.systemmanagement; +package org.eclipse.hawkbit.mgmt.json.model.systemmanagement; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; @@ -18,7 +18,7 @@ import com.fasterxml.jackson.annotation.JsonInclude.Include; */ @JsonInclude(Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) -public class TenantSystemUsageRest { +public class MgmtSystemTenantServiceUsage { private final String tenantName; private long targets; @@ -31,7 +31,7 @@ public class TenantSystemUsageRest { * * @param tenantName */ - public TenantSystemUsageRest(final String tenantName) { + public MgmtSystemTenantServiceUsage(final String tenantName) { super(); this.tenantName = tenantName; } diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/tag/AssignedDistributionSetRequestBody.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/tag/MgmtAssignedDistributionSetRequestBody.java similarity index 81% rename from hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/tag/AssignedDistributionSetRequestBody.java rename to hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/tag/MgmtAssignedDistributionSetRequestBody.java index 2bfd6cbf8..469780abf 100644 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/tag/AssignedDistributionSetRequestBody.java +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/tag/MgmtAssignedDistributionSetRequestBody.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource.model.tag; +package org.eclipse.hawkbit.mgmt.json.model.tag; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; @@ -19,7 +19,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; */ @JsonInclude(Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) -public class AssignedDistributionSetRequestBody { +public class MgmtAssignedDistributionSetRequestBody { @JsonProperty(value = "id", required = true) private Long distributionSetId; @@ -28,7 +28,7 @@ public class AssignedDistributionSetRequestBody { return distributionSetId; } - public AssignedDistributionSetRequestBody setDistributionSetId(final Long distributionSetId) { + public MgmtAssignedDistributionSetRequestBody setDistributionSetId(final Long distributionSetId) { this.distributionSetId = distributionSetId; return this; } diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/tag/AssignedTargetRequestBody.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/tag/MgmtAssignedTargetRequestBody.java similarity index 83% rename from hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/tag/AssignedTargetRequestBody.java rename to hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/tag/MgmtAssignedTargetRequestBody.java index 2147c2697..6df1d10d7 100644 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/tag/AssignedTargetRequestBody.java +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/tag/MgmtAssignedTargetRequestBody.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource.model.tag; +package org.eclipse.hawkbit.mgmt.json.model.tag; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; @@ -19,7 +19,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; */ @JsonInclude(Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) -public class AssignedTargetRequestBody { +public class MgmtAssignedTargetRequestBody { @JsonProperty(required = true) private String controllerId; @@ -28,7 +28,7 @@ public class AssignedTargetRequestBody { return controllerId; } - public AssignedTargetRequestBody setControllerId(final String controllerId) { + public MgmtAssignedTargetRequestBody setControllerId(final String controllerId) { this.controllerId = controllerId; return this; } diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/tag/DistributionSetTagAssigmentResultRest.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/tag/MgmtDistributionSetTagAssigmentResult.java similarity index 59% rename from hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/tag/DistributionSetTagAssigmentResultRest.java rename to hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/tag/MgmtDistributionSetTagAssigmentResult.java index 1d0b51e72..892bac453 100644 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/tag/DistributionSetTagAssigmentResultRest.java +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/tag/MgmtDistributionSetTagAssigmentResult.java @@ -6,9 +6,11 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource.model.tag; +package org.eclipse.hawkbit.mgmt.json.model.tag; -import org.eclipse.hawkbit.rest.resource.model.distributionset.DistributionSetsRest; +import java.util.List; + +import org.eclipse.hawkbit.mgmt.json.model.distributionset.MgmtDistributionSet; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; @@ -22,27 +24,27 @@ import com.fasterxml.jackson.annotation.JsonProperty; */ @JsonInclude(Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) -public class DistributionSetTagAssigmentResultRest { +public class MgmtDistributionSetTagAssigmentResult { @JsonProperty - private DistributionSetsRest assignedDistributionSets; + private List assignedDistributionSets; @JsonProperty - private DistributionSetsRest unassignedDistributionSets; + private List unassignedDistributionSets; - public DistributionSetsRest getAssignedDistributionSets() { + public List getAssignedDistributionSets() { return assignedDistributionSets; } - public DistributionSetsRest getUnassignedDistributionSets() { + public List getUnassignedDistributionSets() { return unassignedDistributionSets; } - public void setAssignedDistributionSets(final DistributionSetsRest assignedDistributionSets) { + public void setAssignedDistributionSets(final List assignedDistributionSets) { this.assignedDistributionSets = assignedDistributionSets; } - public void setUnassignedDistributionSets(final DistributionSetsRest unassignedDistributionSets) { + public void setUnassignedDistributionSets(final List unassignedDistributionSets) { this.unassignedDistributionSets = unassignedDistributionSets; } diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/tag/TagRest.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/tag/MgmtTag.java similarity index 87% rename from hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/tag/TagRest.java rename to hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/tag/MgmtTag.java index 54d3c5064..82c33b434 100644 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/tag/TagRest.java +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/tag/MgmtTag.java @@ -6,9 +6,9 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource.model.tag; +package org.eclipse.hawkbit.mgmt.json.model.tag; -import org.eclipse.hawkbit.rest.resource.model.NamedEntityRest; +import org.eclipse.hawkbit.mgmt.json.model.MgmtNamedEntity; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @@ -22,7 +22,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; */ @JsonInclude(Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) -public class TagRest extends NamedEntityRest { +public class MgmtTag extends MgmtNamedEntity { @JsonProperty(value = "id", required = true) private Long tagId; diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/tag/TagRequestBodyPut.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/tag/MgmtTagRequestBodyPut.java similarity index 80% rename from hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/tag/TagRequestBodyPut.java rename to hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/tag/MgmtTagRequestBodyPut.java index 2165bcfc0..e7037af2b 100644 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/tag/TagRequestBodyPut.java +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/tag/MgmtTagRequestBodyPut.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource.model.tag; +package org.eclipse.hawkbit.mgmt.json.model.tag; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; @@ -19,7 +19,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; */ @JsonInclude(Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) -public class TagRequestBodyPut { +public class MgmtTagRequestBodyPut { @JsonProperty private String colour; @@ -34,7 +34,7 @@ public class TagRequestBodyPut { return name; } - public TagRequestBodyPut setName(final String name) { + public MgmtTagRequestBodyPut setName(final String name) { this.name = name; return this; } @@ -43,12 +43,12 @@ public class TagRequestBodyPut { return description; } - public TagRequestBodyPut setDescription(final String description) { + public MgmtTagRequestBodyPut setDescription(final String description) { this.description = description; return this; } - public TagRequestBodyPut setColour(final String colour) { + public MgmtTagRequestBodyPut setColour(final String colour) { this.colour = colour; return this; } diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/tag/TargetTagAssigmentResultRest.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/tag/MgmtTargetTagAssigmentResult.java similarity index 64% rename from hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/tag/TargetTagAssigmentResultRest.java rename to hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/tag/MgmtTargetTagAssigmentResult.java index 928a72460..61625e59d 100644 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/tag/TargetTagAssigmentResultRest.java +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/tag/MgmtTargetTagAssigmentResult.java @@ -6,9 +6,11 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource.model.tag; +package org.eclipse.hawkbit.mgmt.json.model.tag; -import org.eclipse.hawkbit.rest.resource.model.target.TargetsRest; +import java.util.List; + +import org.eclipse.hawkbit.mgmt.json.model.target.MgmtTarget; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; @@ -22,27 +24,27 @@ import com.fasterxml.jackson.annotation.JsonProperty; */ @JsonInclude(Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) -public class TargetTagAssigmentResultRest { +public class MgmtTargetTagAssigmentResult { @JsonProperty - private TargetsRest assignedTargets; + private List assignedTargets; @JsonProperty - private TargetsRest unassignedTargets; + private List unassignedTargets; - public void setAssignedTargets(final TargetsRest assignedTargets) { + public void setAssignedTargets(final List assignedTargets) { this.assignedTargets = assignedTargets; } - public TargetsRest getAssignedTargets() { + public List getAssignedTargets() { return assignedTargets; } - public void setUnassignedTargets(final TargetsRest unassignedTargets) { + public void setUnassignedTargets(final List unassignedTargets) { this.unassignedTargets = unassignedTargets; } - public TargetsRest getUnassignedTargets() { + public List getUnassignedTargets() { return unassignedTargets; } diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/target/DistributionSetAssigmentRest.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/target/MgmtDistributionSetAssigment.java similarity index 64% rename from hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/target/DistributionSetAssigmentRest.java rename to hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/target/MgmtDistributionSetAssigment.java index c2dc7f4a9..edfcc5687 100644 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/target/DistributionSetAssigmentRest.java +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/target/MgmtDistributionSetAssigment.java @@ -1,23 +1,23 @@ /** * Copyright (c) 2011-2015 Bosch Software Innovations GmbH, Germany. All rights reserved. */ -package org.eclipse.hawkbit.rest.resource.model.target; +package org.eclipse.hawkbit.mgmt.json.model.target; -import org.eclipse.hawkbit.rest.resource.model.IdRest; -import org.eclipse.hawkbit.rest.resource.model.distributionset.ActionTypeRest; +import org.eclipse.hawkbit.mgmt.json.model.MgmtId; +import org.eclipse.hawkbit.mgmt.json.model.distributionset.MgmtActionType; /** * Request Body of DistributionSet for assignment operations (ID only). * */ -public class DistributionSetAssigmentRest extends IdRest { +public class MgmtDistributionSetAssigment extends MgmtId { private long forcetime; - private ActionTypeRest type; + private MgmtActionType type; /** * @return the type */ - public ActionTypeRest getType() { + public MgmtActionType getType() { return type; } @@ -25,7 +25,7 @@ public class DistributionSetAssigmentRest extends IdRest { * @param type * the type to set */ - public void setType(final ActionTypeRest type) { + public void setType(final MgmtActionType type) { this.type = type; } diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/target/TargetRest.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/target/MgmtTarget.java similarity index 90% rename from hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/target/TargetRest.java rename to hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/target/MgmtTarget.java index 37baeeec9..40dd553a5 100644 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/target/TargetRest.java +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/target/MgmtTarget.java @@ -1,12 +1,12 @@ /** * Copyright (c) 2011-2015 Bosch Software Innovations GmbH, Germany. All rights reserved. */ -package org.eclipse.hawkbit.rest.resource.model.target; +package org.eclipse.hawkbit.mgmt.json.model.target; import java.net.URI; -import org.eclipse.hawkbit.rest.resource.model.NamedEntityRest; -import org.eclipse.hawkbit.rest.resource.model.PollStatusRest; +import org.eclipse.hawkbit.mgmt.json.model.MgmtNamedEntity; +import org.eclipse.hawkbit.mgmt.json.model.MgmtPollStatus; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @@ -20,7 +20,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; */ @JsonInclude(Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) -public class TargetRest extends NamedEntityRest { +public class MgmtTarget extends MgmtNamedEntity { @JsonProperty(required = true) private String controllerId; @@ -41,7 +41,7 @@ public class TargetRest extends NamedEntityRest { private String address; @JsonProperty - private PollStatusRest pollStatus; + private MgmtPollStatus pollStatus; @JsonProperty private String securityToken; @@ -111,7 +111,7 @@ public class TargetRest extends NamedEntityRest { /** * @return the pollStatus */ - public PollStatusRest getPollStatus() { + public MgmtPollStatus getPollStatus() { return pollStatus; } @@ -120,7 +120,7 @@ public class TargetRest extends NamedEntityRest { * the pollStatus to set */ @JsonIgnore - public void setPollStatus(final PollStatusRest pollStatus) { + public void setPollStatus(final MgmtPollStatus pollStatus) { this.pollStatus = pollStatus; } diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/target/TargetAttributes.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/target/MgmtTargetAttributes.java similarity index 63% rename from hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/target/TargetAttributes.java rename to hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/target/MgmtTargetAttributes.java index 821be6b45..dad8e868f 100644 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/target/TargetAttributes.java +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/target/MgmtTargetAttributes.java @@ -1,7 +1,7 @@ /** * Copyright (c) 2011-2015 Bosch Software Innovations GmbH, Germany. All rights reserved. */ -package org.eclipse.hawkbit.rest.resource.model.target; +package org.eclipse.hawkbit.mgmt.json.model.target; import java.util.HashMap; import java.util.Map; @@ -10,6 +10,6 @@ import java.util.Map; * {@link Map} with attributes of SP Target. * */ -public class TargetAttributes extends HashMap { +public class MgmtTargetAttributes extends HashMap { } diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/target/TargetRequestBody.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/target/MgmtTargetRequestBody.java similarity index 78% rename from hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/target/TargetRequestBody.java rename to hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/target/MgmtTargetRequestBody.java index bc1ca8a63..bc40326e4 100644 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/target/TargetRequestBody.java +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/json/model/target/MgmtTargetRequestBody.java @@ -1,7 +1,7 @@ /** * Copyright (c) 2011-2015 Bosch Software Innovations GmbH, Germany. All rights reserved. */ -package org.eclipse.hawkbit.rest.resource.model.target; +package org.eclipse.hawkbit.mgmt.json.model.target; import com.fasterxml.jackson.annotation.JsonProperty; @@ -9,7 +9,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; * Request body for target PUT/POST commands. * */ -public class TargetRequestBody { +public class MgmtTargetRequestBody { @JsonProperty(required = true) private String name; @@ -43,7 +43,7 @@ public class TargetRequestBody { * @param name * the name to set */ - public TargetRequestBody setName(final String name) { + public MgmtTargetRequestBody setName(final String name) { this.name = name; return this; } @@ -52,7 +52,7 @@ public class TargetRequestBody { * @param description * the description to set */ - public TargetRequestBody setDescription(final String description) { + public MgmtTargetRequestBody setDescription(final String description) { this.description = description; return this; } @@ -61,7 +61,7 @@ public class TargetRequestBody { * @param controllerId * the controllerId to set */ - public TargetRequestBody setControllerId(final String controllerId) { + public MgmtTargetRequestBody setControllerId(final String controllerId) { this.controllerId = controllerId; return this; } diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/api/DistributionSetRestApi.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/rest/api/MgmtDistributionSetRestApi.java similarity index 68% rename from hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/api/DistributionSetRestApi.java rename to hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/rest/api/MgmtDistributionSetRestApi.java index 05d377950..c61c9ecd3 100644 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/api/DistributionSetRestApi.java +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/rest/api/MgmtDistributionSetRestApi.java @@ -6,24 +6,20 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ - -package org.eclipse.hawkbit.rest.resource.api; +package org.eclipse.hawkbit.mgmt.rest.api; import java.util.List; -import org.eclipse.hawkbit.rest.resource.RestConstants; -import org.eclipse.hawkbit.rest.resource.model.MetadataRest; -import org.eclipse.hawkbit.rest.resource.model.MetadataRestPageList; -import org.eclipse.hawkbit.rest.resource.model.distributionset.DistributionSetPagedList; -import org.eclipse.hawkbit.rest.resource.model.distributionset.DistributionSetRequestBodyPost; -import org.eclipse.hawkbit.rest.resource.model.distributionset.DistributionSetRequestBodyPut; -import org.eclipse.hawkbit.rest.resource.model.distributionset.DistributionSetRest; -import org.eclipse.hawkbit.rest.resource.model.distributionset.DistributionSetsRest; -import org.eclipse.hawkbit.rest.resource.model.distributionset.TargetAssignmentRequestBody; -import org.eclipse.hawkbit.rest.resource.model.distributionset.TargetAssignmentResponseBody; -import org.eclipse.hawkbit.rest.resource.model.softwaremodule.SoftwareModuleAssigmentRest; -import org.eclipse.hawkbit.rest.resource.model.softwaremodule.SoftwareModulePagedList; -import org.eclipse.hawkbit.rest.resource.model.target.TargetPagedList; +import org.eclipse.hawkbit.mgmt.json.model.MgmtMetadata; +import org.eclipse.hawkbit.mgmt.json.model.PagedList; +import org.eclipse.hawkbit.mgmt.json.model.distributionset.MgmtDistributionSet; +import org.eclipse.hawkbit.mgmt.json.model.distributionset.MgmtDistributionSetRequestBodyPost; +import org.eclipse.hawkbit.mgmt.json.model.distributionset.MgmtDistributionSetRequestBodyPut; +import org.eclipse.hawkbit.mgmt.json.model.distributionset.MgmtTargetAssignmentRequestBody; +import org.eclipse.hawkbit.mgmt.json.model.distributionset.MgmtTargetAssignmentResponseBody; +import org.eclipse.hawkbit.mgmt.json.model.softwaremodule.MgmtSoftwareModule; +import org.eclipse.hawkbit.mgmt.json.model.softwaremodule.MgmtSoftwareModuleAssigment; +import org.eclipse.hawkbit.mgmt.json.model.target.MgmtTarget; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; @@ -35,8 +31,8 @@ import org.springframework.web.bind.annotation.RequestParam; /** * REST Resource handling for DistributionSet CRUD operations. */ -@RequestMapping(RestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING) -public interface DistributionSetRestApi { +@RequestMapping(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING) +public interface MgmtDistributionSetRestApi { /** * Handles the GET request of retrieving all DistributionSets . @@ -58,11 +54,11 @@ public interface DistributionSetRestApi { * JsonResponseExceptionHandler is handling the response. */ @RequestMapping(method = RequestMethod.GET, produces = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }) - public ResponseEntity getDistributionSets( - @RequestParam(value = RestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = RestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = RestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam); + ResponseEntity> getDistributionSets( + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam); /** * Handles the GET request of retrieving a single DistributionSet . @@ -72,12 +68,10 @@ public interface DistributionSetRestApi { * * @return a single DistributionSet with status OK. * - * @throws EntityNotFoundException - * in case no DistributionSet with the given ID exists. */ @RequestMapping(method = RequestMethod.GET, value = "/{distributionSetId}", produces = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }) - public ResponseEntity getDistributionSet( + ResponseEntity getDistributionSet( @PathVariable("distributionSetId") final Long distributionSetId); /** @@ -93,8 +87,8 @@ public interface DistributionSetRestApi { */ @RequestMapping(method = RequestMethod.POST, consumes = { MediaType.APPLICATION_JSON_VALUE, "application/hal+json" }, produces = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }) - public ResponseEntity createDistributionSets( - @RequestBody final List sets); + ResponseEntity> createDistributionSets( + @RequestBody final List sets); /** * Handles the DELETE request for a single DistributionSet . @@ -105,7 +99,7 @@ public interface DistributionSetRestApi { * */ @RequestMapping(method = RequestMethod.DELETE, value = "/{distributionSetId}") - public ResponseEntity deleteDistributionSet(@PathVariable("distributionSetId") final Long distributionSetId); + ResponseEntity deleteDistributionSet(@PathVariable("distributionSetId") final Long distributionSetId); /** * Handles the UPDATE request for a single DistributionSet . @@ -120,9 +114,9 @@ public interface DistributionSetRestApi { */ @RequestMapping(method = RequestMethod.PUT, value = "/{distributionSetId}", consumes = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }, produces = { MediaType.APPLICATION_JSON_VALUE, "application/hal+json" }) - public ResponseEntity updateDistributionSet( + ResponseEntity updateDistributionSet( @PathVariable("distributionSetId") final Long distributionSetId, - @RequestBody final DistributionSetRequestBodyPut toUpdate); + @RequestBody final MgmtDistributionSetRequestBodyPut toUpdate); /** * Handles the GET request of retrieving assigned targets to a specific @@ -148,12 +142,12 @@ public interface DistributionSetRestApi { */ @RequestMapping(method = RequestMethod.GET, value = "/{distributionSetId}/assignedTargets", produces = { MediaType.APPLICATION_JSON_VALUE, "application/hal+json" }) - public ResponseEntity getAssignedTargets( + ResponseEntity> getAssignedTargets( @PathVariable("distributionSetId") final Long distributionSetId, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = RestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = RestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam); + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam); /** * Handles the GET request of retrieving installed targets to a specific @@ -179,12 +173,12 @@ public interface DistributionSetRestApi { */ @RequestMapping(method = RequestMethod.GET, value = "/{distributionSetId}/installedTargets", produces = { MediaType.APPLICATION_JSON_VALUE, "application/hal+json" }) - public ResponseEntity getInstalledTargets( + ResponseEntity> getInstalledTargets( @PathVariable("distributionSetId") final Long distributionSetId, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = RestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = RestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam); + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam); /** * Handles the POST request of assigning multiple targets to a single @@ -202,9 +196,9 @@ public interface DistributionSetRestApi { @RequestMapping(method = RequestMethod.POST, value = "/{distributionSetId}/assignedTargets", consumes = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }, produces = { MediaType.APPLICATION_JSON_VALUE, "application/hal+json" }) - public ResponseEntity createAssignedTarget( + ResponseEntity createAssignedTarget( @PathVariable("distributionSetId") final Long distributionSetId, - @RequestBody final List targetIds); + @RequestBody final List targetIds); /** * Gets a paged list of meta data for a distribution set. @@ -228,12 +222,11 @@ public interface DistributionSetRestApi { */ @RequestMapping(method = RequestMethod.GET, value = "/{distributionSetId}/metadata", produces = { MediaType.APPLICATION_JSON_VALUE, "application/hal+json" }) - public ResponseEntity getMetadata( - @PathVariable("distributionSetId") final Long distributionSetId, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = RestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = RestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam); + ResponseEntity> getMetadata(@PathVariable("distributionSetId") final Long distributionSetId, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam); /** * Gets a single meta data value for a specific key of a distribution set. @@ -247,8 +240,7 @@ public interface DistributionSetRestApi { */ @RequestMapping(method = RequestMethod.GET, value = "/{distributionSetId}/metadata/{metadataKey}", produces = { MediaType.APPLICATION_JSON_VALUE }) - public ResponseEntity getMetadataValue( - @PathVariable("distributionSetId") final Long distributionSetId, + ResponseEntity getMetadataValue(@PathVariable("distributionSetId") final Long distributionSetId, @PathVariable("metadataKey") final String metadataKey); /** @@ -263,8 +255,8 @@ public interface DistributionSetRestApi { */ @RequestMapping(method = RequestMethod.PUT, value = "/{distributionSetId}/metadata/{metadataKey}", produces = { MediaType.APPLICATION_JSON_VALUE, "application/hal+json" }) - public ResponseEntity updateMetadata(@PathVariable("distributionSetId") final Long distributionSetId, - @PathVariable("metadataKey") final String metadataKey, @RequestBody final MetadataRest metadata); + ResponseEntity updateMetadata(@PathVariable("distributionSetId") final Long distributionSetId, + @PathVariable("metadataKey") final String metadataKey, @RequestBody final MgmtMetadata metadata); /** * Deletes a single meta data entry from the distribution set. @@ -276,7 +268,7 @@ public interface DistributionSetRestApi { * @return status OK if the delete request is successful */ @RequestMapping(method = RequestMethod.DELETE, value = "/{distributionSetId}/metadata/{metadataKey}") - public ResponseEntity deleteMetadata(@PathVariable("distributionSetId") final Long distributionSetId, + ResponseEntity deleteMetadata(@PathVariable("distributionSetId") final Long distributionSetId, @PathVariable("metadataKey") final String metadataKey); /** @@ -292,9 +284,8 @@ public interface DistributionSetRestApi { @RequestMapping(method = RequestMethod.POST, value = "/{distributionSetId}/metadata", consumes = { MediaType.APPLICATION_JSON_VALUE, "application/hal+json" }, produces = { MediaType.APPLICATION_JSON_VALUE, "application/hal+json" }) - public ResponseEntity> createMetadata( - @PathVariable("distributionSetId") final Long distributionSetId, - @RequestBody final List metadataRest); + ResponseEntity> createMetadata(@PathVariable("distributionSetId") final Long distributionSetId, + @RequestBody final List metadataRest); /** * Assigns a list of software modules to a distribution set. @@ -305,15 +296,12 @@ public interface DistributionSetRestApi { * the list of software modules ids to assign * @return http status * - * @throws EntityNotFoundException - * in case no distribution set with the given - * {@code distributionSetId} exists. */ @RequestMapping(method = RequestMethod.POST, value = "/{distributionSetId}/assignedSM", consumes = { MediaType.APPLICATION_JSON_VALUE, "application/hal+json" }, produces = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }) - public ResponseEntity assignSoftwareModules(@PathVariable("distributionSetId") final Long distributionSetId, - @RequestBody final List softwareModuleIDs); + ResponseEntity assignSoftwareModules(@PathVariable("distributionSetId") final Long distributionSetId, + @RequestBody final List softwareModuleIDs); /** * Deletes the assignment of the software module form the distribution set. @@ -325,13 +313,9 @@ public interface DistributionSetRestApi { * the software module id to get rejected form the distribution * set * @return status OK if rejection was successful. - * @throws EntityNotFoundException - * in case no distribution set with the given - * {@code distributionSetId} exists. */ @RequestMapping(method = RequestMethod.DELETE, value = "/{distributionSetId}/assignedSM/{softwareModuleId}") - public ResponseEntity deleteAssignSoftwareModules( - @PathVariable("distributionSetId") final Long distributionSetId, + ResponseEntity deleteAssignSoftwareModules(@PathVariable("distributionSetId") final Long distributionSetId, @PathVariable("softwareModuleId") final Long softwareModuleId); /** @@ -351,15 +335,12 @@ public interface DistributionSetRestApi { * {@code field:direction, field:direction} * @return a list of the assigned software modules of a distribution set * with status OK, if none is assigned than {@code null} - * @throws EntityNotFoundException - * in case no distribution set with the given - * {@code distributionSetId} exists. */ @RequestMapping(method = RequestMethod.GET, value = "/{distributionSetId}/assignedSM", produces = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }) - public ResponseEntity getAssignedSoftwareModules( + ResponseEntity> getAssignedSoftwareModules( @PathVariable("distributionSetId") final Long distributionSetId, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = RestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = RestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam); + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam); } diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/api/DistributionSetTagRestApi.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/rest/api/MgmtDistributionSetTagRestApi.java similarity index 61% rename from hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/api/DistributionSetTagRestApi.java rename to hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/rest/api/MgmtDistributionSetTagRestApi.java index d99368dc2..5a836ef55 100644 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/api/DistributionSetTagRestApi.java +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/rest/api/MgmtDistributionSetTagRestApi.java @@ -6,18 +6,16 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource.api; +package org.eclipse.hawkbit.mgmt.rest.api; import java.util.List; -import org.eclipse.hawkbit.rest.resource.RestConstants; -import org.eclipse.hawkbit.rest.resource.model.distributionset.DistributionSetsRest; -import org.eclipse.hawkbit.rest.resource.model.tag.AssignedDistributionSetRequestBody; -import org.eclipse.hawkbit.rest.resource.model.tag.DistributionSetTagAssigmentResultRest; -import org.eclipse.hawkbit.rest.resource.model.tag.TagPagedList; -import org.eclipse.hawkbit.rest.resource.model.tag.TagRequestBodyPut; -import org.eclipse.hawkbit.rest.resource.model.tag.TagRest; -import org.eclipse.hawkbit.rest.resource.model.tag.TagsRest; +import org.eclipse.hawkbit.mgmt.json.model.PagedList; +import org.eclipse.hawkbit.mgmt.json.model.distributionset.MgmtDistributionSet; +import org.eclipse.hawkbit.mgmt.json.model.tag.MgmtAssignedDistributionSetRequestBody; +import org.eclipse.hawkbit.mgmt.json.model.tag.MgmtDistributionSetTagAssigmentResult; +import org.eclipse.hawkbit.mgmt.json.model.tag.MgmtTag; +import org.eclipse.hawkbit.mgmt.json.model.tag.MgmtTagRequestBodyPut; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; @@ -30,8 +28,8 @@ import org.springframework.web.bind.annotation.RequestParam; * REST Resource handling for DistributionSetTag CRUD operations. * */ -@RequestMapping(RestConstants.DISTRIBUTIONSET_TAG_V1_REQUEST_MAPPING) -public interface DistributionSetTagRestApi { +@RequestMapping(MgmtRestConstants.DISTRIBUTIONSET_TAG_V1_REQUEST_MAPPING) +public interface MgmtDistributionSetTagRestApi { /** * Handles the GET request of retrieving all DistributionSet tags. * @@ -53,11 +51,11 @@ public interface DistributionSetTagRestApi { * JsonResponseExceptionHandler is handling the response. */ @RequestMapping(method = RequestMethod.GET, produces = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }) - public ResponseEntity getDistributionSetTags( - @RequestParam(value = RestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = RestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = RestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam); + ResponseEntity> getDistributionSetTags( + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam); /** * Handles the GET request of retrieving a single distribution set tag. @@ -66,13 +64,10 @@ public interface DistributionSetTagRestApi { * the ID of the distribution set tag to retrieve * * @return a single distribution set tag with status OK. - * @throws EntityNotFoundException - * in case the given {@code distributionsetTagId} doesn't - * exists. */ @RequestMapping(method = RequestMethod.GET, value = "/{distributionsetTagId}", produces = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }) - public ResponseEntity getDistributionSetTag( + ResponseEntity getDistributionSetTag( @PathVariable("distributionsetTagId") final Long distributionsetTagId); /** @@ -87,7 +82,7 @@ public interface DistributionSetTagRestApi { */ @RequestMapping(method = RequestMethod.POST, consumes = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }, produces = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }) - public ResponseEntity createDistributionSetTags(@RequestBody final List tags); + ResponseEntity> createDistributionSetTags(@RequestBody final List tags); /** * @@ -99,15 +94,12 @@ public interface DistributionSetTagRestApi { * the the request body to be updated * @return status OK if update is successful and the updated distribution * set tag. - * @throws EntityNotFoundException - * in case the given {@code distributionsetTagId} doesn't - * exists. */ @RequestMapping(method = RequestMethod.PUT, value = "/{distributionsetTagId}", consumes = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }, produces = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }) - public ResponseEntity updateDistributionSetTag( + ResponseEntity updateDistributionSetTag( @PathVariable("distributionsetTagId") final Long distributionsetTagId, - @RequestBody final TagRequestBodyPut restDSTagRest); + @RequestBody final MgmtTagRequestBodyPut restDSTagRest); /** * Handles the DELETE request for a single distribution set tag. @@ -115,13 +107,10 @@ public interface DistributionSetTagRestApi { * @param distributionsetTagId * the ID of the distribution set tag * @return status OK if delete as successfully. - * @throws EntityNotFoundException - * in case the given {@code distributionsetTagId} doesn't - * exists. * */ @RequestMapping(method = RequestMethod.DELETE, value = "/{distributionsetTagId}") - public ResponseEntity deleteDistributionSetTag( + ResponseEntity deleteDistributionSetTag( @PathVariable("distributionsetTagId") final Long distributionsetTagId); /** @@ -132,12 +121,9 @@ public interface DistributionSetTagRestApi { * the ID of the distribution set tag * * @return the list of assigned distribution sets. - * @throws EntityNotFoundException - * in case the given {@code distributionsetTagId} doesn't - * exists. */ - @RequestMapping(method = RequestMethod.GET, value = RestConstants.DISTRIBUTIONSET_REQUEST_MAPPING) - public ResponseEntity getAssignedDistributionSets( + @RequestMapping(method = RequestMethod.GET, value = MgmtRestConstants.DISTRIBUTIONSET_REQUEST_MAPPING) + ResponseEntity> getAssignedDistributionSets( @PathVariable("distributionsetTagId") final Long distributionsetTagId); /** @@ -151,15 +137,12 @@ public interface DistributionSetTagRestApi { * * @return the list of assigned distribution sets and unassigned * distribution sets. - * @throws EntityNotFoundException - * in case the given {@code distributionsetTagId} doesn't - * exists. */ - @RequestMapping(method = RequestMethod.POST, value = RestConstants.DISTRIBUTIONSET_REQUEST_MAPPING + @RequestMapping(method = RequestMethod.POST, value = MgmtRestConstants.DISTRIBUTIONSET_REQUEST_MAPPING + "/toggleTagAssignment") - public ResponseEntity toggleTagAssignment( + ResponseEntity toggleTagAssignment( @PathVariable("distributionsetTagId") final Long distributionsetTagId, - @RequestBody final List assignedDSRequestBodies); + @RequestBody final List assignedDSRequestBodies); /** * Handles the POST request to assign distribution sets to the given tag id. @@ -170,14 +153,11 @@ public interface DistributionSetTagRestApi { * list of distribution sets ids to be assigned * * @return the list of assigned distribution set. - * @throws EntityNotFoundException - * in case the given {@code distributionsetTagId} doesn't - * exists. */ - @RequestMapping(method = RequestMethod.POST, value = RestConstants.DISTRIBUTIONSET_REQUEST_MAPPING) - public ResponseEntity assignDistributionSets( + @RequestMapping(method = RequestMethod.POST, value = MgmtRestConstants.DISTRIBUTIONSET_REQUEST_MAPPING) + ResponseEntity> assignDistributionSets( @PathVariable("distributionsetTagId") final Long distributionsetTagId, - @RequestBody final List assignedDSRequestBodies); + @RequestBody final List assignedDSRequestBodies); /** * Handles the DELETE request to unassign all distribution set from the @@ -186,12 +166,9 @@ public interface DistributionSetTagRestApi { * @param distributionsetTagId * the ID of the distribution set tag to retrieve * @return http status code - * @throws EntityNotFoundException - * in case the given {@code distributionsetTagId} doesn't - * exists. */ - @RequestMapping(method = RequestMethod.DELETE, value = RestConstants.DISTRIBUTIONSET_REQUEST_MAPPING) - public ResponseEntity unassignDistributionSets( + @RequestMapping(method = RequestMethod.DELETE, value = MgmtRestConstants.DISTRIBUTIONSET_REQUEST_MAPPING) + ResponseEntity unassignDistributionSets( @PathVariable("distributionsetTagId") final Long distributionsetTagId); /** @@ -203,13 +180,9 @@ public interface DistributionSetTagRestApi { * @param distributionsetId * the ID of the distribution set to unassign * @return http status code - * @throws EntityNotFoundException - * in case the given {@code distributionsetTagId} doesn't - * exists. */ - @RequestMapping(method = RequestMethod.DELETE, value = RestConstants.DISTRIBUTIONSET_REQUEST_MAPPING + @RequestMapping(method = RequestMethod.DELETE, value = MgmtRestConstants.DISTRIBUTIONSET_REQUEST_MAPPING + "/{distributionsetId}") - public ResponseEntity unassignDistributionSet( - @PathVariable("distributionsetTagId") final Long distributionsetTagId, + ResponseEntity unassignDistributionSet(@PathVariable("distributionsetTagId") final Long distributionsetTagId, @PathVariable("distributionsetId") final Long distributionsetId); } diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/api/DistributionSetTypeRestApi.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/rest/api/MgmtDistributionSetTypeRestApi.java similarity index 70% rename from hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/api/DistributionSetTypeRestApi.java rename to hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/rest/api/MgmtDistributionSetTypeRestApi.java index 9bed7f4f8..25468739e 100644 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/api/DistributionSetTypeRestApi.java +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/rest/api/MgmtDistributionSetTypeRestApi.java @@ -6,19 +6,16 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource.api; +package org.eclipse.hawkbit.mgmt.rest.api; import java.util.List; -import org.eclipse.hawkbit.rest.resource.RestConstants; -import org.eclipse.hawkbit.rest.resource.model.IdRest; -import org.eclipse.hawkbit.rest.resource.model.distributionsettype.DistributionSetTypePagedList; -import org.eclipse.hawkbit.rest.resource.model.distributionsettype.DistributionSetTypeRequestBodyPost; -import org.eclipse.hawkbit.rest.resource.model.distributionsettype.DistributionSetTypeRequestBodyPut; -import org.eclipse.hawkbit.rest.resource.model.distributionsettype.DistributionSetTypeRest; -import org.eclipse.hawkbit.rest.resource.model.distributionsettype.DistributionSetTypesRest; -import org.eclipse.hawkbit.rest.resource.model.softwaremoduletype.SoftwareModuleTypeRest; -import org.eclipse.hawkbit.rest.resource.model.softwaremoduletype.SoftwareModuleTypesRest; +import org.eclipse.hawkbit.mgmt.json.model.MgmtId; +import org.eclipse.hawkbit.mgmt.json.model.PagedList; +import org.eclipse.hawkbit.mgmt.json.model.distributionsettype.MgmtDistributionSetType; +import org.eclipse.hawkbit.mgmt.json.model.distributionsettype.MgmtDistributionSetTypeRequestBodyPost; +import org.eclipse.hawkbit.mgmt.json.model.distributionsettype.MgmtDistributionSetTypeRequestBodyPut; +import org.eclipse.hawkbit.mgmt.json.model.softwaremoduletype.MgmtSoftwareModuleType; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; @@ -32,8 +29,8 @@ import org.springframework.web.bind.annotation.RequestParam; * operations. * */ -@RequestMapping(RestConstants.DISTRIBUTIONSETTYPE_V1_REQUEST_MAPPING) -public interface DistributionSetTypeRestApi { +@RequestMapping(MgmtRestConstants.DISTRIBUTIONSETTYPE_V1_REQUEST_MAPPING) +public interface MgmtDistributionSetTypeRestApi { /** * Handles the GET request of retrieving all DistributionSetTypes. @@ -57,11 +54,11 @@ public interface DistributionSetTypeRestApi { * response. */ @RequestMapping(method = RequestMethod.GET, produces = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }) - public ResponseEntity getDistributionSetTypes( - @RequestParam(value = RestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = RestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = RestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam); + ResponseEntity> getDistributionSetTypes( + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam); /** * Handles the GET request of retrieving a single DistributionSetType @@ -71,12 +68,10 @@ public interface DistributionSetTypeRestApi { * the ID of the module type to retrieve * * @return a single softwareModule with status OK. - * @throws EntityNotFoundException - * in case no with the given {@code softwareModuleId} exists. */ @RequestMapping(method = RequestMethod.GET, value = "/{distributionSetTypeId}", produces = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }) - public ResponseEntity getDistributionSetType( + ResponseEntity getDistributionSetType( @PathVariable("distributionSetTypeId") final Long distributionSetTypeId); /** @@ -88,7 +83,7 @@ public interface DistributionSetTypeRestApi { * */ @RequestMapping(method = RequestMethod.DELETE, value = "/{distributionSetTypeId}") - public ResponseEntity deleteDistributionSetType( + ResponseEntity deleteDistributionSetType( @PathVariable("distributionSetTypeId") final Long distributionSetTypeId); /** @@ -102,9 +97,9 @@ public interface DistributionSetTypeRestApi { */ @RequestMapping(method = RequestMethod.PUT, value = "/{distributionSetTypeId}", consumes = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }, produces = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }) - public ResponseEntity updateDistributionSetType( + ResponseEntity updateDistributionSetType( @PathVariable("distributionSetTypeId") final Long distributionSetTypeId, - @RequestBody final DistributionSetTypeRequestBodyPut restDistributionSetType); + @RequestBody final MgmtDistributionSetTypeRequestBodyPut restDistributionSetType); /** * Handles the POST request of creating new DistributionSetTypes. The @@ -119,8 +114,8 @@ public interface DistributionSetTypeRestApi { */ @RequestMapping(method = RequestMethod.POST, consumes = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }, produces = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }) - public ResponseEntity createDistributionSetTypes( - @RequestBody final List distributionSetTypes); + ResponseEntity> createDistributionSetTypes( + @RequestBody final List distributionSetTypes); /** * Handles the GET request of retrieving the list of mandatory software @@ -131,9 +126,9 @@ public interface DistributionSetTypeRestApi { * @return Unpaged list of module types and OK in case of success. */ @RequestMapping(method = RequestMethod.GET, value = "/{distributionSetTypeId}/" - + RestConstants.DISTRIBUTIONSETTYPE_V1_MANDATORY_MODULE_TYPES, produces = { "application/hal+json", + + MgmtRestConstants.DISTRIBUTIONSETTYPE_V1_MANDATORY_MODULE_TYPES, produces = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }) - public ResponseEntity getMandatoryModules( + ResponseEntity> getMandatoryModules( @PathVariable("distributionSetTypeId") final Long distributionSetTypeId); /** @@ -147,9 +142,9 @@ public interface DistributionSetTypeRestApi { * @return Unpaged list of module types and OK in case of success. */ @RequestMapping(method = RequestMethod.GET, value = "/{distributionSetTypeId}/" - + RestConstants.DISTRIBUTIONSETTYPE_V1_MANDATORY_MODULE_TYPES + + MgmtRestConstants.DISTRIBUTIONSETTYPE_V1_MANDATORY_MODULE_TYPES + "/{softwareModuleTypeId}", produces = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }) - public ResponseEntity getMandatoryModule( + ResponseEntity getMandatoryModule( @PathVariable("distributionSetTypeId") final Long distributionSetTypeId, @PathVariable("softwareModuleTypeId") final Long softwareModuleTypeId); @@ -164,9 +159,9 @@ public interface DistributionSetTypeRestApi { * @return Unpaged list of module types and OK in case of success. */ @RequestMapping(method = RequestMethod.GET, value = "/{distributionSetTypeId}/" - + RestConstants.DISTRIBUTIONSETTYPE_V1_OPTIONAL_MODULE_TYPES + + MgmtRestConstants.DISTRIBUTIONSETTYPE_V1_OPTIONAL_MODULE_TYPES + "/{softwareModuleTypeId}", produces = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }) - public ResponseEntity getOptionalModule( + ResponseEntity getOptionalModule( @PathVariable("distributionSetTypeId") final Long distributionSetTypeId, @PathVariable("softwareModuleTypeId") final Long softwareModuleTypeId); @@ -179,9 +174,9 @@ public interface DistributionSetTypeRestApi { * @return Unpaged list of module types and OK in case of success. */ @RequestMapping(method = RequestMethod.GET, value = "/{distributionSetTypeId}/" - + RestConstants.DISTRIBUTIONSETTYPE_V1_OPTIONAL_MODULE_TYPES, produces = { "application/hal+json", + + MgmtRestConstants.DISTRIBUTIONSETTYPE_V1_OPTIONAL_MODULE_TYPES, produces = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }) - public ResponseEntity getOptionalModules( + ResponseEntity> getOptionalModules( @PathVariable("distributionSetTypeId") final Long distributionSetTypeId); /** @@ -196,10 +191,9 @@ public interface DistributionSetTypeRestApi { * @return OK if the request was successful */ @RequestMapping(method = RequestMethod.DELETE, value = "/{distributionSetTypeId}/" - + RestConstants.DISTRIBUTIONSETTYPE_V1_MANDATORY_MODULE_TYPES + + MgmtRestConstants.DISTRIBUTIONSETTYPE_V1_MANDATORY_MODULE_TYPES + "/{softwareModuleTypeId}", produces = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }) - public ResponseEntity removeMandatoryModule( - @PathVariable("distributionSetTypeId") final Long distributionSetTypeId, + ResponseEntity removeMandatoryModule(@PathVariable("distributionSetTypeId") final Long distributionSetTypeId, @PathVariable("softwareModuleTypeId") final Long softwareModuleTypeId); /** @@ -214,10 +208,9 @@ public interface DistributionSetTypeRestApi { * @return OK if the request was successful */ @RequestMapping(method = RequestMethod.DELETE, value = "/{distributionSetTypeId}/" - + RestConstants.DISTRIBUTIONSETTYPE_V1_OPTIONAL_MODULE_TYPES + + MgmtRestConstants.DISTRIBUTIONSETTYPE_V1_OPTIONAL_MODULE_TYPES + "/{softwareModuleTypeId}", produces = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }) - public ResponseEntity removeOptionalModule( - @PathVariable("distributionSetTypeId") final Long distributionSetTypeId, + ResponseEntity removeOptionalModule(@PathVariable("distributionSetTypeId") final Long distributionSetTypeId, @PathVariable("softwareModuleTypeId") final Long softwareModuleTypeId); /** @@ -232,11 +225,11 @@ public interface DistributionSetTypeRestApi { * @return OK if the request was successful */ @RequestMapping(method = RequestMethod.POST, value = "/{distributionSetTypeId}/" - + RestConstants.DISTRIBUTIONSETTYPE_V1_MANDATORY_MODULE_TYPES, consumes = { "application/hal+json", + + MgmtRestConstants.DISTRIBUTIONSETTYPE_V1_MANDATORY_MODULE_TYPES, consumes = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }, produces = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }) - public ResponseEntity addMandatoryModule( - @PathVariable("distributionSetTypeId") final Long distributionSetTypeId, @RequestBody final IdRest smtId); + ResponseEntity addMandatoryModule(@PathVariable("distributionSetTypeId") final Long distributionSetTypeId, + @RequestBody final MgmtId smtId); /** * Handles the POST request for adding an optional software module type to a @@ -250,10 +243,10 @@ public interface DistributionSetTypeRestApi { * @return OK if the request was successful */ @RequestMapping(method = RequestMethod.POST, value = "/{distributionSetTypeId}/" - + RestConstants.DISTRIBUTIONSETTYPE_V1_OPTIONAL_MODULE_TYPES, consumes = { "application/hal+json", + + MgmtRestConstants.DISTRIBUTIONSETTYPE_V1_OPTIONAL_MODULE_TYPES, consumes = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }, produces = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }) - public ResponseEntity addOptionalModule( - @PathVariable("distributionSetTypeId") final Long distributionSetTypeId, @RequestBody final IdRest smtId); + ResponseEntity addOptionalModule(@PathVariable("distributionSetTypeId") final Long distributionSetTypeId, + @RequestBody final MgmtId smtId); } diff --git a/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/rest/api/MgmtDownloadArtifactRestApi.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/rest/api/MgmtDownloadArtifactRestApi.java new file mode 100644 index 000000000..ea6dccc7e --- /dev/null +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/rest/api/MgmtDownloadArtifactRestApi.java @@ -0,0 +1,44 @@ +/** + * Copyright (c) 2015 Bosch Software Innovations GmbH and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + */ +package org.eclipse.hawkbit.mgmt.rest.api; + +import java.io.InputStream; + +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; + +/** + * + */ +@RequestMapping(MgmtRestConstants.SOFTWAREMODULE_V1_REQUEST_MAPPING) +public interface MgmtDownloadArtifactRestApi { + + /** + * Handles the GET request for downloading an artifact. + * + * @param softwareModuleId + * of the parent SoftwareModule + * @param artifactId + * of the related LocalArtifact + * @param servletResponse + * of the servlet + * @param request + * of the client + * + * @return responseEntity with status ok if successful + */ + @RequestMapping(method = RequestMethod.GET, value = "/{softwareModuleId}/artifacts/{artifactId}/download") + @ResponseBody + ResponseEntity downloadArtifact(@PathVariable("softwareModuleId") final Long softwareModuleId, + @PathVariable("artifactId") final Long artifactId); + +} diff --git a/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/rest/api/MgmtDownloadRestApi.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/rest/api/MgmtDownloadRestApi.java new file mode 100644 index 000000000..52cd1c991 --- /dev/null +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/rest/api/MgmtDownloadRestApi.java @@ -0,0 +1,39 @@ +/** + * 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.mgmt.rest.api; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; + +/** + * A resource for download artifacts. + * + */ +@RequestMapping(MgmtRestConstants.DOWNLOAD_ID_V1_REQUEST_MAPPING_BASE) +public interface MgmtDownloadRestApi { + + /** + * Handles the GET request for downloading an artifact. + * + * @param downloadId + * the generated download id + * @param response + * of the servlet + * @return {@link ResponseEntity} with status {@link HttpStatus#OK} if + * successful + */ + @RequestMapping(method = RequestMethod.GET, value = MgmtRestConstants.DOWNLOAD_ID_V1_REQUEST_MAPPING) + @ResponseBody + ResponseEntity downloadArtifactByDownloadId(@PathVariable("downloadId") final String downloadId); + +} diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/RestConstants.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/rest/api/MgmtRestConstants.java similarity index 97% rename from hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/RestConstants.java rename to hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/rest/api/MgmtRestConstants.java index bde96f7a8..e8c25403f 100644 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/RestConstants.java +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/rest/api/MgmtRestConstants.java @@ -6,31 +6,19 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource; +package org.eclipse.hawkbit.mgmt.rest.api; /** * Constants for RESTful API. * - * - * */ -public final class RestConstants { +public final class MgmtRestConstants { /** * API version definition. We are using only major versions. */ public static final String API_VERSION = "v1"; - /** - * The base URL mapping for the spring acuator management context path. - */ - public static final String BASE_SYSTEM_MAPPING = "/system"; - - /** - * URL mapping for system admin operations. - */ - public static final String SYSTEM_ADMIN_MAPPING = BASE_SYSTEM_MAPPING + "/admin"; - /** * The base URL mapping of the SP rest resources. */ @@ -50,6 +38,77 @@ public final class RestConstants { */ public static final String REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT = "50"; + /** + * The software module URL mapping rest resource. + */ + public static final String SOFTWAREMODULE_V1_REQUEST_MAPPING = BASE_V1_REQUEST_MAPPING + "/softwaremodules"; + + public static final String DOWNLOAD_ID_V1_REQUEST_MAPPING_BASE = "/api/" + API_VERSION + "/downloadserver/"; + + public static final String DOWNLOAD_ID_V1_REQUEST_MAPPING = "downloadId/{downloadId}"; + + /** + * The base URL mapping for the spring acuator management context path. + */ + public static final String BASE_SYSTEM_MAPPING = "/system"; + + /** + * URL mapping for system admin operations. + */ + public static final String SYSTEM_ADMIN_MAPPING = BASE_SYSTEM_MAPPING + "/admin"; + + public static final String SYSTEM_V1_REQUEST_MAPPING = BASE_V1_REQUEST_MAPPING + BASE_SYSTEM_MAPPING; + + /** + * The target URL mapping, href link for assigned distribution set. + */ + public static final String TARGET_V1_ASSIGNED_DISTRIBUTION_SET = "assignedDS"; + /** + * The target URL mapping, href link for installed distribution set. + */ + public static final String TARGET_V1_INSTALLED_DISTRIBUTION_SET = "installedDS"; + /** + * The target URL mapping, href link for target attributes. + */ + public static final String TARGET_V1_ATTRIBUTES = "attributes"; + /** + * The target URL mapping, href link for target actions. + */ + public static final String TARGET_V1_ACTIONS = "actions"; + /** + * The target URL mapping, href link for canceled actions. + */ + public static final String TARGET_V1_CANCELED_ACTION = "canceledaction"; + /** + * The target URL mapping, href link for canceled actions. + */ + public static final String TARGET_V1_ACTION_STATUS = "status"; + + /** + * The target URL mapping rest resource. + */ + public static final String TARGET_V1_REQUEST_MAPPING = BASE_V1_REQUEST_MAPPING + "/targets"; + + /** + * The tag URL mapping rest resource. + */ + public static final String TARGET_TAG_V1_REQUEST_MAPPING = BASE_V1_REQUEST_MAPPING + "/targettags"; + /** + * The tag URL mapping rest resource. + */ + public static final String TARGET_TAG_TAGERTS_REQUEST_MAPPING = "/{targetTagId}/targets"; + + /** + * The tag URL mapping rest resource. + */ + public static final String DISTRIBUTIONSET_TAG_V1_REQUEST_MAPPING = BASE_V1_REQUEST_MAPPING + + "/distributionsettags"; + + /** + * The tag URL mapping rest resource. + */ + public static final String DISTRIBUTIONSET_REQUEST_MAPPING = "/{distributionsetTagId}/distributionsets"; + /** * The default offset parameter in case the offset parameter is not present * in the request. @@ -87,62 +146,6 @@ public final class RestConstants { */ public static final String REQUEST_PARAMETER_SEARCH = "q"; - /** - * The target URL mapping, href link for assigned distribution set. - */ - public static final String TARGET_V1_ASSIGNED_DISTRIBUTION_SET = "assignedDS"; - /** - * The target URL mapping, href link for installed distribution set. - */ - public static final String TARGET_V1_INSTALLED_DISTRIBUTION_SET = "installedDS"; - /** - * The target URL mapping, href link for target attributes. - */ - public static final String TARGET_V1_ATTRIBUTES = "attributes"; - /** - * The target URL mapping, href link for target actions. - */ - public static final String TARGET_V1_ACTIONS = "actions"; - /** - * The target URL mapping, href link for canceled actions. - */ - public static final String TARGET_V1_CANCELED_ACTION = "canceledaction"; - /** - * The target URL mapping, href link for canceled actions. - */ - public static final String TARGET_V1_ACTION_STATUS = "status"; - - /** - * The target URL mapping rest resource. - */ - public static final String TARGET_V1_REQUEST_MAPPING = BASE_V1_REQUEST_MAPPING + "/targets"; - - public static final String SYSTEM_V1_REQUEST_MAPPING = BASE_V1_REQUEST_MAPPING + "/system"; - /** - * The software module URL mapping rest resource. - */ - public static final String SOFTWAREMODULE_V1_REQUEST_MAPPING = BASE_V1_REQUEST_MAPPING + "/softwaremodules"; - - /** - * The tag URL mapping rest resource. - */ - public static final String TARGET_TAG_V1_REQUEST_MAPPING = BASE_V1_REQUEST_MAPPING + "/targettags"; - /** - * The tag URL mapping rest resource. - */ - public static final String TARGET_TAG_TAGERTS_REQUEST_MAPPING = "/{targetTagId}/targets"; - - /** - * The tag URL mapping rest resource. - */ - public static final String DISTRIBUTIONSET_TAG_V1_REQUEST_MAPPING = BASE_V1_REQUEST_MAPPING - + "/distributionsettags"; - - /** - * The tag URL mapping rest resource. - */ - public static final String DISTRIBUTIONSET_REQUEST_MAPPING = "/{distributionsetTagId}/distributionsets"; - /** * The software module type URL mapping rest resource. */ @@ -184,11 +187,8 @@ public final class RestConstants { public static final String DISTRIBUTIONSETTYPE_V1_MANDATORY_MODULE_TYPES = "mandatorymoduletypes"; - public static final String DOWNLOAD_ID_V1_REQUEST_MAPPING_BASE = "/api/" + API_VERSION + "/downloadserver/"; - public static final String DOWNLOAD_ID_V1_REQUEST_MAPPING = "downloadId/{downloadId}"; - // constant class, private constructor. - private RestConstants() { + private MgmtRestConstants() { } } diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/api/RolloutRestApi.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/rest/api/MgmtRolloutRestApi.java similarity index 64% rename from hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/api/RolloutRestApi.java rename to hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/rest/api/MgmtRolloutRestApi.java index fe1c7caa5..7f93e2ce8 100644 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/api/RolloutRestApi.java +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/rest/api/MgmtRolloutRestApi.java @@ -6,15 +6,13 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource.api; +package org.eclipse.hawkbit.mgmt.rest.api; -import org.eclipse.hawkbit.rest.resource.RestConstants; -import org.eclipse.hawkbit.rest.resource.model.rollout.RolloutPagedList; -import org.eclipse.hawkbit.rest.resource.model.rollout.RolloutResponseBody; -import org.eclipse.hawkbit.rest.resource.model.rollout.RolloutRestRequestBody; -import org.eclipse.hawkbit.rest.resource.model.rolloutgroup.RolloutGroupPagedList; -import org.eclipse.hawkbit.rest.resource.model.rolloutgroup.RolloutGroupResponseBody; -import org.eclipse.hawkbit.rest.resource.model.target.TargetPagedList; +import org.eclipse.hawkbit.mgmt.json.model.PagedList; +import org.eclipse.hawkbit.mgmt.json.model.rollout.MgmtRolloutResponseBody; +import org.eclipse.hawkbit.mgmt.json.model.rollout.MgmtRolloutRestRequestBody; +import org.eclipse.hawkbit.mgmt.json.model.rolloutgroup.MgmtRolloutGroupResponseBody; +import org.eclipse.hawkbit.mgmt.json.model.target.MgmtTarget; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; @@ -27,8 +25,8 @@ import org.springframework.web.bind.annotation.RequestParam; * REST Resource handling rollout CRUD operations. * */ -@RequestMapping(RestConstants.ROLLOUT_V1_REQUEST_MAPPING) -public interface RolloutRestApi { +@RequestMapping(MgmtRestConstants.ROLLOUT_V1_REQUEST_MAPPING) +public interface MgmtRolloutRestApi { /** * Handles the GET request of retrieving all rollouts. @@ -50,11 +48,11 @@ public interface RolloutRestApi { * JsonResponseExceptionHandler is handling the response. */ @RequestMapping(method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE, "application/hal+json" }) - public ResponseEntity getRollouts( - @RequestParam(value = RestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = RestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = RestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam); + ResponseEntity> getRollouts( + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam); /** * Handles the GET request of retrieving a single rollout. @@ -62,12 +60,10 @@ public interface RolloutRestApi { * @param rolloutId * the ID of the rollout to retrieve * @return a single rollout with status OK. - * @throws EntityNotFoundException - * in case no rollout with the given {@code rolloutId} exists. */ @RequestMapping(value = "/{rolloutId}", method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE, "application/hal+json" }) - public ResponseEntity getRollout(@PathVariable("rolloutId") final Long rolloutId); + ResponseEntity getRollout(@PathVariable("rolloutId") final Long rolloutId); /** * Handles the POST request for creating rollout. @@ -78,11 +74,10 @@ public interface RolloutRestApi { * status code 201 with the successfully created rollout. In any * failure the JsonResponseExceptionHandler is handling the * response. - * @throws EntityNotFoundException */ @RequestMapping(method = RequestMethod.POST, consumes = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }, produces = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }) - public ResponseEntity create(@RequestBody final RolloutRestRequestBody rolloutRequestBody); + ResponseEntity create(@RequestBody final MgmtRolloutRestRequestBody rolloutRequestBody); /** * Handles the POST request for starting a rollout. @@ -91,14 +86,11 @@ public interface RolloutRestApi { * the ID of the rollout to be started. * @return OK response (200) if rollout could be started. In case of any * exception the corresponding errors occur. - * @throws EntityNotFoundException - * @see RolloutManagement#startRollout(Rollout) - * @see ResponseExceptionHandler */ @RequestMapping(method = RequestMethod.POST, value = "/{rolloutId}/start", produces = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }) - public ResponseEntity start(@PathVariable("rolloutId") final Long rolloutId, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_ASYNC, defaultValue = "false") final boolean startAsync); + ResponseEntity start(@PathVariable("rolloutId") final Long rolloutId, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_ASYNC, defaultValue = "false") final boolean startAsync); /** * Handles the POST request for pausing a rollout. @@ -107,13 +99,10 @@ public interface RolloutRestApi { * the ID of the rollout to be paused. * @return OK response (200) if rollout could be paused. In case of any * exception the corresponding errors occur. - * @throws EntityNotFoundException - * @see RolloutManagement#pauseRollout(Rollout) - * @see ResponseExceptionHandler */ @RequestMapping(method = RequestMethod.POST, value = "/{rolloutId}/pause", produces = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }) - public ResponseEntity pause(@PathVariable("rolloutId") final Long rolloutId); + ResponseEntity pause(@PathVariable("rolloutId") final Long rolloutId); /** * Handles the POST request for resuming a rollout. @@ -122,13 +111,10 @@ public interface RolloutRestApi { * the ID of the rollout to be resumed. * @return OK response (200) if rollout could be resumed. In case of any * exception the corresponding errors occur. - * @throws EntityNotFoundException - * @see RolloutManagement#resumeRollout(Rollout) - * @see ResponseExceptionHandler */ @RequestMapping(method = RequestMethod.POST, value = "/{rolloutId}/resume", produces = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }) - public ResponseEntity resume(@PathVariable("rolloutId") final Long rolloutId); + ResponseEntity resume(@PathVariable("rolloutId") final Long rolloutId); /** * Handles the GET request of retrieving all rollout groups referred to a @@ -154,11 +140,12 @@ public interface RolloutRestApi { */ @RequestMapping(method = RequestMethod.GET, value = "/{rolloutId}/deploygroups", produces = { MediaType.APPLICATION_JSON_VALUE, "application/hal+json" }) - public ResponseEntity getRolloutGroups(@PathVariable("rolloutId") final Long rolloutId, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = RestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = RestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam); + ResponseEntity> getRolloutGroups( + @PathVariable("rolloutId") final Long rolloutId, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam); /** * Handles the GET request for retrieving a single rollout group. @@ -167,12 +154,11 @@ public interface RolloutRestApi { * the rolloutId to retrieve the group from * @param groupId * the groupId to retrieve the rollout group - * @return the OK response containing the RolloutGroupResponseBody - * @throws EntityNotFoundException + * @return the OK response containing the MgmtRolloutGroupResponseBody */ @RequestMapping(method = RequestMethod.GET, value = "/{rolloutId}/deploygroups/{groupId}", produces = { MediaType.APPLICATION_JSON_VALUE, "application/hal+json" }) - public ResponseEntity getRolloutGroup(@PathVariable("rolloutId") final Long rolloutId, + ResponseEntity getRolloutGroup(@PathVariable("rolloutId") final Long rolloutId, @PathVariable("groupId") final Long groupId); /** @@ -200,10 +186,10 @@ public interface RolloutRestApi { */ @RequestMapping(method = RequestMethod.GET, value = "/{rolloutId}/deploygroups/{groupId}/targets", produces = { MediaType.APPLICATION_JSON_VALUE, "application/hal+json" }) - public ResponseEntity getRolloutGroupTargets(@PathVariable("rolloutId") final Long rolloutId, + ResponseEntity> getRolloutGroupTargets(@PathVariable("rolloutId") final Long rolloutId, @PathVariable("groupId") final Long groupId, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = RestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = RestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam); + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam); } diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/api/SoftwareModuleRestAPI.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/rest/api/MgmtSoftwareModuleRestApi.java similarity index 72% rename from hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/api/SoftwareModuleRestAPI.java rename to hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/rest/api/MgmtSoftwareModuleRestApi.java index 0662c43ba..cdd63ee26 100644 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/api/SoftwareModuleRestAPI.java +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/rest/api/MgmtSoftwareModuleRestApi.java @@ -6,20 +6,16 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource.api; +package org.eclipse.hawkbit.mgmt.rest.api; import java.util.List; -import org.eclipse.hawkbit.rest.resource.RestConstants; -import org.eclipse.hawkbit.rest.resource.model.MetadataRest; -import org.eclipse.hawkbit.rest.resource.model.MetadataRestPageList; -import org.eclipse.hawkbit.rest.resource.model.artifact.ArtifactRest; -import org.eclipse.hawkbit.rest.resource.model.artifact.ArtifactsRest; -import org.eclipse.hawkbit.rest.resource.model.softwaremodule.SoftwareModulePagedList; -import org.eclipse.hawkbit.rest.resource.model.softwaremodule.SoftwareModuleRequestBodyPost; -import org.eclipse.hawkbit.rest.resource.model.softwaremodule.SoftwareModuleRequestBodyPut; -import org.eclipse.hawkbit.rest.resource.model.softwaremodule.SoftwareModuleRest; -import org.eclipse.hawkbit.rest.resource.model.softwaremodule.SoftwareModulesRest; +import org.eclipse.hawkbit.mgmt.json.model.MgmtMetadata; +import org.eclipse.hawkbit.mgmt.json.model.PagedList; +import org.eclipse.hawkbit.mgmt.json.model.artifact.MgmtArtifact; +import org.eclipse.hawkbit.mgmt.json.model.softwaremodule.MgmtSoftwareModule; +import org.eclipse.hawkbit.mgmt.json.model.softwaremodule.MgmtSoftwareModuleRequestBodyPost; +import org.eclipse.hawkbit.mgmt.json.model.softwaremodule.MgmtSoftwareModuleRequestBodyPut; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; @@ -35,8 +31,8 @@ import org.springframework.web.multipart.MultipartFile; * operations. * */ -@RequestMapping(RestConstants.SOFTWAREMODULE_V1_REQUEST_MAPPING) -public interface SoftwareModuleRestAPI { +@RequestMapping(MgmtRestConstants.SOFTWAREMODULE_V1_REQUEST_MAPPING) +public interface MgmtSoftwareModuleRestApi { /** * Handles POST request for artifact upload. @@ -59,7 +55,7 @@ public interface SoftwareModuleRestAPI { */ @RequestMapping(method = RequestMethod.POST, value = "/{softwareModuleId}/artifacts", produces = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }) - public ResponseEntity uploadArtifact(@PathVariable("softwareModuleId") final Long softwareModuleId, + ResponseEntity uploadArtifact(@PathVariable("softwareModuleId") final Long softwareModuleId, @RequestParam("file") final MultipartFile file, @RequestParam(value = "filename", required = false) final String optionalFileName, @RequestParam(value = "md5sum", required = false) final String md5Sum, @@ -79,7 +75,7 @@ public interface SoftwareModuleRestAPI { @RequestMapping(method = RequestMethod.GET, value = "/{softwareModuleId}/artifacts", produces = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }) @ResponseBody - public ResponseEntity getArtifacts(@PathVariable("softwareModuleId") final Long softwareModuleId); + ResponseEntity> getArtifacts(@PathVariable("softwareModuleId") final Long softwareModuleId); /** * Handles the GET request of retrieving a single Artifact meta data @@ -95,7 +91,7 @@ public interface SoftwareModuleRestAPI { @RequestMapping(method = RequestMethod.GET, value = "/{softwareModuleId}/artifacts/{artifactId}", produces = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }) @ResponseBody - public ResponseEntity getArtifact(@PathVariable("softwareModuleId") final Long softwareModuleId, + ResponseEntity getArtifact(@PathVariable("softwareModuleId") final Long softwareModuleId, @PathVariable("artifactId") final Long artifactId); /** @@ -110,7 +106,7 @@ public interface SoftwareModuleRestAPI { */ @RequestMapping(method = RequestMethod.DELETE, value = "/{softwareModuleId}/artifacts/{artifactId}") @ResponseBody - public ResponseEntity deleteArtifact(@PathVariable("softwareModuleId") final Long softwareModuleId, + ResponseEntity deleteArtifact(@PathVariable("softwareModuleId") final Long softwareModuleId, @PathVariable("artifactId") final Long artifactId); /** @@ -134,11 +130,11 @@ public interface SoftwareModuleRestAPI { * JsonResponseExceptionHandler is handling the response. */ @RequestMapping(method = RequestMethod.GET, produces = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }) - public ResponseEntity getSoftwareModules( - @RequestParam(value = RestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = RestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = RestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam); + ResponseEntity> getSoftwareModules( + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam); /** * Handles the GET request of retrieving a single software module. @@ -147,13 +143,10 @@ public interface SoftwareModuleRestAPI { * the ID of the module to retrieve * * @return a single softwareModule with status OK. - * @throws EntityNotFoundException - * in case no with the given {@code softwareModuleId} exists. */ @RequestMapping(method = RequestMethod.GET, value = "/{softwareModuleId}", produces = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }) - public ResponseEntity getSoftwareModule( - @PathVariable("softwareModuleId") final Long softwareModuleId); + ResponseEntity getSoftwareModule(@PathVariable("softwareModuleId") final Long softwareModuleId); /** * Handles the POST request of creating new softwaremodules. The request @@ -168,8 +161,8 @@ public interface SoftwareModuleRestAPI { */ @RequestMapping(method = RequestMethod.POST, consumes = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }, produces = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }) - public ResponseEntity createSoftwareModules( - @RequestBody final List softwareModules); + ResponseEntity> createSoftwareModules( + @RequestBody final List softwareModules); /** * Handles the PUT request of updating a software module. @@ -182,12 +175,12 @@ public interface SoftwareModuleRestAPI { */ @RequestMapping(method = RequestMethod.PUT, value = "/{softwareModuleId}", consumes = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }, produces = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }) - public ResponseEntity updateSoftwareModule( + ResponseEntity updateSoftwareModule( @PathVariable("softwareModuleId") final Long softwareModuleId, - @RequestBody final SoftwareModuleRequestBodyPut restSoftwareModule); + @RequestBody final MgmtSoftwareModuleRequestBodyPut restSoftwareModule); /** - * Handles the DELETE request for a single softwaremodule. + * Handles the DELETE request for a single software module. * * @param softwareModuleId * the ID of the module to retrieve @@ -195,7 +188,7 @@ public interface SoftwareModuleRestAPI { * */ @RequestMapping(method = RequestMethod.DELETE, value = "/{softwareModuleId}") - public ResponseEntity deleteSoftwareModule(@PathVariable("softwareModuleId") final Long softwareModuleId); + ResponseEntity deleteSoftwareModule(@PathVariable("softwareModuleId") final Long softwareModuleId); /** * Gets a paged list of meta data for a software module. @@ -219,12 +212,11 @@ public interface SoftwareModuleRestAPI { */ @RequestMapping(method = RequestMethod.GET, value = "/{softwareModuleId}/metadata", produces = { MediaType.APPLICATION_JSON_VALUE, "application/hal+json" }) - public ResponseEntity getMetadata( - @PathVariable("softwareModuleId") final Long softwareModuleId, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = RestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = RestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam); + ResponseEntity> getMetadata(@PathVariable("softwareModuleId") final Long softwareModuleId, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam); /** * Gets a single meta data value for a specific key of a software module. @@ -238,7 +230,7 @@ public interface SoftwareModuleRestAPI { */ @RequestMapping(method = RequestMethod.GET, value = "/{softwareModuleId}/metadata/{metadataKey}", produces = { MediaType.APPLICATION_JSON_VALUE }) - public ResponseEntity getMetadataValue(@PathVariable("softwareModuleId") final Long softwareModuleId, + ResponseEntity getMetadataValue(@PathVariable("softwareModuleId") final Long softwareModuleId, @PathVariable("metadataKey") final String metadataKey); /** @@ -253,8 +245,8 @@ public interface SoftwareModuleRestAPI { */ @RequestMapping(method = RequestMethod.PUT, value = "/{softwareModuleId}/metadata/{metadataKey}", produces = { MediaType.APPLICATION_JSON_VALUE, "application/hal+json" }) - public ResponseEntity updateMetadata(@PathVariable("softwareModuleId") final Long softwareModuleId, - @PathVariable("metadataKey") final String metadataKey, @RequestBody final MetadataRest metadata); + ResponseEntity updateMetadata(@PathVariable("softwareModuleId") final Long softwareModuleId, + @PathVariable("metadataKey") final String metadataKey, @RequestBody final MgmtMetadata metadata); /** * Deletes a single meta data entry from the software module. @@ -266,7 +258,7 @@ public interface SoftwareModuleRestAPI { * @return status OK if the delete request is successful */ @RequestMapping(method = RequestMethod.DELETE, value = "/{softwareModuleId}/metadata/{metadataKey}") - public ResponseEntity deleteMetadata(@PathVariable("softwareModuleId") final Long softwareModuleId, + ResponseEntity deleteMetadata(@PathVariable("softwareModuleId") final Long softwareModuleId, @PathVariable("metadataKey") final String metadataKey); /** @@ -282,8 +274,7 @@ public interface SoftwareModuleRestAPI { @RequestMapping(method = RequestMethod.POST, value = "/{softwareModuleId}/metadata", consumes = { MediaType.APPLICATION_JSON_VALUE, "application/hal+json" }, produces = { MediaType.APPLICATION_JSON_VALUE, "application/hal+json" }) - public ResponseEntity> createMetadata( - @PathVariable("softwareModuleId") final Long softwareModuleId, - @RequestBody final List metadataRest); + ResponseEntity> createMetadata(@PathVariable("softwareModuleId") final Long softwareModuleId, + @RequestBody final List metadataRest); } diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/api/SoftwareModuleTypeRestApi.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/rest/api/MgmtSoftwareModuleTypeRestApi.java similarity index 68% rename from hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/api/SoftwareModuleTypeRestApi.java rename to hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/rest/api/MgmtSoftwareModuleTypeRestApi.java index 0c4756a04..3fe32d9ad 100644 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/api/SoftwareModuleTypeRestApi.java +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/rest/api/MgmtSoftwareModuleTypeRestApi.java @@ -6,16 +6,14 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource.api; +package org.eclipse.hawkbit.mgmt.rest.api; import java.util.List; -import org.eclipse.hawkbit.rest.resource.RestConstants; -import org.eclipse.hawkbit.rest.resource.model.softwaremoduletype.SoftwareModuleTypePagedList; -import org.eclipse.hawkbit.rest.resource.model.softwaremoduletype.SoftwareModuleTypeRequestBodyPost; -import org.eclipse.hawkbit.rest.resource.model.softwaremoduletype.SoftwareModuleTypeRequestBodyPut; -import org.eclipse.hawkbit.rest.resource.model.softwaremoduletype.SoftwareModuleTypeRest; -import org.eclipse.hawkbit.rest.resource.model.softwaremoduletype.SoftwareModuleTypesRest; +import org.eclipse.hawkbit.mgmt.json.model.PagedList; +import org.eclipse.hawkbit.mgmt.json.model.softwaremoduletype.MgmtSoftwareModuleType; +import org.eclipse.hawkbit.mgmt.json.model.softwaremoduletype.MgmtSoftwareModuleTypeRequestBodyPost; +import org.eclipse.hawkbit.mgmt.json.model.softwaremoduletype.MgmtSoftwareModuleTypeRequestBodyPut; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; @@ -29,8 +27,8 @@ import org.springframework.web.bind.annotation.RequestParam; * operations. * */ -@RequestMapping(RestConstants.SOFTWAREMODULETYPE_V1_REQUEST_MAPPING) -public interface SoftwareModuleTypeRestApi { +@RequestMapping(MgmtRestConstants.SOFTWAREMODULETYPE_V1_REQUEST_MAPPING) +public interface MgmtSoftwareModuleTypeRestApi { /** * Handles the GET request of retrieving all SoftwareModuleTypes . * @@ -52,11 +50,11 @@ public interface SoftwareModuleTypeRestApi { * JsonResponseExceptionHandler is handling the response. */ @RequestMapping(method = RequestMethod.GET, produces = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }) - public ResponseEntity getTypes( - @RequestParam(value = RestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = RestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = RestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam); + ResponseEntity> getTypes( + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam); /** * Handles the GET request of retrieving a single software module type . @@ -65,12 +63,10 @@ public interface SoftwareModuleTypeRestApi { * the ID of the module type to retrieve * * @return a single softwareModule with status OK. - * @throws EntityNotFoundException - * in case no with the given {@code softwareModuleId} exists. */ @RequestMapping(method = RequestMethod.GET, value = "/{softwareModuleTypeId}", produces = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }) - public ResponseEntity getSoftwareModuleType( + ResponseEntity getSoftwareModuleType( @PathVariable("softwareModuleTypeId") final Long softwareModuleTypeId); /** @@ -82,7 +78,7 @@ public interface SoftwareModuleTypeRestApi { * */ @RequestMapping(method = RequestMethod.DELETE, value = "/{softwareModuleTypeId}") - public ResponseEntity deleteSoftwareModuleType( + ResponseEntity deleteSoftwareModuleType( @PathVariable("softwareModuleTypeId") final Long softwareModuleTypeId); /** @@ -96,9 +92,9 @@ public interface SoftwareModuleTypeRestApi { */ @RequestMapping(method = RequestMethod.PUT, value = "/{softwareModuleTypeId}", consumes = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }, produces = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }) - public ResponseEntity updateSoftwareModuleType( + ResponseEntity updateSoftwareModuleType( @PathVariable("softwareModuleTypeId") final Long softwareModuleTypeId, - @RequestBody final SoftwareModuleTypeRequestBodyPut restSoftwareModuleType); + @RequestBody final MgmtSoftwareModuleTypeRequestBodyPut restSoftwareModuleType); /** * Handles the POST request of creating new SoftwareModuleTypes. The request @@ -113,7 +109,7 @@ public interface SoftwareModuleTypeRestApi { */ @RequestMapping(method = RequestMethod.POST, consumes = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }, produces = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }) - public ResponseEntity createSoftwareModuleTypes( - @RequestBody final List softwareModuleTypes); + ResponseEntity> createSoftwareModuleTypes( + @RequestBody final List softwareModuleTypes); } diff --git a/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/rest/api/MgmtSystemManagementRestApi.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/rest/api/MgmtSystemManagementRestApi.java new file mode 100644 index 000000000..d4832aa7d --- /dev/null +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/rest/api/MgmtSystemManagementRestApi.java @@ -0,0 +1,64 @@ +/** + * 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.mgmt.rest.api; + +import java.util.Collection; + +import org.eclipse.hawkbit.mgmt.json.model.systemmanagement.MgmtSystemCache; +import org.eclipse.hawkbit.mgmt.json.model.systemmanagement.MgmtSystemStatisticsRest; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +/** + * System management capabilities by REST. + * + */ +@RequestMapping(MgmtRestConstants.SYSTEM_ADMIN_MAPPING) +public interface MgmtSystemManagementRestApi { + + /** + * Deletes the tenant data of a given tenant. USE WITH CARE! + * + * @param tenant + * to delete + * @return HttpStatus.OK + */ + @RequestMapping(method = RequestMethod.DELETE, value = "/tenants/{tenant}") + ResponseEntity deleteTenant(@PathVariable("tenant") final String tenant); + + /** + * Collects and returns system usage statistics. It provides a system wide + * overview and tenant based stats. + * + * @return system usage statistics + */ + @RequestMapping(method = RequestMethod.GET, value = "/usage", produces = { "application/hal+json", + MediaType.APPLICATION_JSON_VALUE }) + ResponseEntity getSystemUsageStats(); + + /** + * Returns a list of all caches. + * + * @return a list of caches for all tenants + */ + @RequestMapping(method = RequestMethod.GET, value = "/caches") + ResponseEntity> getCaches(); + + /** + * Invalidates all caches for all tenants. + * + * @return a list of cache names which has been invalidated + */ + @RequestMapping(method = RequestMethod.DELETE, value = "/caches") + ResponseEntity> invalidateCaches(); + +} diff --git a/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/rest/api/MgmtSystemRestApi.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/rest/api/MgmtSystemRestApi.java new file mode 100644 index 000000000..d120759b2 --- /dev/null +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/rest/api/MgmtSystemRestApi.java @@ -0,0 +1,88 @@ +/** + * 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.mgmt.rest.api; + +import java.util.Map; + +import org.eclipse.hawkbit.mgmt.json.model.system.MgmtSystemTenantConfigurationValue; +import org.eclipse.hawkbit.mgmt.json.model.system.MgmtSystemTenantConfigurationValueRequest; +import org.springframework.hateoas.ResourceSupport; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +/** + * REST Resource handling tenant specific configuration operations. + * + * + */ +@RequestMapping(MgmtRestConstants.SYSTEM_V1_REQUEST_MAPPING) +public interface MgmtSystemRestApi { + + @RequestMapping(method = RequestMethod.GET, produces = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }) + ResponseEntity getSystem(); + + /** + * @return a Map of all configuration values. + */ + @RequestMapping(method = RequestMethod.GET, value = "/configs", produces = { "application/hal+json", + MediaType.APPLICATION_JSON_VALUE }) + ResponseEntity> getSystemConfiguration(); + + /** + * Handles the DELETE request of deleting a tenant specific configuration + * value within SP. + * + * @param keyName + * the Name of the configuration key + * @return If the given configuration value exists and could be deleted Http + * OK. In any failure the JsonResponseExceptionHandler is handling + * the response. + */ + @RequestMapping(method = RequestMethod.DELETE, value = "/configs/{keyName}", produces = { "application/hal+json", + MediaType.APPLICATION_JSON_VALUE }) + ResponseEntity deleteConfigurationValue(@PathVariable("keyName") final String keyName); + + /** + * Handles the GET request of deleting a tenant specific configuration value + * within SP. + * + * @param keyName + * the Name of the configuration key + * @return If the given configuration value exists and could be get Http OK. + * In any failure the JsonResponseExceptionHandler is handling the + * response. + */ + @RequestMapping(method = RequestMethod.GET, value = "/configs/{keyName}", produces = { "application/hal+json", + MediaType.APPLICATION_JSON_VALUE }) + ResponseEntity getConfigurationValue( + @PathVariable("keyName") final String keyName); + + /** + * Handles the GET request of deleting a tenant specific configuration value + * within SP. + * + * @param keyName + * the Name of the configuration key + * @param configurationValueRest + * the new value for the configuration + * @return If the given configuration value exists and could be get Http OK. + * In any failure the JsonResponseExceptionHandler is handling the + * response. + */ + @RequestMapping(method = RequestMethod.PUT, value = "/configs/{keyName}", consumes = { "application/hal+json", + MediaType.APPLICATION_JSON_VALUE }, produces = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }) + ResponseEntity updateConfigurationValue( + @PathVariable("keyName") final String keyName, + @RequestBody final MgmtSystemTenantConfigurationValueRequest configurationValueRest); + +} diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/api/TargetRestApi.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/rest/api/MgmtTargetRestApi.java similarity index 67% rename from hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/api/TargetRestApi.java rename to hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/rest/api/MgmtTargetRestApi.java index 9d63a520f..bf4e169a0 100644 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/api/TargetRestApi.java +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/rest/api/MgmtTargetRestApi.java @@ -6,21 +6,18 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource.api; +package org.eclipse.hawkbit.mgmt.rest.api; import java.util.List; -import org.eclipse.hawkbit.rest.resource.RestConstants; -import org.eclipse.hawkbit.rest.resource.model.action.ActionPagedList; -import org.eclipse.hawkbit.rest.resource.model.action.ActionRest; -import org.eclipse.hawkbit.rest.resource.model.action.ActionStatusPagedList; -import org.eclipse.hawkbit.rest.resource.model.distributionset.DistributionSetRest; -import org.eclipse.hawkbit.rest.resource.model.target.DistributionSetAssigmentRest; -import org.eclipse.hawkbit.rest.resource.model.target.TargetAttributes; -import org.eclipse.hawkbit.rest.resource.model.target.TargetPagedList; -import org.eclipse.hawkbit.rest.resource.model.target.TargetRequestBody; -import org.eclipse.hawkbit.rest.resource.model.target.TargetRest; -import org.eclipse.hawkbit.rest.resource.model.target.TargetsRest; +import org.eclipse.hawkbit.mgmt.json.model.PagedList; +import org.eclipse.hawkbit.mgmt.json.model.action.MgmtAction; +import org.eclipse.hawkbit.mgmt.json.model.action.MgmtActionStatus; +import org.eclipse.hawkbit.mgmt.json.model.distributionset.MgmtDistributionSet; +import org.eclipse.hawkbit.mgmt.json.model.target.MgmtDistributionSetAssigment; +import org.eclipse.hawkbit.mgmt.json.model.target.MgmtTarget; +import org.eclipse.hawkbit.mgmt.json.model.target.MgmtTargetAttributes; +import org.eclipse.hawkbit.mgmt.json.model.target.MgmtTargetRequestBody; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; @@ -32,8 +29,8 @@ import org.springframework.web.bind.annotation.RequestParam; /** * Api for handling target operations. */ -@RequestMapping(RestConstants.TARGET_V1_REQUEST_MAPPING) -public interface TargetRestApi { +@RequestMapping(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING) +public interface MgmtTargetRestApi { /** * Handles the GET request of retrieving a single target. @@ -41,13 +38,11 @@ public interface TargetRestApi { * @param targetId * the ID of the target to retrieve * @return a single target with status OK. - * @throws EntityNotFoundException - * in case no target with the given {@code targetId} exists. */ @RequestMapping(method = RequestMethod.GET, value = "/{targetId}", produces = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }) - public ResponseEntity getTarget(@PathVariable("targetId") final String targetId); + ResponseEntity getTarget(@PathVariable("targetId") final String targetId); /** * Handles the GET request of retrieving all targets. @@ -70,11 +65,11 @@ public interface TargetRestApi { */ @RequestMapping(method = RequestMethod.GET, produces = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }) - public ResponseEntity getTargets( - @RequestParam(value = RestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = RestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = RestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam); + ResponseEntity> getTargets( + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam); /** * Handles the POST request of creating new targets. The request body must @@ -89,7 +84,7 @@ public interface TargetRestApi { */ @RequestMapping(method = RequestMethod.POST, consumes = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }, produces = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }) - public ResponseEntity createTargets(@RequestBody final List targets); + ResponseEntity> createTargets(@RequestBody final List targets); /** * Handles the PUT request of updating a target. The ID is within the URL @@ -107,8 +102,8 @@ public interface TargetRestApi { */ @RequestMapping(method = RequestMethod.PUT, value = "/{targetId}", consumes = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }, produces = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }) - public ResponseEntity updateTarget(@PathVariable("targetId") final String targetId, - @RequestBody final TargetRequestBody targetRest); + ResponseEntity updateTarget(@PathVariable("targetId") final String targetId, + @RequestBody final MgmtTargetRequestBody targetRest); /** * Handles the DELETE request of deleting a target. @@ -121,7 +116,7 @@ public interface TargetRestApi { */ @RequestMapping(method = RequestMethod.DELETE, value = "/{targetId}", produces = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }) - public ResponseEntity deleteTarget(@PathVariable("targetId") final String targetId); + ResponseEntity deleteTarget(@PathVariable("targetId") final String targetId); /** * Handles the GET request of retrieving the attributes of a specific @@ -130,12 +125,10 @@ public interface TargetRestApi { * @param targetId * the ID of the target to retrieve the attributes. * @return the target attributes as map response with status OK - * @throws EntityNotFoundException - * in case no target with the given {@code targetId} exists. */ @RequestMapping(method = RequestMethod.GET, value = "/{targetId}/attributes", produces = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }) - public ResponseEntity getAttributes(@PathVariable("targetId") final String targetId); + ResponseEntity getAttributes(@PathVariable("targetId") final String targetId); /** * Handles the GET request of retrieving the Actions of a specific target. @@ -160,11 +153,11 @@ public interface TargetRestApi { */ @RequestMapping(method = RequestMethod.GET, value = "/{targetId}/actions", produces = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }) - public ResponseEntity getActionHistory(@PathVariable("targetId") final String targetId, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = RestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = RestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam); + ResponseEntity> getActionHistory(@PathVariable("targetId") final String targetId, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam); /** * Handles the GET request of retrieving a specific Actions of a specific @@ -178,7 +171,7 @@ public interface TargetRestApi { */ @RequestMapping(method = RequestMethod.GET, value = "/{targetId}/actions/{actionId}", produces = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }) - public ResponseEntity getAction(@PathVariable("targetId") final String targetId, + ResponseEntity getAction(@PathVariable("targetId") final String targetId, @PathVariable("actionId") final Long actionId); /** @@ -192,13 +185,9 @@ public interface TargetRestApi { * @param force * optional parameter, which indicates a force cancel * @return status no content in case cancellation was successful - * @throws CancelActionNotAllowedException - * if the given action is not active and cannot be canceled. - * @throws EntityNotFoundException - * if the target or the action is not found */ @RequestMapping(method = RequestMethod.DELETE, value = "/{targetId}/actions/{actionId}") - public ResponseEntity cancelAction(@PathVariable("targetId") final String targetId, + ResponseEntity cancelAction(@PathVariable("targetId") final String targetId, @PathVariable("actionId") final Long actionId, @RequestParam(value = "force", required = false, defaultValue = "false") final boolean force); @@ -225,11 +214,11 @@ public interface TargetRestApi { */ @RequestMapping(method = RequestMethod.GET, value = "/{targetId}/actions/{actionId}/status", produces = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }) - public ResponseEntity getActionStatusList(@PathVariable("targetId") final String targetId, + ResponseEntity> getActionStatusList(@PathVariable("targetId") final String targetId, @PathVariable("actionId") final Long actionId, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = RestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = RestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam); + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam); /** * Handles the GET request of retrieving the assigned distribution set of an @@ -239,13 +228,10 @@ public interface TargetRestApi { * the ID of the target to retrieve the assigned distribution * @return the assigned distribution set with status OK, if none is assigned * than {@code null} content (e.g. "{}") - * @throws EntityNotFoundException - * in case no target with the given {@code targetId} exists. */ @RequestMapping(method = RequestMethod.GET, value = "/{targetId}/assignedDS", produces = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }) - public ResponseEntity getAssignedDistributionSet( - @PathVariable("targetId") final String targetId); + ResponseEntity getAssignedDistributionSet(@PathVariable("targetId") final String targetId); /** * Changes the assigned distribution set of a target. @@ -255,15 +241,11 @@ public interface TargetRestApi { * @param dsId * of the distributionset that is to be assigned * @return http status - * - * @throws EntityNotFoundException - * in case no target with the given {@code targetId} exists. - * */ @RequestMapping(method = RequestMethod.POST, value = "/{targetId}/assignedDS", consumes = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }, produces = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }) - public ResponseEntity postAssignedDistributionSet(@PathVariable("targetId") final String targetId, - @RequestBody final DistributionSetAssigmentRest dsId); + ResponseEntity postAssignedDistributionSet(@PathVariable("targetId") final String targetId, + @RequestBody final MgmtDistributionSetAssigment dsId); /** * Handles the GET request of retrieving the installed distribution set of @@ -273,12 +255,9 @@ public interface TargetRestApi { * the ID of the target to retrieve * @return the assigned installed set with status OK, if none is installed * than {@code null} content (e.g. "{}") - * @throws EntityNotFoundException - * in case no target with the given {@code targetId} exists. */ @RequestMapping(method = RequestMethod.GET, value = "/{targetId}/installedDS", produces = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }) - public ResponseEntity getInstalledDistributionSet( - @PathVariable("targetId") final String targetId); + ResponseEntity getInstalledDistributionSet(@PathVariable("targetId") final String targetId); -} \ No newline at end of file +} diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/api/TargetTagRestApi.java b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/rest/api/MgmtTargetTagRestApi.java similarity index 58% rename from hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/api/TargetTagRestApi.java rename to hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/rest/api/MgmtTargetTagRestApi.java index 59770db08..e568e7377 100644 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/api/TargetTagRestApi.java +++ b/hawkbit-mgmt-api/src/main/java/org/eclipse/hawkbit/mgmt/rest/api/MgmtTargetTagRestApi.java @@ -6,18 +6,16 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource.api; +package org.eclipse.hawkbit.mgmt.rest.api; import java.util.List; -import org.eclipse.hawkbit.rest.resource.RestConstants; -import org.eclipse.hawkbit.rest.resource.model.tag.AssignedTargetRequestBody; -import org.eclipse.hawkbit.rest.resource.model.tag.TagPagedList; -import org.eclipse.hawkbit.rest.resource.model.tag.TagRequestBodyPut; -import org.eclipse.hawkbit.rest.resource.model.tag.TagRest; -import org.eclipse.hawkbit.rest.resource.model.tag.TagsRest; -import org.eclipse.hawkbit.rest.resource.model.tag.TargetTagAssigmentResultRest; -import org.eclipse.hawkbit.rest.resource.model.target.TargetsRest; +import org.eclipse.hawkbit.mgmt.json.model.PagedList; +import org.eclipse.hawkbit.mgmt.json.model.tag.MgmtAssignedTargetRequestBody; +import org.eclipse.hawkbit.mgmt.json.model.tag.MgmtTag; +import org.eclipse.hawkbit.mgmt.json.model.tag.MgmtTagRequestBodyPut; +import org.eclipse.hawkbit.mgmt.json.model.tag.MgmtTargetTagAssigmentResult; +import org.eclipse.hawkbit.mgmt.json.model.target.MgmtTarget; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; @@ -30,8 +28,8 @@ import org.springframework.web.bind.annotation.RequestParam; * REST Resource handling for TargetTag CRUD operations. * */ -@RequestMapping(RestConstants.TARGET_TAG_V1_REQUEST_MAPPING) -public interface TargetTagRestApi { +@RequestMapping(MgmtRestConstants.TARGET_TAG_V1_REQUEST_MAPPING) +public interface MgmtTargetTagRestApi { /** * Handles the GET request of retrieving all target tags. @@ -53,11 +51,11 @@ public interface TargetTagRestApi { * JsonResponseExceptionHandler is handling the response. */ @RequestMapping(method = RequestMethod.GET, produces = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }) - public ResponseEntity getTargetTags( - @RequestParam(value = RestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = RestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = RestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam); + ResponseEntity> getTargetTags( + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam); /** * Handles the GET request of retrieving a single target tag. @@ -66,12 +64,10 @@ public interface TargetTagRestApi { * the ID of the target tag to retrieve * * @return a single target tag with status OK. - * @throws EntityNotFoundException - * in case the given {@code targetTagId} doesn't exists. */ @RequestMapping(method = RequestMethod.GET, value = "/{targetTagId}", produces = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }) - public ResponseEntity getTargetTag(@PathVariable("targetTagId") final Long targetTagId); + ResponseEntity getTargetTag(@PathVariable("targetTagId") final Long targetTagId); /** * Handles the POST request of creating new target tag. The request body @@ -85,7 +81,7 @@ public interface TargetTagRestApi { */ @RequestMapping(method = RequestMethod.POST, consumes = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }, produces = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }) - public ResponseEntity createTargetTags(@RequestBody final List tags); + ResponseEntity> createTargetTags(@RequestBody final List tags); /** * @@ -96,13 +92,11 @@ public interface TargetTagRestApi { * @param restTargetTagRest * the the request body to be updated * @return status OK if update is successful and the updated target tag. - * @throws EntityNotFoundException - * in case the given {@code targetTagId} doesn't exists. */ @RequestMapping(method = RequestMethod.PUT, value = "/{targetTagId}", consumes = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }, produces = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }) - public ResponseEntity updateTagretTag(@PathVariable("targetTagId") final Long targetTagId, - @RequestBody final TagRequestBodyPut restTargetTagRest); + ResponseEntity updateTagretTag(@PathVariable("targetTagId") final Long targetTagId, + @RequestBody final MgmtTagRequestBodyPut restTargetTagRest); /** * Handles the DELETE request for a single target tag. @@ -110,12 +104,10 @@ public interface TargetTagRestApi { * @param targetTagId * the ID of the target tag * @return status OK if delete as successfully. - * @throws EntityNotFoundException - * in case the given {@code targetTagId} doesn't exists. * */ @RequestMapping(method = RequestMethod.DELETE, value = "/{targetTagId}") - public ResponseEntity deleteTargetTag(@PathVariable("targetTagId") final Long targetTagId); + ResponseEntity deleteTargetTag(@PathVariable("targetTagId") final Long targetTagId); /** * Handles the GET request of retrieving all assigned targets by the given @@ -125,11 +117,9 @@ public interface TargetTagRestApi { * the ID of the target tag to retrieve * * @return the list of assigned targets. - * @throws EntityNotFoundException - * in case the given {@code targetTagId} doesn't exists. */ - @RequestMapping(method = RequestMethod.GET, value = RestConstants.TARGET_TAG_TAGERTS_REQUEST_MAPPING) - public ResponseEntity getAssignedTargets(@PathVariable("targetTagId") final Long targetTagId); + @RequestMapping(method = RequestMethod.GET, value = MgmtRestConstants.TARGET_TAG_TAGERTS_REQUEST_MAPPING) + ResponseEntity> getAssignedTargets(@PathVariable("targetTagId") final Long targetTagId); /** * Handles the POST request to toggle the assignment of targets by the given @@ -141,14 +131,12 @@ public interface TargetTagRestApi { * list of target ids to be toggled * * @return the list of assigned targets and unassigned targets. - * @throws EntityNotFoundException - * in case the given {@code targetTagId} doesn't exists. */ - @RequestMapping(method = RequestMethod.POST, value = RestConstants.TARGET_TAG_TAGERTS_REQUEST_MAPPING + @RequestMapping(method = RequestMethod.POST, value = MgmtRestConstants.TARGET_TAG_TAGERTS_REQUEST_MAPPING + "/toggleTagAssignment") - public ResponseEntity toggleTagAssignment( + ResponseEntity toggleTagAssignment( @PathVariable("targetTagId") final Long targetTagId, - @RequestBody final List assignedTargetRequestBodies); + @RequestBody final List assignedTargetRequestBodies); /** * Handles the POST request to assign targets to the given tag id. @@ -159,12 +147,10 @@ public interface TargetTagRestApi { * list of target ids to be assigned * * @return the list of assigned targets. - * @throws EntityNotFoundException - * in case the given {@code targetTagId} doesn't exists. */ - @RequestMapping(method = RequestMethod.POST, value = RestConstants.TARGET_TAG_TAGERTS_REQUEST_MAPPING) - public ResponseEntity assignTargets(@PathVariable("targetTagId") final Long targetTagId, - @RequestBody final List assignedTargetRequestBodies); + @RequestMapping(method = RequestMethod.POST, value = MgmtRestConstants.TARGET_TAG_TAGERTS_REQUEST_MAPPING) + ResponseEntity> assignTargets(@PathVariable("targetTagId") final Long targetTagId, + @RequestBody final List assignedTargetRequestBodies); /** * Handles the DELETE request to unassign all targets from the given tag id. @@ -172,11 +158,9 @@ public interface TargetTagRestApi { * @param targetTagId * the ID of the target tag to retrieve * @return http status code - * @throws EntityNotFoundException - * in case the given {@code targetTagId} doesn't exists. */ - @RequestMapping(method = RequestMethod.DELETE, value = RestConstants.TARGET_TAG_TAGERTS_REQUEST_MAPPING) - public ResponseEntity unassignTargets(@PathVariable("targetTagId") final Long targetTagId); + @RequestMapping(method = RequestMethod.DELETE, value = MgmtRestConstants.TARGET_TAG_TAGERTS_REQUEST_MAPPING) + ResponseEntity unassignTargets(@PathVariable("targetTagId") final Long targetTagId); /** * Handles the DELETE request to unassign one target from the given tag id. @@ -186,11 +170,9 @@ public interface TargetTagRestApi { * @param controllerId * the ID of the target to unassign * @return http status code - * @throws EntityNotFoundException - * in case the given {@code targetTagId} doesn't exists. */ - @RequestMapping(method = RequestMethod.DELETE, value = RestConstants.TARGET_TAG_TAGERTS_REQUEST_MAPPING + @RequestMapping(method = RequestMethod.DELETE, value = MgmtRestConstants.TARGET_TAG_TAGERTS_REQUEST_MAPPING + "/{controllerId}") - public ResponseEntity unassignTarget(@PathVariable("targetTagId") final Long targetTagId, + ResponseEntity unassignTarget(@PathVariable("targetTagId") final Long targetTagId, @PathVariable("controllerId") final String controllerId); } diff --git a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/model/PagedListTest.java b/hawkbit-mgmt-api/src/test/java/org/eclipse/hawkbit/mgmt/json/model/PagedListTest.java similarity index 89% rename from hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/model/PagedListTest.java rename to hawkbit-mgmt-api/src/test/java/org/eclipse/hawkbit/mgmt/json/model/PagedListTest.java index 49e13c0b4..c17acb3b1 100644 --- a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/model/PagedListTest.java +++ b/hawkbit-mgmt-api/src/test/java/org/eclipse/hawkbit/mgmt/json/model/PagedListTest.java @@ -6,9 +6,10 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource.model; +package org.eclipse.hawkbit.mgmt.json.model; import static org.fest.assertions.Assertions.assertThat; +import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.List; @@ -23,10 +24,14 @@ import ru.yandex.qatools.allure.annotations.Stories; @Stories("Paged List Handling") public class PagedListTest { - @Test(expected = NullPointerException.class) + @Test @Description("Ensures that a null payload entitiy throws an exception.") public void createListWithNullContentThrowsException() { - new PagedList<>(null, 0); + try { + new PagedList<>(null, 0); + fail("as content is null"); + } catch (final NullPointerException e) { + } } @Test diff --git a/hawkbit-mgmt-resource/README.md b/hawkbit-mgmt-resource/README.md new file mode 100644 index 000000000..3bad53d61 --- /dev/null +++ b/hawkbit-mgmt-resource/README.md @@ -0,0 +1,13 @@ +# Eclipse.IoT hawkBit - Mgmt Resource + +This is the server-side implementation of the hawkBit Mgmt API that is used to manage and monitor the HawkBit Update Server via HTTP. + +# Compile + +#### Build hawkbit-mgmt-resource + +``` +$ cd hawkbit/hawkbit-mgmt-resource +$ mvn clean install +``` + diff --git a/hawkbit-rest-resource/pom.xml b/hawkbit-mgmt-resource/pom.xml similarity index 81% rename from hawkbit-rest-resource/pom.xml rename to hawkbit-mgmt-resource/pom.xml index 633a1f8cc..160299651 100644 --- a/hawkbit-rest-resource/pom.xml +++ b/hawkbit-mgmt-resource/pom.xml @@ -16,8 +16,8 @@ hawkbit-parent 0.2.0-SNAPSHOT - hawkbit-rest-resource - hawkBit :: REST Resources + hawkbit-mgmt-resource + hawkBit :: REST Mgmt Resources @@ -28,23 +28,13 @@ org.eclipse.hawkbit - hawkbit-rest-api + hawkbit-mgmt-api ${project.version} - javax.servlet - javax.servlet-api - provided - - - org.apache.tomcat.embed - tomcat-embed-core - provided - - - io.springfox - springfox-core - 2.0.3 + org.eclipse.hawkbit + hawkbit-rest-core + ${project.version} commons-io @@ -52,11 +42,18 @@ 2.4 - org.springframework.security - spring-security-web + org.springframework.plugin + spring-plugin-core + + org.eclipse.hawkbit + hawkbit-rest-core + ${project.version} + tests + test + org.springframework.boot spring-boot-starter @@ -156,25 +153,10 @@ allure-junit-adaptor test - + org.springframework spring-context-support test - + - - - - org.apache.maven.plugins - maven-jar-plugin - - - - test-jar - - - - - - \ No newline at end of file diff --git a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/EnableRestResources.java b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/EnableMgmtApi.java similarity index 81% rename from hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/EnableRestResources.java rename to hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/EnableMgmtApi.java index 8f9952054..6d4252e55 100644 --- a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/EnableRestResources.java +++ b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/EnableMgmtApi.java @@ -6,29 +6,29 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource; +package org.eclipse.hawkbit.mgmt; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import org.eclipse.hawkbit.rest.configuration.RestConfiguration; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; import org.springframework.stereotype.Controller; /** * Annotation to enable {@link ComponentScan} in the resource package to setup * all {@link Controller} annotated classes and setup the REST-Resources for the * Management API. - * - * - * */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Configuration @ComponentScan -public @interface EnableRestResources { +@Import(RestConfiguration.class) +public @interface EnableMgmtApi { } diff --git a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/DistributionSetMapper.java b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetMapper.java similarity index 70% rename from hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/DistributionSetMapper.java rename to hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetMapper.java index 9ae133dd5..6d2d890b2 100644 --- a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/DistributionSetMapper.java +++ b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetMapper.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource; +package org.eclipse.hawkbit.mgmt.rest.resource; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; @@ -14,6 +14,13 @@ import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; import java.util.ArrayList; import java.util.List; +import org.eclipse.hawkbit.mgmt.json.model.MgmtMetadata; +import org.eclipse.hawkbit.mgmt.json.model.distributionset.MgmtDistributionSet; +import org.eclipse.hawkbit.mgmt.json.model.distributionset.MgmtDistributionSetRequestBodyPost; +import org.eclipse.hawkbit.mgmt.json.model.distributionset.MgmtTargetAssignmentResponseBody; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtDistributionSetRestApi; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtDistributionSetTypeRestApi; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants; import org.eclipse.hawkbit.repository.DistributionSetAssignmentResult; import org.eclipse.hawkbit.repository.DistributionSetManagement; import org.eclipse.hawkbit.repository.SoftwareManagement; @@ -22,13 +29,6 @@ import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.DistributionSetMetadata; import org.eclipse.hawkbit.repository.model.DistributionSetType; import org.eclipse.hawkbit.repository.model.SoftwareModule; -import org.eclipse.hawkbit.rest.resource.api.DistributionSetRestApi; -import org.eclipse.hawkbit.rest.resource.api.DistributionSetTypeRestApi; -import org.eclipse.hawkbit.rest.resource.model.MetadataRest; -import org.eclipse.hawkbit.rest.resource.model.distributionset.DistributionSetRequestBodyPost; -import org.eclipse.hawkbit.rest.resource.model.distributionset.DistributionSetRest; -import org.eclipse.hawkbit.rest.resource.model.distributionset.DistributionSetsRest; -import org.eclipse.hawkbit.rest.resource.model.distributionset.TargetAssignmentResponseBody; /** * A mapper which maps repository model to RESTful model representation and @@ -38,8 +38,8 @@ import org.eclipse.hawkbit.rest.resource.model.distributionset.TargetAssignmentR * * */ -public final class DistributionSetMapper { - private DistributionSetMapper() { +public final class MgmtDistributionSetMapper { + private MgmtDistributionSetMapper() { // Utility class } @@ -66,7 +66,7 @@ public final class DistributionSetMapper { } /** - * {@link DistributionSetRequestBodyPost}s to {@link DistributionSet}s. + * {@link MgmtDistributionSetRequestBodyPost}s to {@link DistributionSet}s. * * @param sets * to convert @@ -74,11 +74,11 @@ public final class DistributionSetMapper { * to use for conversion * @return converted list of {@link DistributionSet}s */ - static List dsFromRequest(final Iterable sets, + static List dsFromRequest(final Iterable sets, final SoftwareManagement softwareManagement, final DistributionSetManagement distributionSetManagement) { final List mappedList = new ArrayList<>(); - for (final DistributionSetRequestBodyPost dsRest : sets) { + for (final MgmtDistributionSetRequestBodyPost dsRest : sets) { mappedList.add(fromRequest(dsRest, softwareManagement, distributionSetManagement)); } return mappedList; @@ -86,7 +86,7 @@ public final class DistributionSetMapper { } /** - * {@link DistributionSetRequestBodyPost} to {@link DistributionSet}. + * {@link MgmtDistributionSetRequestBodyPost} to {@link DistributionSet}. * * @param dsRest * to convert @@ -94,7 +94,7 @@ public final class DistributionSetMapper { * to use for conversion * @return converted {@link DistributionSet} */ - static DistributionSet fromRequest(final DistributionSetRequestBodyPost dsRest, + static DistributionSet fromRequest(final MgmtDistributionSetRequestBodyPost dsRest, final SoftwareManagement softwareManagement, final DistributionSetManagement distributionSetManagement) { final DistributionSet result = new DistributionSet(); @@ -128,16 +128,16 @@ public final class DistributionSetMapper { } /** - * From {@link MetadataRest} to {@link DistributionSetMetadata}. + * From {@link MgmtMetadata} to {@link DistributionSetMetadata}. * * @param ds * @param metadata * @return */ static List fromRequestDsMetadata(final DistributionSet ds, - final List metadata) { + final List metadata) { final List mappedList = new ArrayList<>(metadata.size()); - for (final MetadataRest metadataRest : metadata) { + for (final MgmtMetadata metadataRest : metadata) { if (metadataRest.getKey() == null) { throw new IllegalArgumentException("the key of the metadata must be present"); } @@ -153,12 +153,12 @@ public final class DistributionSetMapper { * the ds set * @return the response */ - public static DistributionSetRest toResponse(final DistributionSet distributionSet) { + public static MgmtDistributionSet toResponse(final DistributionSet distributionSet) { if (distributionSet == null) { return null; } - final DistributionSetRest response = new DistributionSetRest(); - RestModelMapper.mapNamedToNamed(response, distributionSet); + final MgmtDistributionSet response = new MgmtDistributionSet(); + MgmtRestModelMapper.mapNamedToNamed(response, distributionSet); response.setDsId(distributionSet.getId()); response.setVersion(distributionSet.getVersion()); @@ -166,35 +166,35 @@ public final class DistributionSetMapper { response.setType(distributionSet.getType().getKey()); distributionSet.getModules() - .forEach(module -> response.getModules().add(SoftwareModuleMapper.toResponse(module))); + .forEach(module -> response.getModules().add(MgmtSoftwareModuleMapper.toResponse(module))); response.setRequiredMigrationStep(distributionSet.isRequiredMigrationStep()); response.add( - linkTo(methodOn(DistributionSetRestApi.class).getDistributionSet(response.getDsId())).withRel("self")); + linkTo(methodOn(MgmtDistributionSetRestApi.class).getDistributionSet(response.getDsId())).withRel("self")); response.add(linkTo( - methodOn(DistributionSetTypeRestApi.class).getDistributionSetType(distributionSet.getType().getId())) + methodOn(MgmtDistributionSetTypeRestApi.class).getDistributionSetType(distributionSet.getType().getId())) .withRel("type")); - response.add(linkTo(methodOn(DistributionSetRestApi.class).getMetadata(response.getDsId(), - Integer.parseInt(RestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET), - Integer.parseInt(RestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT), null, null)) + response.add(linkTo(methodOn(MgmtDistributionSetRestApi.class).getMetadata(response.getDsId(), + Integer.parseInt(MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET), + Integer.parseInt(MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT), null, null)) .withRel("metadata")); return response; } - static TargetAssignmentResponseBody toResponse(final DistributionSetAssignmentResult dsAssignmentResult) { - final TargetAssignmentResponseBody result = new TargetAssignmentResponseBody(); + static MgmtTargetAssignmentResponseBody toResponse(final DistributionSetAssignmentResult dsAssignmentResult) { + final MgmtTargetAssignmentResponseBody result = new MgmtTargetAssignmentResponseBody(); result.setAssigned(dsAssignmentResult.getAssigned()); result.setAlreadyAssigned(dsAssignmentResult.getAlreadyAssigned()); result.setTotal(dsAssignmentResult.getTotal()); return result; } - static DistributionSetsRest toResponseDistributionSets(final Iterable sets) { - final DistributionSetsRest response = new DistributionSetsRest(); + static List toResponseDistributionSets(final Iterable sets) { + final List response = new ArrayList<>(); if (sets != null) { for (final DistributionSet set : sets) { @@ -204,27 +204,27 @@ public final class DistributionSetMapper { return response; } - static MetadataRest toResponseDsMetadata(final DistributionSetMetadata metadata) { - final MetadataRest metadataRest = new MetadataRest(); + static MgmtMetadata toResponseDsMetadata(final DistributionSetMetadata metadata) { + final MgmtMetadata metadataRest = new MgmtMetadata(); metadataRest.setKey(metadata.getId().getKey()); metadataRest.setValue(metadata.getValue()); return metadataRest; } - static List toResponseDsMetadata(final List metadata) { + static List toResponseDsMetadata(final List metadata) { - final List mappedList = new ArrayList<>(metadata.size()); + final List mappedList = new ArrayList<>(metadata.size()); for (final DistributionSetMetadata distributionSetMetadata : metadata) { mappedList.add(toResponseDsMetadata(distributionSetMetadata)); } return mappedList; } - static List toResponseFromDsList(final List sets) { - final List mappedList = new ArrayList<>(); + static List toResponseFromDsList(final List sets) { + final List mappedList = new ArrayList<>(); if (sets != null) { for (final DistributionSet set : sets) { - final DistributionSetRest response = toResponse(set); + final MgmtDistributionSet response = toResponse(set); mappedList.add(response); } diff --git a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/DistributionSetResource.java b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetResource.java similarity index 58% rename from hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/DistributionSetResource.java rename to hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetResource.java index a4c71378d..17f4c3303 100644 --- a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/DistributionSetResource.java +++ b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetResource.java @@ -6,18 +6,31 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource; +package org.eclipse.hawkbit.mgmt.rest.resource; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; +import org.eclipse.hawkbit.mgmt.json.model.MgmtMetadata; +import org.eclipse.hawkbit.mgmt.json.model.PagedList; +import org.eclipse.hawkbit.mgmt.json.model.distributionset.MgmtDistributionSet; +import org.eclipse.hawkbit.mgmt.json.model.distributionset.MgmtDistributionSetRequestBodyPost; +import org.eclipse.hawkbit.mgmt.json.model.distributionset.MgmtDistributionSetRequestBodyPut; +import org.eclipse.hawkbit.mgmt.json.model.distributionset.MgmtTargetAssignmentRequestBody; +import org.eclipse.hawkbit.mgmt.json.model.distributionset.MgmtTargetAssignmentResponseBody; +import org.eclipse.hawkbit.mgmt.json.model.softwaremodule.MgmtSoftwareModule; +import org.eclipse.hawkbit.mgmt.json.model.softwaremodule.MgmtSoftwareModuleAssigment; +import org.eclipse.hawkbit.mgmt.json.model.target.MgmtTarget; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtDistributionSetRestApi; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants; import org.eclipse.hawkbit.repository.DeploymentManagement; import org.eclipse.hawkbit.repository.DistributionSetAssignmentResult; import org.eclipse.hawkbit.repository.DistributionSetFields; import org.eclipse.hawkbit.repository.DistributionSetManagement; import org.eclipse.hawkbit.repository.DistributionSetMetadataFields; +import org.eclipse.hawkbit.repository.OffsetBasedPageRequest; import org.eclipse.hawkbit.repository.SoftwareManagement; import org.eclipse.hawkbit.repository.SystemManagement; import org.eclipse.hawkbit.repository.TargetFields; @@ -30,20 +43,6 @@ import org.eclipse.hawkbit.repository.model.DsMetadataCompositeKey; import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.repository.rsql.RSQLUtility; -import org.eclipse.hawkbit.rest.resource.api.DistributionSetRestApi; -import org.eclipse.hawkbit.rest.resource.helper.RestResourceConversionHelper; -import org.eclipse.hawkbit.rest.resource.model.MetadataRest; -import org.eclipse.hawkbit.rest.resource.model.MetadataRestPageList; -import org.eclipse.hawkbit.rest.resource.model.distributionset.DistributionSetPagedList; -import org.eclipse.hawkbit.rest.resource.model.distributionset.DistributionSetRequestBodyPost; -import org.eclipse.hawkbit.rest.resource.model.distributionset.DistributionSetRequestBodyPut; -import org.eclipse.hawkbit.rest.resource.model.distributionset.DistributionSetRest; -import org.eclipse.hawkbit.rest.resource.model.distributionset.DistributionSetsRest; -import org.eclipse.hawkbit.rest.resource.model.distributionset.TargetAssignmentRequestBody; -import org.eclipse.hawkbit.rest.resource.model.distributionset.TargetAssignmentResponseBody; -import org.eclipse.hawkbit.rest.resource.model.softwaremodule.SoftwareModuleAssigmentRest; -import org.eclipse.hawkbit.rest.resource.model.softwaremodule.SoftwareModulePagedList; -import org.eclipse.hawkbit.rest.resource.model.target.TargetPagedList; import org.eclipse.hawkbit.tenancy.TenantAware; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -53,14 +52,17 @@ import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; /** * REST Resource handling for {@link DistributionSet} CRUD operations. */ @RestController -public class DistributionSetResource implements DistributionSetRestApi { - private static final Logger LOG = LoggerFactory.getLogger(DistributionSetResource.class); +public class MgmtDistributionSetResource implements MgmtDistributionSetRestApi { + private static final Logger LOG = LoggerFactory.getLogger(MgmtDistributionSetResource.class); @Autowired private SoftwareManagement softwareManagement; @@ -81,8 +83,11 @@ public class DistributionSetResource implements DistributionSetRestApi { private DistributionSetManagement distributionSetManagement; @Override - public ResponseEntity getDistributionSets(final int pagingOffsetParam, - final int pagingLimitParam, final String sortParam, final String rsqlParam) { + public ResponseEntity> getDistributionSets( + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam) { final int sanitizedOffsetParam = PagingUtility.sanitizeOffsetParam(pagingOffsetParam); final int sanitizedLimitParam = PagingUtility.sanitizePageLimitParam(pagingLimitParam); @@ -97,20 +102,21 @@ public class DistributionSetResource implements DistributionSetRestApi { findDsPage = this.distributionSetManagement.findDistributionSetsAll(pageable, false, null); } - final List rest = DistributionSetMapper.toResponseFromDsList(findDsPage.getContent()); - return new ResponseEntity<>(new DistributionSetPagedList(rest, findDsPage.getTotalElements()), HttpStatus.OK); + final List rest = MgmtDistributionSetMapper.toResponseFromDsList(findDsPage.getContent()); + return new ResponseEntity<>(new PagedList<>(rest, findDsPage.getTotalElements()), HttpStatus.OK); } @Override - public ResponseEntity getDistributionSet(final Long distributionSetId) { + public ResponseEntity getDistributionSet( + @PathVariable("distributionSetId") final Long distributionSetId) { final DistributionSet foundDs = findDistributionSetWithExceptionIfNotFound(distributionSetId); - return new ResponseEntity<>(DistributionSetMapper.toResponse(foundDs), HttpStatus.OK); + return new ResponseEntity<>(MgmtDistributionSetMapper.toResponse(foundDs), HttpStatus.OK); } @Override - public ResponseEntity createDistributionSets( - final List sets) { + public ResponseEntity> createDistributionSets( + @RequestBody final List sets) { LOG.debug("creating {} distribution sets", sets.size()); // set default Ds type if ds type is null @@ -118,14 +124,15 @@ public class DistributionSetResource implements DistributionSetRestApi { .getTenantMetadata(this.currentTenant.getCurrentTenant()).getDefaultDsType().getKey())); final Iterable createdDSets = this.distributionSetManagement.createDistributionSets( - DistributionSetMapper.dsFromRequest(sets, this.softwareManagement, this.distributionSetManagement)); + MgmtDistributionSetMapper.dsFromRequest(sets, this.softwareManagement, this.distributionSetManagement)); LOG.debug("{} distribution sets created, return status {}", sets.size(), HttpStatus.CREATED); - return new ResponseEntity<>(DistributionSetMapper.toResponseDistributionSets(createdDSets), HttpStatus.CREATED); + return new ResponseEntity<>(MgmtDistributionSetMapper.toResponseDistributionSets(createdDSets), + HttpStatus.CREATED); } @Override - public ResponseEntity deleteDistributionSet(final Long distributionSetId) { + public ResponseEntity deleteDistributionSet(@PathVariable("distributionSetId") final Long distributionSetId) { final DistributionSet set = findDistributionSetWithExceptionIfNotFound(distributionSetId); this.distributionSetManagement.deleteDistributionSet(set); @@ -134,8 +141,9 @@ public class DistributionSetResource implements DistributionSetRestApi { } @Override - public ResponseEntity updateDistributionSet(final Long distributionSetId, - final DistributionSetRequestBodyPut toUpdate) { + public ResponseEntity updateDistributionSet( + @PathVariable("distributionSetId") final Long distributionSetId, + @RequestBody final MgmtDistributionSetRequestBodyPut toUpdate) { final DistributionSet set = findDistributionSetWithExceptionIfNotFound(distributionSetId); if (toUpdate.getDescription() != null) { @@ -150,13 +158,17 @@ public class DistributionSetResource implements DistributionSetRestApi { set.setVersion(toUpdate.getVersion()); } return new ResponseEntity<>( - DistributionSetMapper.toResponse(this.distributionSetManagement.updateDistributionSet(set)), + MgmtDistributionSetMapper.toResponse(this.distributionSetManagement.updateDistributionSet(set)), HttpStatus.OK); } @Override - public ResponseEntity getAssignedTargets(final Long distributionSetId, final int pagingOffsetParam, - final int pagingLimitParam, final String sortParam, final String rsqlParam) { + public ResponseEntity> getAssignedTargets( + @PathVariable("distributionSetId") final Long distributionSetId, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam) { // check if distribution set exists otherwise throw exception // immediately @@ -175,13 +187,17 @@ public class DistributionSetResource implements DistributionSetRestApi { targetsAssignedDS = this.targetManagement.findTargetByAssignedDistributionSet(distributionSetId, pageable); } - return new ResponseEntity<>(new TargetPagedList(TargetMapper.toResponse(targetsAssignedDS.getContent()), + return new ResponseEntity<>(new PagedList<>(MgmtTargetMapper.toResponse(targetsAssignedDS.getContent()), targetsAssignedDS.getTotalElements()), HttpStatus.OK); } @Override - public ResponseEntity getInstalledTargets(final Long distributionSetId, - final int pagingOffsetParam, final int pagingLimitParam, final String sortParam, final String rsqlParam) { + public ResponseEntity> getInstalledTargets( + @PathVariable("distributionSetId") final Long distributionSetId, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam) { // check if distribution set exists otherwise throw exception // immediately findDistributionSetWithExceptionIfNotFound(distributionSetId); @@ -200,27 +216,34 @@ public class DistributionSetResource implements DistributionSetRestApi { pageable); } - return new ResponseEntity<>(new TargetPagedList(TargetMapper.toResponse(targetsInstalledDS.getContent()), - targetsInstalledDS.getTotalElements()), HttpStatus.OK); + return new ResponseEntity<>( + new PagedList(MgmtTargetMapper.toResponse(targetsInstalledDS.getContent()), + targetsInstalledDS.getTotalElements()), + HttpStatus.OK); } @Override - public ResponseEntity createAssignedTarget(final Long distributionSetId, - final List targetIds) { + public ResponseEntity createAssignedTarget( + @PathVariable("distributionSetId") final Long distributionSetId, + @RequestBody final List targetIds) { final DistributionSetAssignmentResult assignDistributionSet = this.deployManagament.assignDistributionSet( distributionSetId, targetIds.stream() .map(t -> new TargetWithActionType(t.getId(), - RestResourceConversionHelper.convertActionType(t.getType()), t.getForcetime())) + MgmtRestModelMapper.convertActionType(t.getType()), t.getForcetime())) .collect(Collectors.toList())); - return new ResponseEntity<>(DistributionSetMapper.toResponse(assignDistributionSet), HttpStatus.OK); + return new ResponseEntity<>(MgmtDistributionSetMapper.toResponse(assignDistributionSet), HttpStatus.OK); } @Override - public ResponseEntity getMetadata(final Long distributionSetId, final int pagingOffsetParam, - final int pagingLimitParam, final String sortParam, final String rsqlParam) { + public ResponseEntity> getMetadata( + @PathVariable("distributionSetId") final Long distributionSetId, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam) { // check if distribution set exists otherwise throw exception // immediately @@ -242,35 +265,38 @@ public class DistributionSetResource implements DistributionSetRestApi { } return new ResponseEntity<>( - new MetadataRestPageList(DistributionSetMapper.toResponseDsMetadata(metaDataPage.getContent()), + new PagedList<>(MgmtDistributionSetMapper.toResponseDsMetadata(metaDataPage.getContent()), metaDataPage.getTotalElements()), HttpStatus.OK); } @Override - public ResponseEntity getMetadataValue(final Long distributionSetId, final String metadataKey) { + public ResponseEntity getMetadataValue( + @PathVariable("distributionSetId") final Long distributionSetId, + @PathVariable("metadataKey") final String metadataKey) { // check if distribution set exists otherwise throw exception // immediately final DistributionSet ds = findDistributionSetWithExceptionIfNotFound(distributionSetId); final DistributionSetMetadata findOne = this.distributionSetManagement .findOne(new DsMetadataCompositeKey(ds, metadataKey)); - return ResponseEntity. ok(DistributionSetMapper.toResponseDsMetadata(findOne)); + return ResponseEntity. ok(MgmtDistributionSetMapper.toResponseDsMetadata(findOne)); } @Override - public ResponseEntity updateMetadata(final Long distributionSetId, final String metadataKey, - final MetadataRest metadata) { + public ResponseEntity updateMetadata(@PathVariable("distributionSetId") final Long distributionSetId, + @PathVariable("metadataKey") final String metadataKey, @RequestBody final MgmtMetadata metadata) { // check if distribution set exists otherwise throw exception // immediately final DistributionSet ds = findDistributionSetWithExceptionIfNotFound(distributionSetId); final DistributionSetMetadata updated = this.distributionSetManagement .updateDistributionSetMetadata(new DistributionSetMetadata(metadataKey, ds, metadata.getValue())); - return ResponseEntity.ok(DistributionSetMapper.toResponseDsMetadata(updated)); + return ResponseEntity.ok(MgmtDistributionSetMapper.toResponseDsMetadata(updated)); } @Override - public ResponseEntity deleteMetadata(final Long distributionSetId, final String metadataKey) { + public ResponseEntity deleteMetadata(@PathVariable("distributionSetId") final Long distributionSetId, + @PathVariable("metadataKey") final String metadataKey) { // check if distribution set exists otherwise throw exception // immediately final DistributionSet ds = findDistributionSetWithExceptionIfNotFound(distributionSetId); @@ -279,27 +305,28 @@ public class DistributionSetResource implements DistributionSetRestApi { } @Override - public ResponseEntity> createMetadata(final Long distributionSetId, - final List metadataRest) { + public ResponseEntity> createMetadata( + @PathVariable("distributionSetId") final Long distributionSetId, + @RequestBody final List metadataRest) { // check if distribution set exists otherwise throw exception // immediately final DistributionSet ds = findDistributionSetWithExceptionIfNotFound(distributionSetId); final List created = this.distributionSetManagement - .createDistributionSetMetadata(DistributionSetMapper.fromRequestDsMetadata(ds, metadataRest)); - return new ResponseEntity<>(DistributionSetMapper.toResponseDsMetadata(created), HttpStatus.CREATED); + .createDistributionSetMetadata(MgmtDistributionSetMapper.fromRequestDsMetadata(ds, metadataRest)); + return new ResponseEntity<>(MgmtDistributionSetMapper.toResponseDsMetadata(created), HttpStatus.CREATED); } @Override - public ResponseEntity assignSoftwareModules(final Long distributionSetId, - final List softwareModuleIDs) { + public ResponseEntity assignSoftwareModules(@PathVariable("distributionSetId") final Long distributionSetId, + @RequestBody final List softwareModuleIDs) { // check if distribution set exists otherwise throw exception // immediately final DistributionSet ds = findDistributionSetWithExceptionIfNotFound(distributionSetId); final Set softwareModuleToBeAssigned = new HashSet<>(); - for (final SoftwareModuleAssigmentRest sm : softwareModuleIDs) { + for (final MgmtSoftwareModuleAssigment sm : softwareModuleIDs) { final SoftwareModule softwareModule = this.softwareManagement.findSoftwareModuleById(sm.getId()); if (softwareModule != null) { softwareModuleToBeAssigned.add(softwareModule); @@ -313,7 +340,9 @@ public class DistributionSetResource implements DistributionSetRestApi { } @Override - public ResponseEntity deleteAssignSoftwareModules(final Long distributionSetId, final Long softwareModuleId) { + public ResponseEntity deleteAssignSoftwareModules( + @PathVariable("distributionSetId") final Long distributionSetId, + @PathVariable("softwareModuleId") final Long softwareModuleId) { // check if distribution set and software module exist otherwise throw // exception immediately final DistributionSet ds = findDistributionSetWithExceptionIfNotFound(distributionSetId); @@ -323,8 +352,11 @@ public class DistributionSetResource implements DistributionSetRestApi { } @Override - public ResponseEntity getAssignedSoftwareModules(final Long distributionSetId, - final int pagingOffsetParam, final int pagingLimitParam, final String sortParam) { + public ResponseEntity> getAssignedSoftwareModules( + @PathVariable("distributionSetId") final Long distributionSetId, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam) { // check if distribution set exists otherwise throw exception // immediately final DistributionSet foundDs = findDistributionSetWithExceptionIfNotFound(distributionSetId); @@ -334,10 +366,8 @@ public class DistributionSetResource implements DistributionSetRestApi { final Pageable pageable = new OffsetBasedPageRequest(sanitizedOffsetParam, sanitizedLimitParam, sorting); final Page softwaremodules = this.softwareManagement.findSoftwareModuleByAssignedTo(pageable, foundDs); - return new ResponseEntity<>( - new SoftwareModulePagedList(SoftwareModuleMapper.toResponse(softwaremodules.getContent()), - softwaremodules.getTotalElements()), - HttpStatus.OK); + return new ResponseEntity<>(new PagedList<>(MgmtSoftwareModuleMapper.toResponse(softwaremodules.getContent()), + softwaremodules.getTotalElements()), HttpStatus.OK); } private DistributionSet findDistributionSetWithExceptionIfNotFound(final Long distributionSetId) { diff --git a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/DistributionSetTagResource.java b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTagResource.java similarity index 56% rename from hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/DistributionSetTagResource.java rename to hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTagResource.java index c395863ab..907bbb574 100644 --- a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/DistributionSetTagResource.java +++ b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTagResource.java @@ -6,27 +6,28 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource; +package org.eclipse.hawkbit.mgmt.rest.resource; import java.util.List; import java.util.stream.Collectors; +import org.eclipse.hawkbit.mgmt.json.model.PagedList; +import org.eclipse.hawkbit.mgmt.json.model.distributionset.MgmtDistributionSet; +import org.eclipse.hawkbit.mgmt.json.model.tag.MgmtAssignedDistributionSetRequestBody; +import org.eclipse.hawkbit.mgmt.json.model.tag.MgmtDistributionSetTagAssigmentResult; +import org.eclipse.hawkbit.mgmt.json.model.tag.MgmtTag; +import org.eclipse.hawkbit.mgmt.json.model.tag.MgmtTagRequestBodyPut; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtDistributionSetTagRestApi; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants; import org.eclipse.hawkbit.repository.DistributionSetManagement; +import org.eclipse.hawkbit.repository.OffsetBasedPageRequest; import org.eclipse.hawkbit.repository.TagFields; import org.eclipse.hawkbit.repository.TagManagement; import org.eclipse.hawkbit.repository.exception.EntityNotFoundException; import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.DistributionSetTag; -import org.eclipse.hawkbit.repository.model.DistributionSetTagAssigmentResult; +import org.eclipse.hawkbit.repository.model.DistributionSetTagAssignmentResult; import org.eclipse.hawkbit.repository.rsql.RSQLUtility; -import org.eclipse.hawkbit.rest.resource.api.DistributionSetTagRestApi; -import org.eclipse.hawkbit.rest.resource.model.distributionset.DistributionSetsRest; -import org.eclipse.hawkbit.rest.resource.model.tag.AssignedDistributionSetRequestBody; -import org.eclipse.hawkbit.rest.resource.model.tag.DistributionSetTagAssigmentResultRest; -import org.eclipse.hawkbit.rest.resource.model.tag.TagPagedList; -import org.eclipse.hawkbit.rest.resource.model.tag.TagRequestBodyPut; -import org.eclipse.hawkbit.rest.resource.model.tag.TagRest; -import org.eclipse.hawkbit.rest.resource.model.tag.TagsRest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -36,6 +37,9 @@ import org.springframework.data.domain.Slice; import org.springframework.data.domain.Sort; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; /** @@ -43,8 +47,8 @@ import org.springframework.web.bind.annotation.RestController; * */ @RestController -public class DistributionSetTagResource implements DistributionSetTagRestApi { - private static final Logger LOG = LoggerFactory.getLogger(DistributionSetTagResource.class); +public class MgmtDistributionSetTagResource implements MgmtDistributionSetTagRestApi { + private static final Logger LOG = LoggerFactory.getLogger(MgmtDistributionSetTagResource.class); @Autowired private TagManagement tagManagement; @@ -53,8 +57,11 @@ public class DistributionSetTagResource implements DistributionSetTagRestApi { private DistributionSetManagement distributionSetManagement; @Override - public ResponseEntity getDistributionSetTags(final int pagingOffsetParam, final int pagingLimitParam, - final String sortParam, final String rsqlParam) { + public ResponseEntity> getDistributionSetTags( + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam) { final int sanitizedOffsetParam = PagingUtility.sanitizeOffsetParam(pagingOffsetParam); final int sanitizedLimitParam = PagingUtility.sanitizePageLimitParam(pagingLimitParam); @@ -75,43 +82,47 @@ public class DistributionSetTagResource implements DistributionSetTagRestApi { } - final List rest = TagMapper.toResponseDistributionSetTag(findTargetsAll.getContent()); - return new ResponseEntity<>(new TagPagedList(rest, countTargetsAll), HttpStatus.OK); + final List rest = MgmtTagMapper.toResponseDistributionSetTag(findTargetsAll.getContent()); + return new ResponseEntity<>(new PagedList<>(rest, countTargetsAll), HttpStatus.OK); } @Override - public ResponseEntity getDistributionSetTag(final Long distributionsetTagId) { + public ResponseEntity getDistributionSetTag( + @PathVariable("distributionsetTagId") final Long distributionsetTagId) { final DistributionSetTag tag = findDistributionTagById(distributionsetTagId); - return new ResponseEntity<>(TagMapper.toResponse(tag), HttpStatus.OK); + return new ResponseEntity<>(MgmtTagMapper.toResponse(tag), HttpStatus.OK); } @Override - public ResponseEntity createDistributionSetTags(final List tags) { + public ResponseEntity> createDistributionSetTags( + @RequestBody final List tags) { LOG.debug("creating {} ds tags", tags.size()); final List createdTags = this.tagManagement - .createDistributionSetTags(TagMapper.mapDistributionSetTagFromRequest(tags)); + .createDistributionSetTags(MgmtTagMapper.mapDistributionSetTagFromRequest(tags)); - return new ResponseEntity<>(TagMapper.toResponseDistributionSetTag(createdTags), HttpStatus.CREATED); + return new ResponseEntity<>(MgmtTagMapper.toResponseDistributionSetTag(createdTags), HttpStatus.CREATED); } @Override - public ResponseEntity updateDistributionSetTag(final Long distributionsetTagId, - final TagRequestBodyPut restDSTagRest) { + public ResponseEntity updateDistributionSetTag( + @PathVariable("distributionsetTagId") final Long distributionsetTagId, + @RequestBody final MgmtTagRequestBodyPut restDSTagRest) { LOG.debug("update {} ds tag", restDSTagRest); final DistributionSetTag distributionSetTag = findDistributionTagById(distributionsetTagId); - TagMapper.updateTag(restDSTagRest, distributionSetTag); + MgmtTagMapper.updateTag(restDSTagRest, distributionSetTag); final DistributionSetTag updateDistributionSetTag = this.tagManagement .updateDistributionSetTag(distributionSetTag); LOG.debug("ds tag updated"); - return new ResponseEntity<>(TagMapper.toResponse(updateDistributionSetTag), HttpStatus.OK); + return new ResponseEntity<>(MgmtTagMapper.toResponse(updateDistributionSetTag), HttpStatus.OK); } @Override - public ResponseEntity deleteDistributionSetTag(final Long distributionsetTagId) { + public ResponseEntity deleteDistributionSetTag( + @PathVariable("distributionsetTagId") final Long distributionsetTagId) { LOG.debug("Delete {} distribution set tag", distributionsetTagId); final DistributionSetTag tag = findDistributionTagById(distributionsetTagId); @@ -121,28 +132,31 @@ public class DistributionSetTagResource implements DistributionSetTagRestApi { } @Override - public ResponseEntity getAssignedDistributionSets(final Long distributionsetTagId) { + public ResponseEntity> getAssignedDistributionSets( + @PathVariable("distributionsetTagId") final Long distributionsetTagId) { final DistributionSetTag tag = findDistributionTagById(distributionsetTagId); return new ResponseEntity<>( - DistributionSetMapper.toResponseDistributionSets(tag.getAssignedToDistributionSet()), HttpStatus.OK); + MgmtDistributionSetMapper.toResponseDistributionSets(tag.getAssignedToDistributionSet()), + HttpStatus.OK); } @Override - public ResponseEntity toggleTagAssignment(final Long distributionsetTagId, - final List assignedDSRequestBodies) { + public ResponseEntity toggleTagAssignment( + @PathVariable("distributionsetTagId") final Long distributionsetTagId, + @RequestBody final List assignedDSRequestBodies) { LOG.debug("Toggle distribution set assignment {} for ds tag {}", assignedDSRequestBodies.size(), distributionsetTagId); final DistributionSetTag tag = findDistributionTagById(distributionsetTagId); - final DistributionSetTagAssigmentResult assigmentResult = this.distributionSetManagement + final DistributionSetTagAssignmentResult assigmentResult = this.distributionSetManagement .toggleTagAssignment(findDistributionSetIds(assignedDSRequestBodies), tag.getName()); - final DistributionSetTagAssigmentResultRest tagAssigmentResultRest = new DistributionSetTagAssigmentResultRest(); + final MgmtDistributionSetTagAssigmentResult tagAssigmentResultRest = new MgmtDistributionSetTagAssigmentResult(); tagAssigmentResultRest.setAssignedDistributionSets( - DistributionSetMapper.toResponseDistributionSets(assigmentResult.getAssignedDs())); + MgmtDistributionSetMapper.toResponseDistributionSets(assigmentResult.getAssignedEntity())); tagAssigmentResultRest.setUnassignedDistributionSets( - DistributionSetMapper.toResponseDistributionSets(assigmentResult.getUnassignedDs())); + MgmtDistributionSetMapper.toResponseDistributionSets(assigmentResult.getUnassignedEntity())); LOG.debug("Toggled assignedDS {} and unassignedDS{}", assigmentResult.getAssigned(), assigmentResult.getUnassigned()); @@ -151,19 +165,21 @@ public class DistributionSetTagResource implements DistributionSetTagRestApi { } @Override - public ResponseEntity assignDistributionSets(final Long distributionsetTagId, - final List assignedDSRequestBodies) { + public ResponseEntity> assignDistributionSets( + @PathVariable("distributionsetTagId") final Long distributionsetTagId, + @RequestBody final List assignedDSRequestBodies) { LOG.debug("Assign DistributionSet {} for ds tag {}", assignedDSRequestBodies.size(), distributionsetTagId); final DistributionSetTag tag = findDistributionTagById(distributionsetTagId); final List assignedDs = this.distributionSetManagement .assignTag(findDistributionSetIds(assignedDSRequestBodies), tag); LOG.debug("Assignd DistributionSet {}", assignedDs.size()); - return new ResponseEntity<>(DistributionSetMapper.toResponseDistributionSets(assignedDs), HttpStatus.OK); + return new ResponseEntity<>(MgmtDistributionSetMapper.toResponseDistributionSets(assignedDs), HttpStatus.OK); } @Override - public ResponseEntity unassignDistributionSets(final Long distributionsetTagId) { + public ResponseEntity unassignDistributionSets( + @PathVariable("distributionsetTagId") final Long distributionsetTagId) { LOG.debug("Unassign all DS for ds tag {}", distributionsetTagId); final DistributionSetTag tag = findDistributionTagById(distributionsetTagId); if (tag.getAssignedToDistributionSet() == null) { @@ -178,7 +194,9 @@ public class DistributionSetTagResource implements DistributionSetTagRestApi { } @Override - public ResponseEntity unassignDistributionSet(final Long distributionsetTagId, final Long distributionsetId) { + public ResponseEntity unassignDistributionSet( + @PathVariable("distributionsetTagId") final Long distributionsetTagId, + @PathVariable("distributionsetId") final Long distributionsetId) { LOG.debug("Unassign ds {} for ds tag {}", distributionsetId, distributionsetTagId); final DistributionSetTag tag = findDistributionTagById(distributionsetTagId); this.distributionSetManagement.unAssignTag(distributionsetId, tag); @@ -194,7 +212,7 @@ public class DistributionSetTagResource implements DistributionSetTagRestApi { } private List findDistributionSetIds( - final List assignedDistributionSetRequestBodies) { + final List assignedDistributionSetRequestBodies) { return assignedDistributionSetRequestBodies.stream().map(request -> request.getDistributionSetId()) .collect(Collectors.toList()); } diff --git a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/DistributionSetTypeMapper.java b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTypeMapper.java similarity index 59% rename from hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/DistributionSetTypeMapper.java rename to hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTypeMapper.java index b32302705..d3046f149 100644 --- a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/DistributionSetTypeMapper.java +++ b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTypeMapper.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource; +package org.eclipse.hawkbit.mgmt.rest.resource; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; @@ -14,42 +14,39 @@ import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; import java.util.ArrayList; import java.util.List; +import org.eclipse.hawkbit.mgmt.json.model.distributionsettype.MgmtDistributionSetTypeRequestBodyPost; +import org.eclipse.hawkbit.mgmt.json.model.distributionsettype.MgmtDistributionSetType; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtDistributionSetTypeRestApi; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants; import org.eclipse.hawkbit.repository.SoftwareManagement; import org.eclipse.hawkbit.repository.exception.EntityNotFoundException; import org.eclipse.hawkbit.repository.model.DistributionSetType; import org.eclipse.hawkbit.repository.model.SoftwareModuleType; -import org.eclipse.hawkbit.rest.resource.api.DistributionSetTypeRestApi; -import org.eclipse.hawkbit.rest.resource.model.distributionsettype.DistributionSetTypeRequestBodyPost; -import org.eclipse.hawkbit.rest.resource.model.distributionsettype.DistributionSetTypeRest; -import org.eclipse.hawkbit.rest.resource.model.distributionsettype.DistributionSetTypesRest; /** * A mapper which maps repository model to RESTful model representation and * back. * - * - * - * */ -final class DistributionSetTypeMapper { +final class MgmtDistributionSetTypeMapper { // private constructor, utility class - private DistributionSetTypeMapper() { + private MgmtDistributionSetTypeMapper() { } static List smFromRequest(final SoftwareManagement softwareManagement, - final Iterable smTypesRest) { + final Iterable smTypesRest) { final List mappedList = new ArrayList<>(); - for (final DistributionSetTypeRequestBodyPost smRest : smTypesRest) { + for (final MgmtDistributionSetTypeRequestBodyPost smRest : smTypesRest) { mappedList.add(fromRequest(softwareManagement, smRest)); } return mappedList; } static DistributionSetType fromRequest(final SoftwareManagement softwareManagement, - final DistributionSetTypeRequestBodyPost smsRest) { + final MgmtDistributionSetTypeRequestBodyPost smsRest) { final DistributionSetType result = new DistributionSetType(smsRest.getKey(), smsRest.getName(), smsRest.getDescription()); @@ -63,7 +60,7 @@ final class DistributionSetTypeMapper { } return smType; - }).forEach(softmType -> result.addMandatoryModuleType(softmType)); + }).forEach(result::addMandatoryModuleType); // Add optional smsRest.getOptionalmodules().stream().map(opt -> { @@ -74,42 +71,42 @@ final class DistributionSetTypeMapper { } return smType; - }).forEach(softmType -> result.addOptionalModuleType(softmType)); + }).forEach(result::addOptionalModuleType); return result; } - static DistributionSetTypesRest toTypesResponse(final List types) { - final DistributionSetTypesRest response = new DistributionSetTypesRest(); + static List toTypesResponse(final List types) { + final List response = new ArrayList<>(); for (final DistributionSetType dsType : types) { response.add(toResponse(dsType)); } return response; } - static List toListResponse(final List types) { - final List response = new ArrayList<>(); + static List toListResponse(final List types) { + final List response = new ArrayList<>(); for (final DistributionSetType dsType : types) { response.add(toResponse(dsType)); } return response; } - static DistributionSetTypeRest toResponse(final DistributionSetType type) { - final DistributionSetTypeRest result = new DistributionSetTypeRest(); + static MgmtDistributionSetType toResponse(final DistributionSetType type) { + final MgmtDistributionSetType result = new MgmtDistributionSetType(); - RestModelMapper.mapNamedToNamed(result, type); + MgmtRestModelMapper.mapNamedToNamed(result, type); result.setKey(type.getKey()); result.setModuleId(type.getId()); - result.add(linkTo(methodOn(DistributionSetTypeRestApi.class).getDistributionSetType(result.getModuleId())) + result.add(linkTo(methodOn(MgmtDistributionSetTypeRestApi.class).getDistributionSetType(result.getModuleId())) .withRel("self")); - result.add(linkTo(methodOn(DistributionSetTypeRestApi.class).getMandatoryModules(result.getModuleId())) - .withRel(RestConstants.DISTRIBUTIONSETTYPE_V1_MANDATORY_MODULES)); + result.add(linkTo(methodOn(MgmtDistributionSetTypeRestApi.class).getMandatoryModules(result.getModuleId())) + .withRel(MgmtRestConstants.DISTRIBUTIONSETTYPE_V1_MANDATORY_MODULES)); - result.add(linkTo(methodOn(DistributionSetTypeRestApi.class).getOptionalModules(result.getModuleId())) - .withRel(RestConstants.DISTRIBUTIONSETTYPE_V1_OPTIONAL_MODULES)); + result.add(linkTo(methodOn(MgmtDistributionSetTypeRestApi.class).getOptionalModules(result.getModuleId())) + .withRel(MgmtRestConstants.DISTRIBUTIONSETTYPE_V1_OPTIONAL_MODULES)); return result; } diff --git a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/DistributionSetTypeResource.java b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTypeResource.java similarity index 62% rename from hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/DistributionSetTypeResource.java rename to hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTypeResource.java index a5c8544fb..baa6f2955 100644 --- a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/DistributionSetTypeResource.java +++ b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTypeResource.java @@ -6,12 +6,21 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource; +package org.eclipse.hawkbit.mgmt.rest.resource; import java.util.List; +import org.eclipse.hawkbit.mgmt.json.model.MgmtId; +import org.eclipse.hawkbit.mgmt.json.model.PagedList; +import org.eclipse.hawkbit.mgmt.json.model.distributionsettype.MgmtDistributionSetTypeRequestBodyPost; +import org.eclipse.hawkbit.mgmt.json.model.distributionsettype.MgmtDistributionSetTypeRequestBodyPut; +import org.eclipse.hawkbit.mgmt.json.model.distributionsettype.MgmtDistributionSetType; +import org.eclipse.hawkbit.mgmt.json.model.softwaremoduletype.MgmtSoftwareModuleType; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtDistributionSetTypeRestApi; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants; import org.eclipse.hawkbit.repository.DistributionSetManagement; import org.eclipse.hawkbit.repository.DistributionSetTypeFields; +import org.eclipse.hawkbit.repository.OffsetBasedPageRequest; import org.eclipse.hawkbit.repository.SoftwareManagement; import org.eclipse.hawkbit.repository.exception.EntityNotFoundException; import org.eclipse.hawkbit.repository.model.Artifact; @@ -19,15 +28,6 @@ import org.eclipse.hawkbit.repository.model.DistributionSetType; import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.repository.model.SoftwareModuleType; import org.eclipse.hawkbit.repository.rsql.RSQLUtility; -import org.eclipse.hawkbit.rest.resource.api.DistributionSetTypeRestApi; -import org.eclipse.hawkbit.rest.resource.model.IdRest; -import org.eclipse.hawkbit.rest.resource.model.distributionsettype.DistributionSetTypePagedList; -import org.eclipse.hawkbit.rest.resource.model.distributionsettype.DistributionSetTypeRequestBodyPost; -import org.eclipse.hawkbit.rest.resource.model.distributionsettype.DistributionSetTypeRequestBodyPut; -import org.eclipse.hawkbit.rest.resource.model.distributionsettype.DistributionSetTypeRest; -import org.eclipse.hawkbit.rest.resource.model.distributionsettype.DistributionSetTypesRest; -import org.eclipse.hawkbit.rest.resource.model.softwaremoduletype.SoftwareModuleTypeRest; -import org.eclipse.hawkbit.rest.resource.model.softwaremoduletype.SoftwareModuleTypesRest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; @@ -47,7 +47,7 @@ import org.springframework.web.bind.annotation.RestController; * */ @RestController -public class DistributionSetTypeResource implements DistributionSetTypeRestApi { +public class MgmtDistributionSetTypeResource implements MgmtDistributionSetTypeRestApi { @Autowired private SoftwareManagement softwareManagement; @@ -56,11 +56,11 @@ public class DistributionSetTypeResource implements DistributionSetTypeRestApi { private DistributionSetManagement distributionSetManagement; @Override - public ResponseEntity getDistributionSetTypes( - @RequestParam(value = RestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = RestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = RestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam) { + public ResponseEntity> getDistributionSetTypes( + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam) { final int sanitizedOffsetParam = PagingUtility.sanitizeOffsetParam(pagingOffsetParam); final int sanitizedLimitParam = PagingUtility.sanitizePageLimitParam(pagingLimitParam); @@ -79,21 +79,22 @@ public class DistributionSetTypeResource implements DistributionSetTypeRestApi { countModulesAll = distributionSetManagement.countDistributionSetTypesAll(); } - final List rest = DistributionSetTypeMapper + final List rest = MgmtDistributionSetTypeMapper .toListResponse(findModuleTypessAll.getContent()); - return new ResponseEntity<>(new DistributionSetTypePagedList(rest, countModulesAll), HttpStatus.OK); + return new ResponseEntity<>(new PagedList<>(rest, countModulesAll), HttpStatus.OK); } @Override - public ResponseEntity getDistributionSetType( - @PathVariable final Long distributionSetTypeId) { + public ResponseEntity getDistributionSetType( + @PathVariable("distributionSetTypeId") final Long distributionSetTypeId) { final DistributionSetType foundType = findDistributionSetTypeWithExceptionIfNotFound(distributionSetTypeId); - return new ResponseEntity<>(DistributionSetTypeMapper.toResponse(foundType), HttpStatus.OK); + return new ResponseEntity<>(MgmtDistributionSetTypeMapper.toResponse(foundType), HttpStatus.OK); } @Override - public ResponseEntity deleteDistributionSetType(@PathVariable final Long distributionSetTypeId) { + public ResponseEntity deleteDistributionSetType( + @PathVariable("distributionSetTypeId") final Long distributionSetTypeId) { final DistributionSetType module = findDistributionSetTypeWithExceptionIfNotFound(distributionSetTypeId); distributionSetManagement.deleteDistributionSetType(module); @@ -102,9 +103,9 @@ public class DistributionSetTypeResource implements DistributionSetTypeRestApi { } @Override - public ResponseEntity updateDistributionSetType( - @PathVariable final Long distributionSetTypeId, - @RequestBody final DistributionSetTypeRequestBodyPut restDistributionSetType) { + public ResponseEntity updateDistributionSetType( + @PathVariable("distributionSetTypeId") final Long distributionSetTypeId, + @RequestBody final MgmtDistributionSetTypeRequestBodyPut restDistributionSetType) { final DistributionSetType type = findDistributionSetTypeWithExceptionIfNotFound(distributionSetTypeId); // only description can be modified @@ -115,17 +116,18 @@ public class DistributionSetTypeResource implements DistributionSetTypeRestApi { final DistributionSetType updatedDistributionSetType = distributionSetManagement .updateDistributionSetType(type); - return new ResponseEntity<>(DistributionSetTypeMapper.toResponse(updatedDistributionSetType), HttpStatus.OK); + return new ResponseEntity<>(MgmtDistributionSetTypeMapper.toResponse(updatedDistributionSetType), + HttpStatus.OK); } @Override - public ResponseEntity createDistributionSetTypes( - @RequestBody final List distributionSetTypes) { + public ResponseEntity> createDistributionSetTypes( + @RequestBody final List distributionSetTypes) { final List createdSoftwareModules = distributionSetManagement.createDistributionSetTypes( - DistributionSetTypeMapper.smFromRequest(softwareManagement, distributionSetTypes)); + MgmtDistributionSetTypeMapper.smFromRequest(softwareManagement, distributionSetTypes)); - return new ResponseEntity<>(DistributionSetTypeMapper.toTypesResponse(createdSoftwareModules), + return new ResponseEntity<>(MgmtDistributionSetTypeMapper.toTypesResponse(createdSoftwareModules), HttpStatus.CREATED); } @@ -139,19 +141,18 @@ public class DistributionSetTypeResource implements DistributionSetTypeRestApi { } @Override - public ResponseEntity getMandatoryModules(@PathVariable final Long distributionSetTypeId) { + public ResponseEntity> getMandatoryModules( + @PathVariable("distributionSetTypeId") final Long distributionSetTypeId) { final DistributionSetType foundType = findDistributionSetTypeWithExceptionIfNotFound(distributionSetTypeId); - - final SoftwareModuleTypesRest rest = new SoftwareModuleTypesRest(); - - rest.addAll(SoftwareModuleTypeMapper.toListResponse(foundType.getMandatoryModuleTypes())); - return new ResponseEntity<>(rest, HttpStatus.OK); + return new ResponseEntity<>(MgmtSoftwareModuleTypeMapper.toListResponse(foundType.getMandatoryModuleTypes()), + HttpStatus.OK); } @Override - public ResponseEntity getMandatoryModule(@PathVariable final Long distributionSetTypeId, - @PathVariable final Long softwareModuleTypeId) { + public ResponseEntity getMandatoryModule( + @PathVariable("distributionSetTypeId") final Long distributionSetTypeId, + @PathVariable("softwareModuleTypeId") final Long softwareModuleTypeId) { final DistributionSetType foundType = findDistributionSetTypeWithExceptionIfNotFound(distributionSetTypeId); @@ -162,12 +163,13 @@ public class DistributionSetTypeResource implements DistributionSetTypeRestApi { "Software module with given ID is not part of this distribution set type!"); } - return new ResponseEntity<>(SoftwareModuleTypeMapper.toResponse(foundSmType), HttpStatus.OK); + return new ResponseEntity<>(MgmtSoftwareModuleTypeMapper.toResponse(foundSmType), HttpStatus.OK); } @Override - public ResponseEntity getOptionalModule(@PathVariable final Long distributionSetTypeId, - @PathVariable final Long softwareModuleTypeId) { + public ResponseEntity getOptionalModule( + @PathVariable("distributionSetTypeId") final Long distributionSetTypeId, + @PathVariable("softwareModuleTypeId") final Long softwareModuleTypeId) { final DistributionSetType foundType = findDistributionSetTypeWithExceptionIfNotFound(distributionSetTypeId); @@ -178,23 +180,23 @@ public class DistributionSetTypeResource implements DistributionSetTypeRestApi { "Software module with given ID is not part of this distribution set type!"); } - return new ResponseEntity<>(SoftwareModuleTypeMapper.toResponse(foundSmType), HttpStatus.OK); + return new ResponseEntity<>(MgmtSoftwareModuleTypeMapper.toResponse(foundSmType), HttpStatus.OK); } @Override - public ResponseEntity getOptionalModules(@PathVariable final Long distributionSetTypeId) { + public ResponseEntity> getOptionalModules( + @PathVariable("distributionSetTypeId") final Long distributionSetTypeId) { final DistributionSetType foundType = findDistributionSetTypeWithExceptionIfNotFound(distributionSetTypeId); - final SoftwareModuleTypesRest rest = new SoftwareModuleTypesRest(); - - rest.addAll(SoftwareModuleTypeMapper.toListResponse(foundType.getOptionalModuleTypes())); - return new ResponseEntity<>(rest, HttpStatus.OK); + return new ResponseEntity<>(MgmtSoftwareModuleTypeMapper.toListResponse(foundType.getOptionalModuleTypes()), + HttpStatus.OK); } @Override - public ResponseEntity removeMandatoryModule(@PathVariable final Long distributionSetTypeId, - @PathVariable final Long softwareModuleTypeId) { + public ResponseEntity removeMandatoryModule( + @PathVariable("distributionSetTypeId") final Long distributionSetTypeId, + @PathVariable("softwareModuleTypeId") final Long softwareModuleTypeId) { final DistributionSetType foundType = findDistributionSetTypeWithExceptionIfNotFound(distributionSetTypeId); @@ -213,8 +215,9 @@ public class DistributionSetTypeResource implements DistributionSetTypeRestApi { } @Override - public ResponseEntity removeOptionalModule(@PathVariable final Long distributionSetTypeId, - @PathVariable final Long softwareModuleTypeId) { + public ResponseEntity removeOptionalModule( + @PathVariable("distributionSetTypeId") final Long distributionSetTypeId, + @PathVariable("softwareModuleTypeId") final Long softwareModuleTypeId) { final DistributionSetType foundType = findDistributionSetTypeWithExceptionIfNotFound(distributionSetTypeId); final SoftwareModuleType foundSmType = findSoftwareModuleTypeWithExceptionIfNotFound(softwareModuleTypeId); @@ -232,8 +235,8 @@ public class DistributionSetTypeResource implements DistributionSetTypeRestApi { } @Override - public ResponseEntity addMandatoryModule(@PathVariable final Long distributionSetTypeId, - @RequestBody final IdRest smtId) { + public ResponseEntity addMandatoryModule( + @PathVariable("distributionSetTypeId") final Long distributionSetTypeId, @RequestBody final MgmtId smtId) { final DistributionSetType foundType = findDistributionSetTypeWithExceptionIfNotFound(distributionSetTypeId); @@ -247,8 +250,8 @@ public class DistributionSetTypeResource implements DistributionSetTypeRestApi { } @Override - public ResponseEntity addOptionalModule(@PathVariable final Long distributionSetTypeId, - @RequestBody final IdRest smtId) { + public ResponseEntity addOptionalModule( + @PathVariable("distributionSetTypeId") final Long distributionSetTypeId, @RequestBody final MgmtId smtId) { final DistributionSetType foundType = findDistributionSetTypeWithExceptionIfNotFound(distributionSetTypeId); diff --git a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/DownloadArtifactResource.java b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDownloadArtifactResource.java similarity index 74% rename from hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/DownloadArtifactResource.java rename to hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDownloadArtifactResource.java index 00f8f4756..dad43bf00 100644 --- a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/DownloadArtifactResource.java +++ b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDownloadArtifactResource.java @@ -6,34 +6,36 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource; +package org.eclipse.hawkbit.mgmt.rest.resource; + +import java.io.InputStream; import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; import org.eclipse.hawkbit.artifact.repository.model.DbArtifact; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtDownloadArtifactRestApi; import org.eclipse.hawkbit.repository.ArtifactManagement; import org.eclipse.hawkbit.repository.SoftwareManagement; import org.eclipse.hawkbit.repository.exception.EntityNotFoundException; import org.eclipse.hawkbit.repository.model.LocalArtifact; import org.eclipse.hawkbit.repository.model.SoftwareModule; -import org.eclipse.hawkbit.rest.resource.helper.RestResourceConversionHelper; +import org.eclipse.hawkbit.rest.util.RequestResponseContextHolder; +import org.eclipse.hawkbit.rest.util.RestResourceConversionHelper; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Scope; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.context.WebApplicationContext; /** - * @author Jonathan Knoblauch * */ @RestController -@RequestMapping(RestConstants.SOFTWAREMODULE_V1_REQUEST_MAPPING) -public class DownloadArtifactResource { +@Scope(value = WebApplicationContext.SCOPE_REQUEST) +public class MgmtDownloadArtifactResource implements MgmtDownloadArtifactRestApi { @Autowired private SoftwareManagement softwareManagement; @@ -41,6 +43,9 @@ public class DownloadArtifactResource { @Autowired private ArtifactManagement artifactManagement; + @Autowired + private RequestResponseContextHolder requestResponseContextHolder; + /** * Handles the GET request for downloading an artifact. * @@ -48,18 +53,13 @@ public class DownloadArtifactResource { * of the parent SoftwareModule * @param artifactId * of the related LocalArtifact - * @param servletResponse - * of the servlet - * @param request - * of the client * * @return responseEntity with status ok if successful */ - @RequestMapping(method = RequestMethod.GET, value = "/{softwareModuleId}/artifacts/{artifactId}/download") + @Override @ResponseBody - public ResponseEntity downloadArtifact(@PathVariable("softwareModuleId") final Long softwareModuleId, - @PathVariable("artifactId") final Long artifactId, final HttpServletResponse servletResponse, - final HttpServletRequest request) { + public ResponseEntity downloadArtifact(@PathVariable("softwareModuleId") final Long softwareModuleId, + @PathVariable("artifactId") final Long artifactId) { final SoftwareModule module = findSoftwareModuleWithExceptionIfNotFound(softwareModuleId, artifactId); if (null == module || !module.getLocalArtifact(artifactId).isPresent()) { @@ -68,13 +68,14 @@ public class DownloadArtifactResource { final LocalArtifact artifact = module.getLocalArtifact(artifactId).get(); final DbArtifact file = artifactManagement.loadLocalArtifactBinary(artifact); - + final HttpServletRequest request = requestResponseContextHolder.getHttpServletRequest(); final String ifMatch = request.getHeader("If-Match"); if (ifMatch != null && !RestResourceConversionHelper.matchesHttpHeader(ifMatch, artifact.getSha1Hash())) { return new ResponseEntity<>(HttpStatus.PRECONDITION_FAILED); } - return RestResourceConversionHelper.writeFileResponse(artifact, servletResponse, request, file); + return RestResourceConversionHelper.writeFileResponse(artifact, + requestResponseContextHolder.getHttpServletResponse(), request, file); } diff --git a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/DownloadResource.java b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDownloadResource.java similarity index 81% rename from hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/DownloadResource.java rename to hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDownloadResource.java index 14b1dcbc6..87a215183 100644 --- a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/DownloadResource.java +++ b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDownloadResource.java @@ -6,30 +6,30 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource; +package org.eclipse.hawkbit.mgmt.rest.resource; import java.io.IOException; -import javax.servlet.http.HttpServletResponse; - import org.apache.commons.io.IOUtils; import org.eclipse.hawkbit.artifact.repository.ArtifactRepository; import org.eclipse.hawkbit.artifact.repository.model.DbArtifact; import org.eclipse.hawkbit.cache.CacheConstants; import org.eclipse.hawkbit.cache.DownloadArtifactCache; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtDownloadRestApi; +import org.eclipse.hawkbit.rest.util.RequestResponseContextHolder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.cache.Cache; import org.springframework.cache.Cache.ValueWrapper; +import org.springframework.context.annotation.Scope; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.context.WebApplicationContext; /** * A resource for download artifacts. @@ -37,11 +37,11 @@ import org.springframework.web.bind.annotation.RestController; * * */ -@RequestMapping(RestConstants.DOWNLOAD_ID_V1_REQUEST_MAPPING_BASE) @RestController -public class DownloadResource { +@Scope(value = WebApplicationContext.SCOPE_REQUEST) +public class MgmtDownloadResource implements MgmtDownloadRestApi { - private static final Logger LOGGER = LoggerFactory.getLogger(DownloadResource.class); + private static final Logger LOGGER = LoggerFactory.getLogger(MgmtDownloadResource.class); @Autowired private ArtifactRepository artifactRepository; @@ -50,20 +50,20 @@ public class DownloadResource { @Qualifier(CacheConstants.DOWNLOAD_ID_CACHE) private Cache cache; + @Autowired + private RequestResponseContextHolder requestResponseContextHolder; + /** * Handles the GET request for downloading an artifact. * * @param downloadId * the generated download id - * @param response - * of the servlet * @return {@link ResponseEntity} with status {@link HttpStatus#OK} if * successful */ - @RequestMapping(method = RequestMethod.GET, value = RestConstants.DOWNLOAD_ID_V1_REQUEST_MAPPING) + @Override @ResponseBody - public ResponseEntity downloadArtifactByDownloadId(@PathVariable final String downloadId, - final HttpServletResponse response) { + public ResponseEntity downloadArtifactByDownloadId(@PathVariable("downloadId") final String downloadId) { try { final ValueWrapper cacheWrapper = cache.get(downloadId); if (cacheWrapper == null) { @@ -89,7 +89,8 @@ public class DownloadResource { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } try { - IOUtils.copy(artifact.getFileInputStream(), response.getOutputStream()); + IOUtils.copy(artifact.getFileInputStream(), + requestResponseContextHolder.getHttpServletResponse().getOutputStream()); } catch (final IOException e) { LOGGER.error("Cannot copy streams", e); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); diff --git a/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtRestModelMapper.java b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtRestModelMapper.java new file mode 100644 index 000000000..deee0e461 --- /dev/null +++ b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtRestModelMapper.java @@ -0,0 +1,81 @@ +/** + * 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.mgmt.rest.resource; + +import org.eclipse.hawkbit.mgmt.json.model.MgmtBaseEntity; +import org.eclipse.hawkbit.mgmt.json.model.MgmtNamedEntity; +import org.eclipse.hawkbit.mgmt.json.model.distributionset.MgmtActionType; +import org.eclipse.hawkbit.repository.model.Action.ActionType; +import org.eclipse.hawkbit.repository.model.NamedEntity; +import org.eclipse.hawkbit.repository.model.TenantAwareBaseEntity; + +/** + * A mapper which maps repository model to RESTful model representation and + * back. + * + * + * + * + */ +final class MgmtRestModelMapper { + + // private constructor, utility class + private MgmtRestModelMapper() { + + } + + static void mapBaseToBase(final MgmtBaseEntity response, final TenantAwareBaseEntity base) { + response.setCreatedBy(base.getCreatedBy()); + response.setLastModifiedBy(base.getLastModifiedBy()); + if (base.getCreatedAt() != null) { + response.setCreatedAt(base.getCreatedAt()); + } + if (base.getLastModifiedAt() != null) { + response.setLastModifiedAt(base.getLastModifiedAt()); + } + } + + static void mapNamedToNamed(final MgmtNamedEntity response, final NamedEntity base) { + mapBaseToBase(response, base); + + response.setName(base.getName()); + response.setDescription(base.getDescription()); + } + + /** + * Convert a action rest type to a action repository type. + * + * @param actionTypeRest + * the rest type + * @return or the action repository type + */ + /** + * Convert a action rest type to a action repository type. + * + * @param actionTypeRest + * the rest type + * @return or the action repository type + */ + public static ActionType convertActionType(final MgmtActionType actionTypeRest) { + if (actionTypeRest == null) { + return null; + } + + switch (actionTypeRest) { + case SOFT: + return ActionType.SOFT; + case FORCED: + return ActionType.FORCED; + case TIMEFORCED: + return ActionType.TIMEFORCED; + default: + throw new IllegalStateException("Action Type is not supported"); + } + } +} diff --git a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/RolloutMapper.java b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtRolloutMapper.java similarity index 67% rename from hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/RolloutMapper.java rename to hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtRolloutMapper.java index c6be219ba..4dcaf0bf1 100644 --- a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/RolloutMapper.java +++ b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtRolloutMapper.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource; +package org.eclipse.hawkbit.mgmt.rest.resource; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; @@ -14,6 +14,14 @@ import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; import java.util.ArrayList; import java.util.List; +import org.eclipse.hawkbit.mgmt.json.model.rollout.MgmtRolloutCondition.Condition; +import org.eclipse.hawkbit.mgmt.json.model.rollout.MgmtRolloutErrorAction.ErrorAction; +import org.eclipse.hawkbit.mgmt.json.model.rollout.MgmtRolloutResponseBody; +import org.eclipse.hawkbit.mgmt.json.model.rollout.MgmtRolloutRestRequestBody; +import org.eclipse.hawkbit.mgmt.json.model.rollout.MgmtRolloutSuccessAction.SuccessAction; +import org.eclipse.hawkbit.mgmt.json.model.rolloutgroup.MgmtRolloutGroupResponseBody; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtRolloutRestApi; import org.eclipse.hawkbit.repository.model.Action.ActionType; import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.Rollout; @@ -23,14 +31,6 @@ import org.eclipse.hawkbit.repository.model.RolloutGroup.RolloutGroupErrorCondit import org.eclipse.hawkbit.repository.model.RolloutGroup.RolloutGroupSuccessAction; import org.eclipse.hawkbit.repository.model.RolloutGroup.RolloutGroupSuccessCondition; import org.eclipse.hawkbit.repository.model.TotalTargetCountStatus; -import org.eclipse.hawkbit.rest.resource.api.RolloutRestApi; -import org.eclipse.hawkbit.rest.resource.helper.RestResourceConversionHelper; -import org.eclipse.hawkbit.rest.resource.model.rollout.RolloutCondition.Condition; -import org.eclipse.hawkbit.rest.resource.model.rollout.RolloutErrorAction.ErrorAction; -import org.eclipse.hawkbit.rest.resource.model.rollout.RolloutResponseBody; -import org.eclipse.hawkbit.rest.resource.model.rollout.RolloutRestRequestBody; -import org.eclipse.hawkbit.rest.resource.model.rollout.RolloutSuccessAction.SuccessAction; -import org.eclipse.hawkbit.rest.resource.model.rolloutgroup.RolloutGroupResponseBody; /** * A mapper which maps repository model to RESTful model representation and @@ -38,22 +38,22 @@ import org.eclipse.hawkbit.rest.resource.model.rolloutgroup.RolloutGroupResponse * * */ -final class RolloutMapper { +final class MgmtRolloutMapper { private static final String NOT_SUPPORTED = " is not supported"; - private RolloutMapper() { + private MgmtRolloutMapper() { // Utility class } - static List toResponseRollout(final List rollouts) { - final List result = new ArrayList<>(rollouts.size()); + static List toResponseRollout(final List rollouts) { + final List result = new ArrayList<>(rollouts.size()); rollouts.forEach(r -> result.add(toResponseRollout(r))); return result; } - static RolloutResponseBody toResponseRollout(final Rollout rollout) { - final RolloutResponseBody body = new RolloutResponseBody(); + static MgmtRolloutResponseBody toResponseRollout(final Rollout rollout) { + final MgmtRolloutResponseBody body = new MgmtRolloutResponseBody(); body.setCreatedAt(rollout.getCreatedAt()); body.setCreatedBy(rollout.getCreatedBy()); body.setDescription(rollout.getDescription()); @@ -71,25 +71,26 @@ final class RolloutMapper { rollout.getTotalTargetCountStatus().getTotalTargetCountByStatus(status)); } - body.add(linkTo(methodOn(RolloutRestApi.class).getRollout(rollout.getId())).withRel("self")); - body.add(linkTo(methodOn(RolloutRestApi.class).start(rollout.getId(), false)).withRel("start")); - body.add(linkTo(methodOn(RolloutRestApi.class).start(rollout.getId(), true)).withRel("startAsync")); - body.add(linkTo(methodOn(RolloutRestApi.class).pause(rollout.getId())).withRel("pause")); - body.add(linkTo(methodOn(RolloutRestApi.class).resume(rollout.getId())).withRel("resume")); - body.add(linkTo(methodOn(RolloutRestApi.class).getRolloutGroups(rollout.getId(), - Integer.parseInt(RestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET), - Integer.parseInt(RestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT), null, null)).withRel("groups")); + body.add(linkTo(methodOn(MgmtRolloutRestApi.class).getRollout(rollout.getId())).withRel("self")); + body.add(linkTo(methodOn(MgmtRolloutRestApi.class).start(rollout.getId(), false)).withRel("start")); + body.add(linkTo(methodOn(MgmtRolloutRestApi.class).start(rollout.getId(), true)).withRel("startAsync")); + body.add(linkTo(methodOn(MgmtRolloutRestApi.class).pause(rollout.getId())).withRel("pause")); + body.add(linkTo(methodOn(MgmtRolloutRestApi.class).resume(rollout.getId())).withRel("resume")); + body.add(linkTo(methodOn(MgmtRolloutRestApi.class).getRolloutGroups(rollout.getId(), + Integer.parseInt(MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET), + Integer.parseInt(MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT), null, null)) + .withRel("groups")); return body; } - static Rollout fromRequest(final RolloutRestRequestBody restRequest, final DistributionSet distributionSet, + static Rollout fromRequest(final MgmtRolloutRestRequestBody restRequest, final DistributionSet distributionSet, final String filterQuery) { final Rollout rollout = new Rollout(); rollout.setName(restRequest.getName()); rollout.setDescription(restRequest.getDescription()); rollout.setDistributionSet(distributionSet); rollout.setTargetFilterQuery(filterQuery); - final ActionType convertActionType = RestResourceConversionHelper.convertActionType(restRequest.getType()); + final ActionType convertActionType = MgmtRestModelMapper.convertActionType(restRequest.getType()); if (convertActionType != null) { rollout.setActionType(convertActionType); } @@ -100,14 +101,14 @@ final class RolloutMapper { return rollout; } - static List toResponseRolloutGroup(final List rollouts) { - final List result = new ArrayList<>(rollouts.size()); + static List toResponseRolloutGroup(final List rollouts) { + final List result = new ArrayList<>(rollouts.size()); rollouts.forEach(r -> result.add(toResponseRolloutGroup(r))); return result; } - static RolloutGroupResponseBody toResponseRolloutGroup(final RolloutGroup rolloutGroup) { - final RolloutGroupResponseBody body = new RolloutGroupResponseBody(); + static MgmtRolloutGroupResponseBody toResponseRolloutGroup(final RolloutGroup rolloutGroup) { + final MgmtRolloutGroupResponseBody body = new MgmtRolloutGroupResponseBody(); body.setCreatedAt(rolloutGroup.getCreatedAt()); body.setCreatedBy(rolloutGroup.getCreatedBy()); body.setDescription(rolloutGroup.getDescription()); @@ -116,9 +117,8 @@ final class RolloutMapper { body.setName(rolloutGroup.getName()); body.setRolloutGroupId(rolloutGroup.getId()); body.setStatus(rolloutGroup.getStatus().toString().toLowerCase()); - body.add(linkTo( - methodOn(RolloutRestApi.class).getRolloutGroup(rolloutGroup.getRollout().getId(), rolloutGroup.getId())) - .withRel("self")); + body.add(linkTo(methodOn(MgmtRolloutRestApi.class).getRolloutGroup(rolloutGroup.getRollout().getId(), + rolloutGroup.getId())).withRel("self")); return body; } diff --git a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/RolloutResource.java b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtRolloutResource.java similarity index 64% rename from hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/RolloutResource.java rename to hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtRolloutResource.java index e00d07191..37d5c6fdc 100644 --- a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/RolloutResource.java +++ b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtRolloutResource.java @@ -6,11 +6,19 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource; +package org.eclipse.hawkbit.mgmt.rest.resource; import java.util.List; +import org.eclipse.hawkbit.mgmt.json.model.PagedList; +import org.eclipse.hawkbit.mgmt.json.model.rollout.MgmtRolloutResponseBody; +import org.eclipse.hawkbit.mgmt.json.model.rollout.MgmtRolloutRestRequestBody; +import org.eclipse.hawkbit.mgmt.json.model.rolloutgroup.MgmtRolloutGroupResponseBody; +import org.eclipse.hawkbit.mgmt.json.model.target.MgmtTarget; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtRolloutRestApi; import org.eclipse.hawkbit.repository.DistributionSetManagement; +import org.eclipse.hawkbit.repository.OffsetBasedPageRequest; import org.eclipse.hawkbit.repository.RolloutFields; import org.eclipse.hawkbit.repository.RolloutGroupFields; import org.eclipse.hawkbit.repository.RolloutGroupManagement; @@ -27,14 +35,6 @@ import org.eclipse.hawkbit.repository.model.RolloutGroup.RolloutGroupSuccessActi import org.eclipse.hawkbit.repository.model.RolloutGroup.RolloutGroupSuccessCondition; import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.repository.rsql.RSQLUtility; -import org.eclipse.hawkbit.rest.resource.api.RolloutRestApi; -import org.eclipse.hawkbit.rest.resource.model.rollout.RolloutPagedList; -import org.eclipse.hawkbit.rest.resource.model.rollout.RolloutResponseBody; -import org.eclipse.hawkbit.rest.resource.model.rollout.RolloutRestRequestBody; -import org.eclipse.hawkbit.rest.resource.model.rolloutgroup.RolloutGroupPagedList; -import org.eclipse.hawkbit.rest.resource.model.rolloutgroup.RolloutGroupResponseBody; -import org.eclipse.hawkbit.rest.resource.model.target.TargetPagedList; -import org.eclipse.hawkbit.rest.resource.model.target.TargetRest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; @@ -42,7 +42,9 @@ import org.springframework.data.domain.Sort; import org.springframework.data.jpa.domain.Specification; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; /** @@ -50,7 +52,7 @@ import org.springframework.web.bind.annotation.RestController; * */ @RestController -public class RolloutResource implements RolloutRestApi { +public class MgmtRolloutResource implements MgmtRolloutRestApi { private static final String DOES_NOT_EXIST = "} does not exist"; @@ -64,8 +66,11 @@ public class RolloutResource implements RolloutRestApi { private DistributionSetManagement distributionSetManagement; @Override - public ResponseEntity getRollouts(final int pagingOffsetParam, final int pagingLimitParam, - final String sortParam, final String rsqlParam) { + public ResponseEntity> getRollouts( + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam) { final int sanitizedOffsetParam = PagingUtility.sanitizeOffsetParam(pagingOffsetParam); final int sanitizedLimitParam = PagingUtility.sanitizePageLimitParam(pagingLimitParam); @@ -81,18 +86,19 @@ public class RolloutResource implements RolloutRestApi { findModulesAll = this.rolloutManagement.findAll(pageable); } - final List rest = RolloutMapper.toResponseRollout(findModulesAll.getContent()); - return new ResponseEntity<>(new RolloutPagedList(rest, findModulesAll.getTotalElements()), HttpStatus.OK); + final List rest = MgmtRolloutMapper.toResponseRollout(findModulesAll.getContent()); + return new ResponseEntity<>(new PagedList<>(rest, findModulesAll.getTotalElements()), HttpStatus.OK); } @Override - public ResponseEntity getRollout(final Long rolloutId) { + public ResponseEntity getRollout(@PathVariable("rolloutId") final Long rolloutId) { final Rollout findRolloutById = findRolloutOrThrowException(rolloutId); - return new ResponseEntity<>(RolloutMapper.toResponseRollout(findRolloutById), HttpStatus.OK); + return new ResponseEntity<>(MgmtRolloutMapper.toResponseRollout(findRolloutById), HttpStatus.OK); } @Override - public ResponseEntity create(@RequestBody final RolloutRestRequestBody rolloutRequestBody) { + public ResponseEntity create( + @RequestBody final MgmtRolloutRestRequestBody rolloutRequestBody) { // first check the given RSQL query if it's well formed, otherwise and // exception is thrown @@ -113,20 +119,20 @@ public class RolloutResource implements RolloutRestApi { RolloutGroupErrorAction errorAction = null; String errorActionExpr = null; if (rolloutRequestBody.getSuccessCondition() != null) { - successCondition = RolloutMapper + successCondition = MgmtRolloutMapper .mapFinishCondition(rolloutRequestBody.getSuccessCondition().getCondition()); successConditionExpr = rolloutRequestBody.getSuccessCondition().getExpression(); } if (rolloutRequestBody.getSuccessAction() != null) { - successAction = RolloutMapper.map(rolloutRequestBody.getSuccessAction().getAction()); + successAction = MgmtRolloutMapper.map(rolloutRequestBody.getSuccessAction().getAction()); successActionExpr = rolloutRequestBody.getSuccessAction().getExpression(); } if (rolloutRequestBody.getErrorCondition() != null) { - errorCondition = RolloutMapper.mapErrorCondition(rolloutRequestBody.getErrorCondition().getCondition()); + errorCondition = MgmtRolloutMapper.mapErrorCondition(rolloutRequestBody.getErrorCondition().getCondition()); errorConditionExpr = rolloutRequestBody.getErrorCondition().getExpression(); } if (rolloutRequestBody.getErrorAction() != null) { - errorAction = RolloutMapper.map(rolloutRequestBody.getErrorAction().getAction()); + errorAction = MgmtRolloutMapper.map(rolloutRequestBody.getErrorAction().getAction()); errorActionExpr = rolloutRequestBody.getErrorAction().getExpression(); } @@ -135,15 +141,16 @@ public class RolloutResource implements RolloutRestApi { .successAction(successAction, successActionExpr).errorCondition(errorCondition, errorConditionExpr) .errorAction(errorAction, errorActionExpr).build(); final Rollout rollout = this.rolloutManagement.createRollout( - RolloutMapper.fromRequest(rolloutRequestBody, distributionSet, + MgmtRolloutMapper.fromRequest(rolloutRequestBody, distributionSet, rolloutRequestBody.getTargetFilterQuery()), rolloutRequestBody.getAmountGroups(), rolloutGroupConditions); - return ResponseEntity.status(HttpStatus.CREATED).body(RolloutMapper.toResponseRollout(rollout)); + return ResponseEntity.status(HttpStatus.CREATED).body(MgmtRolloutMapper.toResponseRollout(rollout)); } @Override - public ResponseEntity start(final Long rolloutId, final boolean startAsync) { + public ResponseEntity start(@PathVariable("rolloutId") final Long rolloutId, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_ASYNC, defaultValue = "false") final boolean startAsync) { final Rollout rollout = findRolloutOrThrowException(rolloutId); if (startAsync) { this.rolloutManagement.startRolloutAsync(rollout); @@ -154,22 +161,26 @@ public class RolloutResource implements RolloutRestApi { } @Override - public ResponseEntity pause(final Long rolloutId) { + public ResponseEntity pause(@PathVariable("rolloutId") final Long rolloutId) { final Rollout rollout = findRolloutOrThrowException(rolloutId); this.rolloutManagement.pauseRollout(rollout); return ResponseEntity.ok().build(); } @Override - public ResponseEntity resume(final Long rolloutId) { + public ResponseEntity resume(@PathVariable("rolloutId") final Long rolloutId) { final Rollout rollout = findRolloutOrThrowException(rolloutId); this.rolloutManagement.resumeRollout(rollout); return ResponseEntity.ok().build(); } @Override - public ResponseEntity getRolloutGroups(final Long rolloutId, final int pagingOffsetParam, - final int pagingLimitParam, final String sortParam, final String rsqlParam) { + public ResponseEntity> getRolloutGroups( + @PathVariable("rolloutId") final Long rolloutId, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam) { final Rollout rollout = findRolloutOrThrowException(rolloutId); final int sanitizedOffsetParam = PagingUtility.sanitizeOffsetParam(pagingOffsetParam); @@ -186,22 +197,26 @@ public class RolloutResource implements RolloutRestApi { findRolloutGroupsAll = this.rolloutGroupManagement.findRolloutGroupsByRolloutId(rolloutId, pageable); } - final List rest = RolloutMapper + final List rest = MgmtRolloutMapper .toResponseRolloutGroup(findRolloutGroupsAll.getContent()); - return new ResponseEntity<>(new RolloutGroupPagedList(rest, findRolloutGroupsAll.getTotalElements()), - HttpStatus.OK); + return new ResponseEntity<>(new PagedList<>(rest, findRolloutGroupsAll.getTotalElements()), HttpStatus.OK); } @Override - public ResponseEntity getRolloutGroup(final Long rolloutId, final Long groupId) { + public ResponseEntity getRolloutGroup(@PathVariable("rolloutId") final Long rolloutId, + @PathVariable("groupId") final Long groupId) { findRolloutOrThrowException(rolloutId); final RolloutGroup rolloutGroup = findRolloutGroupOrThrowException(groupId); - return ResponseEntity.ok(RolloutMapper.toResponseRolloutGroup(rolloutGroup)); + return ResponseEntity.ok(MgmtRolloutMapper.toResponseRolloutGroup(rolloutGroup)); } @Override - public ResponseEntity getRolloutGroupTargets(final Long rolloutId, final Long groupId, - final int pagingOffsetParam, final int pagingLimitParam, final String sortParam, final String rsqlParam) { + public ResponseEntity> getRolloutGroupTargets(@PathVariable("rolloutId") final Long rolloutId, + @PathVariable("groupId") final Long groupId, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam) { findRolloutOrThrowException(rolloutId); final RolloutGroup rolloutGroup = findRolloutGroupOrThrowException(groupId); @@ -221,8 +236,9 @@ public class RolloutResource implements RolloutRestApi { pageable); rolloutGroupTargets = pageTargets; } - final List rest = TargetMapper.toResponse(rolloutGroupTargets.getContent()); - return new ResponseEntity<>(new TargetPagedList(rest, rolloutGroupTargets.getTotalElements()), HttpStatus.OK); + final List rest = MgmtTargetMapper.toResponse(rolloutGroupTargets.getContent()); + return new ResponseEntity<>(new PagedList(rest, rolloutGroupTargets.getTotalElements()), + HttpStatus.OK); } private Rollout findRolloutOrThrowException(final Long rolloutId) { @@ -241,7 +257,7 @@ public class RolloutResource implements RolloutRestApi { return rolloutGroup; } - private DistributionSet findDistributionSetOrThrowException(final RolloutRestRequestBody rolloutRequestBody) { + private DistributionSet findDistributionSetOrThrowException(final MgmtRolloutRestRequestBody rolloutRequestBody) { final DistributionSet ds = this.distributionSetManagement .findDistributionSetById(rolloutRequestBody.getDistributionSetId()); if (ds == null) { diff --git a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/SoftwareModuleMapper.java b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleMapper.java similarity index 56% rename from hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/SoftwareModuleMapper.java rename to hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleMapper.java index 1a3ce603f..5ca100ca9 100644 --- a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/SoftwareModuleMapper.java +++ b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleMapper.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource; +package org.eclipse.hawkbit.mgmt.rest.resource; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; @@ -14,6 +14,14 @@ import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; import java.util.ArrayList; import java.util.List; +import org.eclipse.hawkbit.mgmt.json.model.MgmtMetadata; +import org.eclipse.hawkbit.mgmt.json.model.artifact.MgmtArtifact; +import org.eclipse.hawkbit.mgmt.json.model.artifact.MgmtArtifactHash; +import org.eclipse.hawkbit.mgmt.json.model.softwaremodule.MgmtSoftwareModule; +import org.eclipse.hawkbit.mgmt.json.model.softwaremodule.MgmtSoftwareModuleRequestBodyPost; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtSoftwareModuleRestApi; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtSoftwareModuleTypeRestApi; import org.eclipse.hawkbit.repository.SoftwareManagement; import org.eclipse.hawkbit.repository.exception.EntityNotFoundException; import org.eclipse.hawkbit.repository.model.Artifact; @@ -21,26 +29,14 @@ import org.eclipse.hawkbit.repository.model.LocalArtifact; import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.repository.model.SoftwareModuleMetadata; import org.eclipse.hawkbit.repository.model.SoftwareModuleType; -import org.eclipse.hawkbit.rest.resource.api.SoftwareModuleRestAPI; -import org.eclipse.hawkbit.rest.resource.api.SoftwareModuleTypeRestApi; -import org.eclipse.hawkbit.rest.resource.model.MetadataRest; -import org.eclipse.hawkbit.rest.resource.model.artifact.ArtifactHash; -import org.eclipse.hawkbit.rest.resource.model.artifact.ArtifactRest; -import org.eclipse.hawkbit.rest.resource.model.artifact.ArtifactsRest; -import org.eclipse.hawkbit.rest.resource.model.softwaremodule.SoftwareModuleRequestBodyPost; -import org.eclipse.hawkbit.rest.resource.model.softwaremodule.SoftwareModuleRest; -import org.eclipse.hawkbit.rest.resource.model.softwaremodule.SoftwareModulesRest; /** * A mapper which maps repository model to RESTful model representation and * back. * - * - * - * */ -public final class SoftwareModuleMapper { - private SoftwareModuleMapper() { +public final class MgmtSoftwareModuleMapper { + private MgmtSoftwareModuleMapper() { // Utility class } @@ -56,16 +52,16 @@ public final class SoftwareModuleMapper { return smType; } - static SoftwareModule fromRequest(final SoftwareModuleRequestBodyPost smsRest, + static SoftwareModule fromRequest(final MgmtSoftwareModuleRequestBodyPost smsRest, final SoftwareManagement softwareManagement) { return new SoftwareModule(getSoftwareModuleTypeFromKeyString(smsRest.getType(), softwareManagement), smsRest.getName(), smsRest.getVersion(), smsRest.getDescription(), smsRest.getVendor()); } static List fromRequestSwMetadata(final SoftwareModule sw, - final List metadata) { + final List metadata) { final List mappedList = new ArrayList<>(metadata.size()); - for (final MetadataRest metadataRest : metadata) { + for (final MgmtMetadata metadataRest : metadata) { if (metadataRest.getKey() == null) { throw new IllegalArgumentException("the key of the metadata must be present"); } @@ -74,10 +70,10 @@ public final class SoftwareModuleMapper { return mappedList; } - static List smFromRequest(final Iterable smsRest, + static List smFromRequest(final Iterable smsRest, final SoftwareManagement softwareManagement) { final List mappedList = new ArrayList<>(); - for (final SoftwareModuleRequestBodyPost smRest : smsRest) { + for (final MgmtSoftwareModuleRequestBodyPost smRest : smsRest) { mappedList.add(fromRequest(smRest, softwareManagement)); } return mappedList; @@ -90,11 +86,11 @@ public final class SoftwareModuleMapper { * the modules * @return the response */ - public static List toResponse(final List baseSoftareModules) { - final List mappedList = new ArrayList<>(); + public static List toResponse(final List baseSoftareModules) { + final List mappedList = new ArrayList<>(); if (baseSoftareModules != null) { for (final SoftwareModule target : baseSoftareModules) { - final SoftwareModuleRest response = toResponse(target); + final MgmtSoftwareModule response = toResponse(target); mappedList.add(response); } @@ -102,24 +98,24 @@ public final class SoftwareModuleMapper { return mappedList; } - static SoftwareModulesRest toResponseSoftwareModules(final Iterable softwareModules) { - final SoftwareModulesRest response = new SoftwareModulesRest(); + static List toResponseSoftwareModules(final Iterable softwareModules) { + final List response = new ArrayList<>(); for (final SoftwareModule softwareModule : softwareModules) { response.add(toResponse(softwareModule)); } return response; } - static List toResponseSwMetadata(final List metadata) { - final List mappedList = new ArrayList<>(metadata.size()); + static List toResponseSwMetadata(final List metadata) { + final List mappedList = new ArrayList<>(metadata.size()); for (final SoftwareModuleMetadata distributionSetMetadata : metadata) { mappedList.add(toResponseSwMetadata(distributionSetMetadata)); } return mappedList; } - static MetadataRest toResponseSwMetadata(final SoftwareModuleMetadata metadata) { - final MetadataRest metadataRest = new MetadataRest(); + static MgmtMetadata toResponseSwMetadata(final SoftwareModuleMetadata metadata) { + final MgmtMetadata metadataRest = new MgmtMetadata(); metadataRest.setKey(metadata.getId().getKey()); metadataRest.setValue(metadata.getValue()); return metadataRest; @@ -132,30 +128,30 @@ public final class SoftwareModuleMapper { * the sw module * @return the response */ - public static SoftwareModuleRest toResponse(final SoftwareModule baseSofwareModule) { + public static MgmtSoftwareModule toResponse(final SoftwareModule baseSofwareModule) { if (baseSofwareModule == null) { return null; } - final SoftwareModuleRest response = new SoftwareModuleRest(); - RestModelMapper.mapNamedToNamed(response, baseSofwareModule); + final MgmtSoftwareModule response = new MgmtSoftwareModule(); + MgmtRestModelMapper.mapNamedToNamed(response, baseSofwareModule); response.setModuleId(baseSofwareModule.getId()); response.setVersion(baseSofwareModule.getVersion()); response.setType(baseSofwareModule.getType().getKey()); response.setVendor(baseSofwareModule.getVendor()); - response.add(linkTo(methodOn(SoftwareModuleRestAPI.class).getArtifacts(response.getModuleId())) - .withRel(RestConstants.SOFTWAREMODULE_V1_ARTIFACT)); - response.add(linkTo(methodOn(SoftwareModuleRestAPI.class).getSoftwareModule(response.getModuleId())) + response.add(linkTo(methodOn(MgmtSoftwareModuleRestApi.class).getArtifacts(response.getModuleId())) + .withRel(MgmtRestConstants.SOFTWAREMODULE_V1_ARTIFACT)); + response.add(linkTo(methodOn(MgmtSoftwareModuleRestApi.class).getSoftwareModule(response.getModuleId())) .withRel("self")); - response.add(linkTo( - methodOn(SoftwareModuleTypeRestApi.class).getSoftwareModuleType(baseSofwareModule.getType().getId())) - .withRel(RestConstants.SOFTWAREMODULE_V1_TYPE)); + response.add(linkTo(methodOn(MgmtSoftwareModuleTypeRestApi.class) + .getSoftwareModuleType(baseSofwareModule.getType().getId())) + .withRel(MgmtRestConstants.SOFTWAREMODULE_V1_TYPE)); - response.add(linkTo(methodOn(SoftwareModuleResource.class).getMetadata(response.getModuleId(), - Integer.parseInt(RestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET), - Integer.parseInt(RestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT), null, null)) + response.add(linkTo(methodOn(MgmtSoftwareModuleResource.class).getMetadata(response.getModuleId(), + Integer.parseInt(MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET), + Integer.parseInt(MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT), null, null)) .withRel("metadata")); return response; } @@ -164,40 +160,39 @@ public final class SoftwareModuleMapper { * @param artifact * @return */ - static ArtifactRest toResponse(final Artifact artifact) { - final ArtifactRest.ArtifactType type = artifact instanceof LocalArtifact ? ArtifactRest.ArtifactType.LOCAL - : ArtifactRest.ArtifactType.EXTERNAL; + static MgmtArtifact toResponse(final Artifact artifact) { + final MgmtArtifact.ArtifactType type = artifact instanceof LocalArtifact ? MgmtArtifact.ArtifactType.LOCAL + : MgmtArtifact.ArtifactType.EXTERNAL; - final ArtifactRest artifactRest = new ArtifactRest(); + final MgmtArtifact artifactRest = new MgmtArtifact(); artifactRest.setType(type); artifactRest.setArtifactId(artifact.getId()); artifactRest.setSize(artifact.getSize()); - artifactRest.setHashes(new ArtifactHash(artifact.getSha1Hash(), artifact.getMd5Hash())); + artifactRest.setHashes(new MgmtArtifactHash(artifact.getSha1Hash(), artifact.getMd5Hash())); if (artifact instanceof LocalArtifact) { artifactRest.setProvidedFilename(((LocalArtifact) artifact).getFilename()); } - RestModelMapper.mapBaseToBase(artifactRest, artifact); + MgmtRestModelMapper.mapBaseToBase(artifactRest, artifact); - artifactRest.add(linkTo(methodOn(SoftwareModuleRestAPI.class).getArtifact(artifact.getSoftwareModule().getId(), - artifact.getId())).withRel("self")); + artifactRest.add(linkTo(methodOn(MgmtSoftwareModuleRestApi.class) + .getArtifact(artifact.getSoftwareModule().getId(), artifact.getId())).withRel("self")); if (artifact instanceof LocalArtifact) { - artifactRest.add(linkTo(methodOn(DownloadArtifactResource.class) - .downloadArtifact(artifact.getSoftwareModule().getId(), artifact.getId(), null, null)) - .withRel("download")); + artifactRest.add(linkTo(methodOn(MgmtDownloadArtifactResource.class) + .downloadArtifact(artifact.getSoftwareModule().getId(), artifact.getId())).withRel("download")); } return artifactRest; } - static ArtifactsRest artifactsToResponse(final List artifacts) { - final ArtifactsRest mappedList = new ArtifactsRest(); + static List artifactsToResponse(final List artifacts) { + final List mappedList = new ArrayList<>(); if (artifacts != null) { for (final Artifact artifact : artifacts) { - final ArtifactRest response = toResponse(artifact); + final MgmtArtifact response = toResponse(artifact); mappedList.add(response); } } diff --git a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/SoftwareModuleResource.java b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleResource.java similarity index 59% rename from hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/SoftwareModuleResource.java rename to hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleResource.java index dfbac1a6f..75abe57f4 100644 --- a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/SoftwareModuleResource.java +++ b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleResource.java @@ -6,12 +6,21 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource; +package org.eclipse.hawkbit.mgmt.rest.resource; import java.io.IOException; import java.util.List; +import org.eclipse.hawkbit.mgmt.json.model.MgmtMetadata; +import org.eclipse.hawkbit.mgmt.json.model.PagedList; +import org.eclipse.hawkbit.mgmt.json.model.artifact.MgmtArtifact; +import org.eclipse.hawkbit.mgmt.json.model.softwaremodule.MgmtSoftwareModule; +import org.eclipse.hawkbit.mgmt.json.model.softwaremodule.MgmtSoftwareModuleRequestBodyPost; +import org.eclipse.hawkbit.mgmt.json.model.softwaremodule.MgmtSoftwareModuleRequestBodyPut; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtSoftwareModuleRestApi; import org.eclipse.hawkbit.repository.ArtifactManagement; +import org.eclipse.hawkbit.repository.OffsetBasedPageRequest; import org.eclipse.hawkbit.repository.SoftwareManagement; import org.eclipse.hawkbit.repository.SoftwareModuleFields; import org.eclipse.hawkbit.repository.SoftwareModuleMetadataFields; @@ -21,16 +30,6 @@ import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.repository.model.SoftwareModuleMetadata; import org.eclipse.hawkbit.repository.model.SwMetadataCompositeKey; import org.eclipse.hawkbit.repository.rsql.RSQLUtility; -import org.eclipse.hawkbit.rest.resource.api.SoftwareModuleRestAPI; -import org.eclipse.hawkbit.rest.resource.model.MetadataRest; -import org.eclipse.hawkbit.rest.resource.model.MetadataRestPageList; -import org.eclipse.hawkbit.rest.resource.model.artifact.ArtifactRest; -import org.eclipse.hawkbit.rest.resource.model.artifact.ArtifactsRest; -import org.eclipse.hawkbit.rest.resource.model.softwaremodule.SoftwareModulePagedList; -import org.eclipse.hawkbit.rest.resource.model.softwaremodule.SoftwareModuleRequestBodyPost; -import org.eclipse.hawkbit.rest.resource.model.softwaremodule.SoftwareModuleRequestBodyPut; -import org.eclipse.hawkbit.rest.resource.model.softwaremodule.SoftwareModuleRest; -import org.eclipse.hawkbit.rest.resource.model.softwaremodule.SoftwareModulesRest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -43,6 +42,7 @@ import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; @@ -52,8 +52,8 @@ import org.springframework.web.multipart.MultipartFile; * */ @RestController -public class SoftwareModuleResource implements SoftwareModuleRestAPI { - private static final Logger LOG = LoggerFactory.getLogger(SoftwareModuleResource.class); +public class MgmtSoftwareModuleResource implements MgmtSoftwareModuleRestApi { + private static final Logger LOG = LoggerFactory.getLogger(MgmtSoftwareModuleResource.class); @Autowired private ArtifactManagement artifactManagement; @@ -62,7 +62,7 @@ public class SoftwareModuleResource implements SoftwareModuleRestAPI { private SoftwareManagement softwareManagement; @Override - public ResponseEntity uploadArtifact(@PathVariable final Long softwareModuleId, + public ResponseEntity uploadArtifact(@PathVariable("softwareModuleId") final Long softwareModuleId, @RequestParam("file") final MultipartFile file, @RequestParam(value = "filename", required = false) final String optionalFileName, @RequestParam(value = "md5sum", required = false) final String md5Sum, @@ -88,29 +88,33 @@ public class SoftwareModuleResource implements SoftwareModuleRestAPI { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } - return new ResponseEntity<>(SoftwareModuleMapper.toResponse(result), HttpStatus.CREATED); + return new ResponseEntity<>(MgmtSoftwareModuleMapper.toResponse(result), HttpStatus.CREATED); } @Override - public ResponseEntity getArtifacts(@PathVariable final Long softwareModuleId) { + @ResponseBody + public ResponseEntity> getArtifacts( + @PathVariable("softwareModuleId") final Long softwareModuleId) { final SoftwareModule module = findSoftwareModuleWithExceptionIfNotFound(softwareModuleId, null); - return new ResponseEntity<>(SoftwareModuleMapper.artifactsToResponse(module.getArtifacts()), HttpStatus.OK); + return new ResponseEntity<>(MgmtSoftwareModuleMapper.artifactsToResponse(module.getArtifacts()), HttpStatus.OK); } @Override - public ResponseEntity getArtifact(@PathVariable final Long softwareModuleId, - @PathVariable final Long artifactId) { + @ResponseBody + public ResponseEntity getArtifact(@PathVariable("softwareModuleId") final Long softwareModuleId, + @PathVariable("artifactId") final Long artifactId) { final SoftwareModule module = findSoftwareModuleWithExceptionIfNotFound(softwareModuleId, artifactId); - return new ResponseEntity<>(SoftwareModuleMapper.toResponse(module.getLocalArtifact(artifactId).get()), + return new ResponseEntity<>(MgmtSoftwareModuleMapper.toResponse(module.getLocalArtifact(artifactId).get()), HttpStatus.OK); } @Override - public ResponseEntity deleteArtifact(@PathVariable final Long softwareModuleId, - @PathVariable final Long artifactId) { + @ResponseBody + public ResponseEntity deleteArtifact(@PathVariable("softwareModuleId") final Long softwareModuleId, + @PathVariable("artifactId") final Long artifactId) { findSoftwareModuleWithExceptionIfNotFound(softwareModuleId, artifactId); artifactManagement.deleteLocalArtifact(artifactId); @@ -120,11 +124,11 @@ public class SoftwareModuleResource implements SoftwareModuleRestAPI { } @Override - public ResponseEntity getSoftwareModules( - @RequestParam(value = RestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = RestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = RestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam) { + public ResponseEntity> getSoftwareModules( + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam) { final int sanitizedOffsetParam = PagingUtility.sanitizeOffsetParam(pagingOffsetParam); final int sanitizedLimitParam = PagingUtility.sanitizePageLimitParam(pagingLimitParam); @@ -143,32 +147,34 @@ public class SoftwareModuleResource implements SoftwareModuleRestAPI { countModulesAll = softwareManagement.countSoftwareModulesAll(); } - final List rest = SoftwareModuleMapper.toResponse(findModulesAll.getContent()); - return new ResponseEntity<>(new SoftwareModulePagedList(rest, countModulesAll), HttpStatus.OK); + final List rest = MgmtSoftwareModuleMapper.toResponse(findModulesAll.getContent()); + return new ResponseEntity<>(new PagedList<>(rest, countModulesAll), HttpStatus.OK); } @Override - public ResponseEntity getSoftwareModule(@PathVariable final Long softwareModuleId) { + public ResponseEntity getSoftwareModule( + @PathVariable("softwareModuleId") final Long softwareModuleId) { final SoftwareModule findBaseSoftareModule = findSoftwareModuleWithExceptionIfNotFound(softwareModuleId, null); - return new ResponseEntity<>(SoftwareModuleMapper.toResponse(findBaseSoftareModule), HttpStatus.OK); + return new ResponseEntity<>(MgmtSoftwareModuleMapper.toResponse(findBaseSoftareModule), HttpStatus.OK); } @Override - public ResponseEntity createSoftwareModules( - @RequestBody final List softwareModules) { + public ResponseEntity> createSoftwareModules( + @RequestBody final List softwareModules) { LOG.debug("creating {} softwareModules", softwareModules.size()); final Iterable createdSoftwareModules = softwareManagement - .createSoftwareModule(SoftwareModuleMapper.smFromRequest(softwareModules, softwareManagement)); + .createSoftwareModule(MgmtSoftwareModuleMapper.smFromRequest(softwareModules, softwareManagement)); LOG.debug("{} softwareModules created, return status {}", softwareModules.size(), HttpStatus.CREATED); - return new ResponseEntity<>(SoftwareModuleMapper.toResponseSoftwareModules(createdSoftwareModules), + return new ResponseEntity<>(MgmtSoftwareModuleMapper.toResponseSoftwareModules(createdSoftwareModules), HttpStatus.CREATED); } @Override - public ResponseEntity updateSoftwareModule(@PathVariable final Long softwareModuleId, - @RequestBody final SoftwareModuleRequestBodyPut restSoftwareModule) { + public ResponseEntity updateSoftwareModule( + @PathVariable("softwareModuleId") final Long softwareModuleId, + @RequestBody final MgmtSoftwareModuleRequestBodyPut restSoftwareModule) { final SoftwareModule module = findSoftwareModuleWithExceptionIfNotFound(softwareModuleId, null); // only description and vendor can be modified @@ -180,11 +186,11 @@ public class SoftwareModuleResource implements SoftwareModuleRestAPI { } final SoftwareModule updateSoftwareModule = softwareManagement.updateSoftwareModule(module); - return new ResponseEntity<>(SoftwareModuleMapper.toResponse(updateSoftwareModule), HttpStatus.OK); + return new ResponseEntity<>(MgmtSoftwareModuleMapper.toResponse(updateSoftwareModule), HttpStatus.OK); } @Override - public ResponseEntity deleteSoftwareModule(@PathVariable final Long softwareModuleId) { + public ResponseEntity deleteSoftwareModule(@PathVariable("softwareModuleId") final Long softwareModuleId) { final SoftwareModule module = findSoftwareModuleWithExceptionIfNotFound(softwareModuleId, null); softwareManagement.deleteSoftwareModule(module); @@ -193,11 +199,12 @@ public class SoftwareModuleResource implements SoftwareModuleRestAPI { } @Override - public ResponseEntity getMetadata(@PathVariable final Long softwareModuleId, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = RestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = RestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam, - @RequestParam(value = RestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam) { + public ResponseEntity> getMetadata( + @PathVariable("softwareModuleId") final Long softwareModuleId, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam) { // check if software module exists otherwise throw exception immediately findSoftwareModuleWithExceptionIfNotFound(softwareModuleId, null); @@ -217,50 +224,47 @@ public class SoftwareModuleResource implements SoftwareModuleRestAPI { } return new ResponseEntity<>( - new MetadataRestPageList(SoftwareModuleMapper.toResponseSwMetadata(metaDataPage.getContent()), + new PagedList<>(MgmtSoftwareModuleMapper.toResponseSwMetadata(metaDataPage.getContent()), metaDataPage.getTotalElements()), HttpStatus.OK); } @Override - public ResponseEntity getMetadataValue(@PathVariable final Long softwareModuleId, - @PathVariable final String metadataKey) { - // check if distribution set exists otherwise throw exception - // immediately + public ResponseEntity getMetadataValue(@PathVariable("softwareModuleId") final Long softwareModuleId, + @PathVariable("metadataKey") final String metadataKey) { final SoftwareModule sw = findSoftwareModuleWithExceptionIfNotFound(softwareModuleId, null); - final SoftwareModuleMetadata findOne = softwareManagement.findOne(new SwMetadataCompositeKey(sw, metadataKey)); - return ResponseEntity. ok(SoftwareModuleMapper.toResponseSwMetadata(findOne)); + final SoftwareModuleMetadata findOne = softwareManagement + .findSoftwareModuleMetadata(new SwMetadataCompositeKey(sw, metadataKey)); + return ResponseEntity. ok(MgmtSoftwareModuleMapper.toResponseSwMetadata(findOne)); } @Override - public ResponseEntity updateMetadata(@PathVariable final Long softwareModuleId, - @PathVariable final String metadataKey, @RequestBody final MetadataRest metadata) { - // check if software module exists otherwise throw exception immediately + public ResponseEntity updateMetadata(@PathVariable("softwareModuleId") final Long softwareModuleId, + @PathVariable("metadataKey") final String metadataKey, @RequestBody final MgmtMetadata metadata) { final SoftwareModule sw = findSoftwareModuleWithExceptionIfNotFound(softwareModuleId, null); final SoftwareModuleMetadata updated = softwareManagement .updateSoftwareModuleMetadata(new SoftwareModuleMetadata(metadataKey, sw, metadata.getValue())); - return ResponseEntity.ok(SoftwareModuleMapper.toResponseSwMetadata(updated)); + return ResponseEntity.ok(MgmtSoftwareModuleMapper.toResponseSwMetadata(updated)); } @Override - public ResponseEntity deleteMetadata(@PathVariable final Long softwareModuleId, - @PathVariable final String metadataKey) { - // check if software module exists otherwise throw exception immediately + public ResponseEntity deleteMetadata(@PathVariable("softwareModuleId") final Long softwareModuleId, + @PathVariable("metadataKey") final String metadataKey) { final SoftwareModule sw = findSoftwareModuleWithExceptionIfNotFound(softwareModuleId, null); softwareManagement.deleteSoftwareModuleMetadata(new SwMetadataCompositeKey(sw, metadataKey)); return ResponseEntity.ok().build(); } @Override - public ResponseEntity> createMetadata(@PathVariable final Long softwareModuleId, - @RequestBody final List metadataRest) { - // check if software module exists otherwise throw exception immediately + public ResponseEntity> createMetadata( + @PathVariable("softwareModuleId") final Long softwareModuleId, + @RequestBody final List metadataRest) { final SoftwareModule sw = findSoftwareModuleWithExceptionIfNotFound(softwareModuleId, null); final List created = softwareManagement - .createSoftwareModuleMetadata(SoftwareModuleMapper.fromRequestSwMetadata(sw, metadataRest)); + .createSoftwareModuleMetadata(MgmtSoftwareModuleMapper.fromRequestSwMetadata(sw, metadataRest)); - return new ResponseEntity<>(SoftwareModuleMapper.toResponseSwMetadata(created), HttpStatus.CREATED); + return new ResponseEntity<>(MgmtSoftwareModuleMapper.toResponseSwMetadata(created), HttpStatus.CREATED); } @@ -274,4 +278,5 @@ public class SoftwareModuleResource implements SoftwareModuleRestAPI { } return module; } + } diff --git a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/SoftwareModuleTypeMapper.java b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleTypeMapper.java similarity index 59% rename from hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/SoftwareModuleTypeMapper.java rename to hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleTypeMapper.java index bd2c5f1c1..5b16436a9 100644 --- a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/SoftwareModuleTypeMapper.java +++ b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleTypeMapper.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource; +package org.eclipse.hawkbit.mgmt.rest.resource; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; @@ -15,11 +15,10 @@ import java.util.ArrayList; import java.util.Collection; import java.util.List; +import org.eclipse.hawkbit.mgmt.json.model.softwaremoduletype.MgmtSoftwareModuleType; +import org.eclipse.hawkbit.mgmt.json.model.softwaremoduletype.MgmtSoftwareModuleTypeRequestBodyPost; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtSoftwareModuleTypeRestApi; import org.eclipse.hawkbit.repository.model.SoftwareModuleType; -import org.eclipse.hawkbit.rest.resource.api.SoftwareModuleTypeRestApi; -import org.eclipse.hawkbit.rest.resource.model.softwaremoduletype.SoftwareModuleTypeRequestBodyPost; -import org.eclipse.hawkbit.rest.resource.model.softwaremoduletype.SoftwareModuleTypeRest; -import org.eclipse.hawkbit.rest.resource.model.softwaremoduletype.SoftwareModuleTypesRest; /** * A mapper which maps repository model to RESTful model representation and @@ -29,52 +28,52 @@ import org.eclipse.hawkbit.rest.resource.model.softwaremoduletype.SoftwareModule * * */ -final class SoftwareModuleTypeMapper { +final class MgmtSoftwareModuleTypeMapper { // private constructor, utility class - private SoftwareModuleTypeMapper() { + private MgmtSoftwareModuleTypeMapper() { } - static List smFromRequest(final Iterable smTypesRest) { + static List smFromRequest(final Iterable smTypesRest) { final List mappedList = new ArrayList<>(); - for (final SoftwareModuleTypeRequestBodyPost smRest : smTypesRest) { + for (final MgmtSoftwareModuleTypeRequestBodyPost smRest : smTypesRest) { mappedList.add(fromRequest(smRest)); } return mappedList; } - static SoftwareModuleType fromRequest(final SoftwareModuleTypeRequestBodyPost smsRest) { + static SoftwareModuleType fromRequest(final MgmtSoftwareModuleTypeRequestBodyPost smsRest) { return new SoftwareModuleType(smsRest.getKey(), smsRest.getName(), smsRest.getDescription(), smsRest.getMaxAssignments()); } - static SoftwareModuleTypesRest toTypesResponse(final List types) { - final SoftwareModuleTypesRest response = new SoftwareModuleTypesRest(); + static List toTypesResponse(final List types) { + final List response = new ArrayList<>(); for (final SoftwareModuleType softwareModule : types) { response.add(toResponse(softwareModule)); } return response; } - static List toListResponse(final Collection types) { - final List response = new ArrayList<>(); + static List toListResponse(final Collection types) { + final List response = new ArrayList<>(); for (final SoftwareModuleType softwareModule : types) { response.add(toResponse(softwareModule)); } return response; } - static SoftwareModuleTypeRest toResponse(final SoftwareModuleType type) { - final SoftwareModuleTypeRest result = new SoftwareModuleTypeRest(); + static MgmtSoftwareModuleType toResponse(final SoftwareModuleType type) { + final MgmtSoftwareModuleType result = new MgmtSoftwareModuleType(); - RestModelMapper.mapNamedToNamed(result, type); + MgmtRestModelMapper.mapNamedToNamed(result, type); result.setKey(type.getKey()); result.setMaxAssignments(type.getMaxAssignments()); result.setModuleId(type.getId()); - result.add(linkTo(methodOn(SoftwareModuleTypeRestApi.class).getSoftwareModuleType(result.getModuleId())) + result.add(linkTo(methodOn(MgmtSoftwareModuleTypeRestApi.class).getSoftwareModuleType(result.getModuleId())) .withRel("self")); return result; diff --git a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/SoftwareModuleTypeResource.java b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleTypeResource.java similarity index 57% rename from hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/SoftwareModuleTypeResource.java rename to hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleTypeResource.java index 4259dcc90..deba883f6 100644 --- a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/SoftwareModuleTypeResource.java +++ b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleTypeResource.java @@ -6,10 +6,17 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource; +package org.eclipse.hawkbit.mgmt.rest.resource; import java.util.List; +import org.eclipse.hawkbit.mgmt.json.model.PagedList; +import org.eclipse.hawkbit.mgmt.json.model.softwaremoduletype.MgmtSoftwareModuleType; +import org.eclipse.hawkbit.mgmt.json.model.softwaremoduletype.MgmtSoftwareModuleTypeRequestBodyPost; +import org.eclipse.hawkbit.mgmt.json.model.softwaremoduletype.MgmtSoftwareModuleTypeRequestBodyPut; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtSoftwareModuleTypeRestApi; +import org.eclipse.hawkbit.repository.OffsetBasedPageRequest; import org.eclipse.hawkbit.repository.SoftwareManagement; import org.eclipse.hawkbit.repository.SoftwareModuleTypeFields; import org.eclipse.hawkbit.repository.exception.EntityNotFoundException; @@ -17,12 +24,6 @@ import org.eclipse.hawkbit.repository.model.Artifact; import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.repository.model.SoftwareModuleType; import org.eclipse.hawkbit.repository.rsql.RSQLUtility; -import org.eclipse.hawkbit.rest.resource.api.SoftwareModuleTypeRestApi; -import org.eclipse.hawkbit.rest.resource.model.softwaremoduletype.SoftwareModuleTypePagedList; -import org.eclipse.hawkbit.rest.resource.model.softwaremoduletype.SoftwareModuleTypeRequestBodyPost; -import org.eclipse.hawkbit.rest.resource.model.softwaremoduletype.SoftwareModuleTypeRequestBodyPut; -import org.eclipse.hawkbit.rest.resource.model.softwaremoduletype.SoftwareModuleTypeRest; -import org.eclipse.hawkbit.rest.resource.model.softwaremoduletype.SoftwareModuleTypesRest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; @@ -30,6 +31,9 @@ import org.springframework.data.domain.Slice; import org.springframework.data.domain.Sort; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; /** @@ -38,13 +42,16 @@ import org.springframework.web.bind.annotation.RestController; * */ @RestController -public class SoftwareModuleTypeResource implements SoftwareModuleTypeRestApi { +public class MgmtSoftwareModuleTypeResource implements MgmtSoftwareModuleTypeRestApi { @Autowired private SoftwareManagement softwareManagement; @Override - public ResponseEntity getTypes(final int pagingOffsetParam, final int pagingLimitParam, - final String sortParam, final String rsqlParam) { + public ResponseEntity> getTypes( + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam) { final int sanitizedOffsetParam = PagingUtility.sanitizeOffsetParam(pagingOffsetParam); final int sanitizedLimitParam = PagingUtility.sanitizePageLimitParam(pagingLimitParam); @@ -63,20 +70,22 @@ public class SoftwareModuleTypeResource implements SoftwareModuleTypeRestApi { countModulesAll = this.softwareManagement.countSoftwareModuleTypesAll(); } - final List rest = SoftwareModuleTypeMapper + final List rest = MgmtSoftwareModuleTypeMapper .toListResponse(findModuleTypessAll.getContent()); - return new ResponseEntity<>(new SoftwareModuleTypePagedList(rest, countModulesAll), HttpStatus.OK); + return new ResponseEntity<>(new PagedList<>(rest, countModulesAll), HttpStatus.OK); } @Override - public ResponseEntity getSoftwareModuleType(final Long softwareModuleTypeId) { + public ResponseEntity getSoftwareModuleType( + @PathVariable("softwareModuleTypeId") final Long softwareModuleTypeId) { final SoftwareModuleType foundType = findSoftwareModuleTypeWithExceptionIfNotFound(softwareModuleTypeId); - return new ResponseEntity<>(SoftwareModuleTypeMapper.toResponse(foundType), HttpStatus.OK); + return new ResponseEntity<>(MgmtSoftwareModuleTypeMapper.toResponse(foundType), HttpStatus.OK); } @Override - public ResponseEntity deleteSoftwareModuleType(final Long softwareModuleTypeId) { + public ResponseEntity deleteSoftwareModuleType( + @PathVariable("softwareModuleTypeId") final Long softwareModuleTypeId) { final SoftwareModuleType module = findSoftwareModuleTypeWithExceptionIfNotFound(softwareModuleTypeId); this.softwareManagement.deleteSoftwareModuleType(module); @@ -85,8 +94,9 @@ public class SoftwareModuleTypeResource implements SoftwareModuleTypeRestApi { } @Override - public ResponseEntity updateSoftwareModuleType(final Long softwareModuleTypeId, - final SoftwareModuleTypeRequestBodyPut restSoftwareModuleType) { + public ResponseEntity updateSoftwareModuleType( + @PathVariable("softwareModuleTypeId") final Long softwareModuleTypeId, + @RequestBody final MgmtSoftwareModuleTypeRequestBodyPut restSoftwareModuleType) { final SoftwareModuleType type = findSoftwareModuleTypeWithExceptionIfNotFound(softwareModuleTypeId); // only description can be modified @@ -95,17 +105,17 @@ public class SoftwareModuleTypeResource implements SoftwareModuleTypeRestApi { } final SoftwareModuleType updatedSoftwareModuleType = this.softwareManagement.updateSoftwareModuleType(type); - return new ResponseEntity<>(SoftwareModuleTypeMapper.toResponse(updatedSoftwareModuleType), HttpStatus.OK); + return new ResponseEntity<>(MgmtSoftwareModuleTypeMapper.toResponse(updatedSoftwareModuleType), HttpStatus.OK); } @Override - public ResponseEntity createSoftwareModuleTypes( - final List softwareModuleTypes) { + public ResponseEntity> createSoftwareModuleTypes( + @RequestBody final List softwareModuleTypes) { final List createdSoftwareModules = this.softwareManagement - .createSoftwareModuleTypes(SoftwareModuleTypeMapper.smFromRequest(softwareModuleTypes)); + .createSoftwareModuleType(MgmtSoftwareModuleTypeMapper.smFromRequest(softwareModuleTypes)); - return new ResponseEntity<>(SoftwareModuleTypeMapper.toTypesResponse(createdSoftwareModules), + return new ResponseEntity<>(MgmtSoftwareModuleTypeMapper.toTypesResponse(createdSoftwareModules), HttpStatus.CREATED); } diff --git a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/SystemManagementResource.java b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSystemManagementResource.java similarity index 62% rename from hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/SystemManagementResource.java rename to hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSystemManagementResource.java index b3a461915..46e51f2ee 100644 --- a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/SystemManagementResource.java +++ b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSystemManagementResource.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource; +package org.eclipse.hawkbit.mgmt.rest.resource; import java.util.Collection; import java.util.Collections; @@ -14,46 +14,36 @@ import java.util.List; import java.util.stream.Collectors; import org.eclipse.hawkbit.im.authentication.SpPermission.SpringEvalExpressions; +import org.eclipse.hawkbit.mgmt.json.model.systemmanagement.MgmtSystemCache; +import org.eclipse.hawkbit.mgmt.json.model.systemmanagement.MgmtSystemStatisticsRest; +import org.eclipse.hawkbit.mgmt.json.model.systemmanagement.MgmtSystemTenantServiceUsage; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtSystemManagementRestApi; import org.eclipse.hawkbit.report.model.SystemUsageReport; import org.eclipse.hawkbit.report.model.TenantUsage; import org.eclipse.hawkbit.repository.SystemManagement; -import org.eclipse.hawkbit.repository.TenantConfigurationManagement; -import org.eclipse.hawkbit.rest.resource.model.systemmanagement.CacheRest; -import org.eclipse.hawkbit.rest.resource.model.systemmanagement.SystemStatisticsRest; -import org.eclipse.hawkbit.rest.resource.model.systemmanagement.TenantSystemUsageRest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.Cache; import org.springframework.cache.CacheManager; import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; /** * {@link SystemManagement} capabilities by REST. * - * - * - * */ @RestController -@RequestMapping(RestConstants.SYSTEM_ADMIN_MAPPING) -public class SystemManagementResource { +public class MgmtSystemManagementResource implements MgmtSystemManagementRestApi { - private static final Logger LOGGER = LoggerFactory.getLogger(SystemManagementResource.class); + private static final Logger LOGGER = LoggerFactory.getLogger(MgmtSystemManagementResource.class); @Autowired private SystemManagement systemManagement; - @Autowired - private TenantConfigurationManagement tenantConfigurationManagement; - @Autowired private CacheManager cacheManager; @@ -64,10 +54,9 @@ public class SystemManagementResource { * to delete * @return HttpStatus.OK */ - @RequestMapping(method = RequestMethod.DELETE, value = "/tenants/{tenant}") - public ResponseEntity deleteTenant(@PathVariable final String tenant) { + @Override + public ResponseEntity deleteTenant(@PathVariable("tenant") final String tenant) { systemManagement.deleteTenant(tenant); - return new ResponseEntity<>(HttpStatus.OK); } @@ -77,24 +66,23 @@ public class SystemManagementResource { * * @return system usage statistics */ - @RequestMapping(method = RequestMethod.GET, value = "/usage", produces = { "application/hal+json", - MediaType.APPLICATION_JSON_VALUE }) - public ResponseEntity getSystemUsageStats() { + @Override + public ResponseEntity getSystemUsageStats() { final SystemUsageReport report = systemManagement.getSystemUsageStatistics(); - final SystemStatisticsRest result = new SystemStatisticsRest().setOverallActions(report.getOverallActions()) - .setOverallArtifacts(report.getOverallArtifacts()) + final MgmtSystemStatisticsRest result = new MgmtSystemStatisticsRest() + .setOverallActions(report.getOverallActions()).setOverallArtifacts(report.getOverallArtifacts()) .setOverallArtifactVolumeInBytes(report.getOverallArtifactVolumeInBytes()) .setOverallTargets(report.getOverallTargets()).setOverallTenants(report.getTenants().size()); - result.setTenantStats( - report.getTenants().stream().map(tenant -> convertTenant(tenant)).collect(Collectors.toList())); + result.setTenantStats(report.getTenants().stream().map(MgmtSystemManagementResource::convertTenant) + .collect(Collectors.toList())); return ResponseEntity.ok(result); } - private static TenantSystemUsageRest convertTenant(final TenantUsage tenant) { - final TenantSystemUsageRest result = new TenantSystemUsageRest(tenant.getTenantName()); + private static MgmtSystemTenantServiceUsage convertTenant(final TenantUsage tenant) { + final MgmtSystemTenantServiceUsage result = new MgmtSystemTenantServiceUsage(tenant.getTenantName()); result.setActions(tenant.getActions()); result.setArtifacts(tenant.getArtifacts()); result.setOverallArtifactVolumeInBytes(tenant.getOverallArtifactVolumeInBytes()); @@ -104,16 +92,16 @@ public class SystemManagementResource { } /** - * Returns a list of all caches containing currently. + * Returns a list of all caches. * * @return a list of caches for all tenants */ - @RequestMapping(method = RequestMethod.GET, value = "/caches") + @Override @PreAuthorize(SpringEvalExpressions.HAS_AUTH_SYSTEM_ADMIN) - public ResponseEntity> getCaches() { + public ResponseEntity> getCaches() { final Collection cacheNames = cacheManager.getCacheNames(); - return ResponseEntity.ok(cacheNames.stream().map(cacheName -> cacheManager.getCache(cacheName)) - .map(cache -> cacheRest(cache)).collect(Collectors.toList())); + return ResponseEntity + .ok(cacheNames.stream().map(cacheManager::getCache).map(this::cacheRest).collect(Collectors.toList())); } /** @@ -121,8 +109,8 @@ public class SystemManagementResource { * * @return a list of cache names which has been invalidated */ - @RequestMapping(method = RequestMethod.DELETE, value = "/caches") @PreAuthorize(SpringEvalExpressions.HAS_AUTH_SYSTEM_ADMIN) + @Override public ResponseEntity> invalidateCaches() { final Collection cacheNames = cacheManager.getCacheNames(); LOGGER.info("Invalidating caches {}", cacheNames); @@ -130,20 +118,20 @@ public class SystemManagementResource { return ResponseEntity.ok(cacheNames); } - private CacheRest cacheRest(final Cache cache) { + private MgmtSystemCache cacheRest(final Cache cache) { final Object nativeCache = cache.getNativeCache(); if (nativeCache instanceof com.google.common.cache.Cache) { return guavaCache(cache, nativeCache); } else { - return new CacheRest(cache.getName(), Collections.emptyList()); + return new MgmtSystemCache(cache.getName(), Collections.emptyList()); } } @SuppressWarnings("unchecked") - private CacheRest guavaCache(final Cache cache, final Object nativeCache) { + private MgmtSystemCache guavaCache(final Cache cache, final Object nativeCache) { final com.google.common.cache.Cache guavaCache = (com.google.common.cache.Cache) nativeCache; final List keys = guavaCache.asMap().keySet().stream().map(key -> key.toString()) .collect(Collectors.toList()); - return new CacheRest(cache.getName(), keys); + return new MgmtSystemCache(cache.getName(), keys); } } diff --git a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/SystemMapper.java b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSystemMapper.java similarity index 74% rename from hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/SystemMapper.java rename to hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSystemMapper.java index 0f8119b53..d3f78fad2 100644 --- a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/SystemMapper.java +++ b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSystemMapper.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource; +package org.eclipse.hawkbit.mgmt.rest.resource; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; @@ -14,18 +14,18 @@ import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; import java.util.HashMap; import java.util.Map; +import org.eclipse.hawkbit.mgmt.json.model.system.MgmtSystemTenantConfigurationValue; import org.eclipse.hawkbit.repository.TenantConfigurationManagement; import org.eclipse.hawkbit.repository.model.TenantConfigurationValue; -import org.eclipse.hawkbit.rest.resource.model.system.TenantConfigurationValueRest; import org.eclipse.hawkbit.tenancy.configuration.TenantConfigurationKey; /** * A mapper which maps repository model to RESTful model representation and * back. */ -public class SystemMapper { +public class MgmtSystemMapper { - private SystemMapper() { + private MgmtSystemMapper() { // Utility class } @@ -34,10 +34,10 @@ public class SystemMapper { * instance of TenantConfigurationManagement * @return a map of all existing configuration values */ - public static Map toResponse( + public static Map toResponse( final TenantConfigurationManagement tenantConfigurationManagement) { - final Map configurationMap = new HashMap<>(); + final Map configurationMap = new HashMap<>(); for (final TenantConfigurationKey key : TenantConfigurationKey.values()) { configurationMap.put(key.getKeyName(), @@ -49,15 +49,15 @@ public class SystemMapper { /** * maps a TenantConfigurationValue from the repository model to a - * TenantConfigurationValueRest, the RESTful model. + * MgmtSystemTenantConfigurationValue, the RESTful model. * * @param repoConfValue * configuration value as repository model * @return configuration value as RESTful model */ - public static TenantConfigurationValueRest toResponse(final String key, + public static MgmtSystemTenantConfigurationValue toResponse(final String key, final TenantConfigurationValue repoConfValue) { - final TenantConfigurationValueRest restConfValue = new TenantConfigurationValueRest(); + final MgmtSystemTenantConfigurationValue restConfValue = new MgmtSystemTenantConfigurationValue(); restConfValue.setValue(repoConfValue.getValue()); restConfValue.setGlobal(repoConfValue.isGlobal()); @@ -66,7 +66,7 @@ public class SystemMapper { restConfValue.setLastModifiedAt(repoConfValue.getLastModifiedAt()); restConfValue.setLastModifiedBy(repoConfValue.getLastModifiedBy()); - restConfValue.add(linkTo(methodOn(SystemResource.class).getConfigurationValue(key)).withRel("self")); + restConfValue.add(linkTo(methodOn(MgmtSystemResource.class).getConfigurationValue(key)).withRel("self")); return restConfValue; } diff --git a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/SystemResource.java b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSystemResource.java similarity index 62% rename from hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/SystemResource.java rename to hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSystemResource.java index 9f2201868..24a3f275e 100644 --- a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/SystemResource.java +++ b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSystemResource.java @@ -6,61 +6,53 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource; +package org.eclipse.hawkbit.mgmt.rest.resource; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; import java.util.Map; +import org.eclipse.hawkbit.mgmt.json.model.system.MgmtSystemTenantConfigurationValue; +import org.eclipse.hawkbit.mgmt.json.model.system.MgmtSystemTenantConfigurationValueRequest; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtSystemRestApi; import org.eclipse.hawkbit.repository.TenantConfigurationManagement; import org.eclipse.hawkbit.repository.model.TenantConfigurationValue; -import org.eclipse.hawkbit.rest.resource.model.system.TenantConfigurationValueRequest; -import org.eclipse.hawkbit.rest.resource.model.system.TenantConfigurationValueRest; import org.eclipse.hawkbit.tenancy.configuration.TenantConfigurationKey; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.hateoas.ResourceSupport; import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; /** * REST Resource handling tenant specific configuration operations. - * - * - * - * */ @RestController -@RequestMapping(RestConstants.SYSTEM_V1_REQUEST_MAPPING) -public class SystemResource { +public class MgmtSystemResource implements MgmtSystemRestApi { - private static final Logger LOG = LoggerFactory.getLogger(SystemResource.class); + private static final Logger LOG = LoggerFactory.getLogger(MgmtSystemResource.class); @Autowired private TenantConfigurationManagement tenantConfigurationManagement; - @RequestMapping(method = RequestMethod.GET, produces = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }) + @Override public ResponseEntity getSystem() { final ResourceSupport resourceSupport = new ResourceSupport(); - resourceSupport.add(linkTo(methodOn(SystemResource.class).getSystemConfiguration()).withRel("configs")); + resourceSupport.add(linkTo(methodOn(MgmtSystemResource.class).getSystemConfiguration()).withRel("configs")); return ResponseEntity.ok(resourceSupport); } /** * @return a Map of all configuration values. */ - @RequestMapping(method = RequestMethod.GET, value = "/configs", produces = { "application/hal+json", - MediaType.APPLICATION_JSON_VALUE }) - public ResponseEntity> getSystemConfiguration() { - return new ResponseEntity<>(SystemMapper.toResponse(tenantConfigurationManagement), HttpStatus.OK); + @Override + public ResponseEntity> getSystemConfiguration() { + return new ResponseEntity<>(MgmtSystemMapper.toResponse(tenantConfigurationManagement), HttpStatus.OK); } /** @@ -73,9 +65,8 @@ public class SystemResource { * OK. In any failure the JsonResponseExceptionHandler is handling * the response. */ - @RequestMapping(method = RequestMethod.DELETE, value = "/configs/{keyName}", produces = { "application/hal+json", - MediaType.APPLICATION_JSON_VALUE }) - public ResponseEntity deleteConfigurationValue(@PathVariable final String keyName) { + @Override + public ResponseEntity deleteConfigurationValue(@PathVariable("keyName") final String keyName) { final TenantConfigurationKey configKey = TenantConfigurationKey.fromKeyName(keyName); @@ -95,14 +86,14 @@ public class SystemResource { * In any failure the JsonResponseExceptionHandler is handling the * response. */ - @RequestMapping(method = RequestMethod.GET, value = "/configs/{keyName}", produces = { "application/hal+json", - MediaType.APPLICATION_JSON_VALUE }) - public ResponseEntity getConfigurationValue(@PathVariable final String keyName) { + @Override + public ResponseEntity getConfigurationValue( + @PathVariable("keyName") final String keyName) { final TenantConfigurationKey configKey = TenantConfigurationKey.fromKeyName(keyName); LOG.debug("{} config value getted, return status {}", keyName, HttpStatus.OK); - return new ResponseEntity<>(SystemMapper.toResponse(configKey.getKeyName(), + return new ResponseEntity<>(MgmtSystemMapper.toResponse(configKey.getKeyName(), tenantConfigurationManagement.getConfigurationValue(configKey)), HttpStatus.OK); } @@ -118,17 +109,17 @@ public class SystemResource { * In any failure the JsonResponseExceptionHandler is handling the * response. */ - @RequestMapping(method = RequestMethod.PUT, value = "/configs/{keyName}", consumes = { "application/hal+json", - MediaType.APPLICATION_JSON_VALUE }, produces = { "application/hal+json", MediaType.APPLICATION_JSON_VALUE }) - public ResponseEntity updateConfigurationValue(@PathVariable final String keyName, - @RequestBody final TenantConfigurationValueRequest configurationValueRest) { + @Override + public ResponseEntity updateConfigurationValue( + @PathVariable("keyName") final String keyName, + @RequestBody final MgmtSystemTenantConfigurationValueRequest configurationValueRest) { final TenantConfigurationKey configKey = TenantConfigurationKey.fromKeyName(keyName); final TenantConfigurationValue updatedValue = tenantConfigurationManagement .addOrUpdateConfiguration(configKey, configurationValueRest.getValue()); - return new ResponseEntity<>(SystemMapper.toResponse(keyName, updatedValue), HttpStatus.OK); + return new ResponseEntity<>(MgmtSystemMapper.toResponse(keyName, updatedValue), HttpStatus.OK); } -} \ No newline at end of file +} diff --git a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/TagMapper.java b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTagMapper.java similarity index 60% rename from hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/TagMapper.java rename to hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTagMapper.java index b5e84abe8..3ab2016ec 100644 --- a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/TagMapper.java +++ b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTagMapper.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource; +package org.eclipse.hawkbit.mgmt.rest.resource; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; @@ -14,112 +14,111 @@ import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; import java.util.ArrayList; import java.util.List; +import org.eclipse.hawkbit.mgmt.json.model.tag.MgmtTag; +import org.eclipse.hawkbit.mgmt.json.model.tag.MgmtTagRequestBodyPut; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtDistributionSetTagRestApi; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtTargetTagRestApi; import org.eclipse.hawkbit.repository.model.DistributionSetTag; import org.eclipse.hawkbit.repository.model.Tag; import org.eclipse.hawkbit.repository.model.TargetTag; -import org.eclipse.hawkbit.rest.resource.api.DistributionSetTagRestApi; -import org.eclipse.hawkbit.rest.resource.api.TargetTagRestApi; -import org.eclipse.hawkbit.rest.resource.model.tag.TagRequestBodyPut; -import org.eclipse.hawkbit.rest.resource.model.tag.TagRest; -import org.eclipse.hawkbit.rest.resource.model.tag.TagsRest; /** * A mapper which maps repository model to RESTful model representation and * back. * */ -final class TagMapper { - private TagMapper() { +final class MgmtTagMapper { + private MgmtTagMapper() { // Utility class } - static TagsRest toResponse(final List targetTags) { - final TagsRest tagsRest = new TagsRest(); + static List toResponse(final List targetTags) { + final List tagsRest = new ArrayList<>(); if (targetTags == null) { return tagsRest; } for (final TargetTag target : targetTags) { - final TagRest response = toResponse(target); + final MgmtTag response = toResponse(target); tagsRest.add(response); } return tagsRest; } - static TagRest toResponse(final TargetTag targetTag) { - final TagRest response = new TagRest(); + static MgmtTag toResponse(final TargetTag targetTag) { + final MgmtTag response = new MgmtTag(); if (targetTag == null) { return response; } mapTag(response, targetTag); - response.add(linkTo(methodOn(TargetTagRestApi.class).getTargetTag(targetTag.getId())).withRel("self")); + response.add(linkTo(methodOn(MgmtTargetTagRestApi.class).getTargetTag(targetTag.getId())).withRel("self")); - response.add(linkTo(methodOn(TargetTagRestApi.class).getAssignedTargets(targetTag.getId())) + response.add(linkTo(methodOn(MgmtTargetTagRestApi.class).getAssignedTargets(targetTag.getId())) .withRel("assignedTargets")); return response; } - static TagsRest toResponseDistributionSetTag(final List distributionSetTags) { - final TagsRest tagsRest = new TagsRest(); + static List toResponseDistributionSetTag(final List distributionSetTags) { + final List tagsRest = new ArrayList<>(); if (distributionSetTags == null) { return tagsRest; } for (final DistributionSetTag distributionSetTag : distributionSetTags) { - final TagRest response = toResponse(distributionSetTag); + final MgmtTag response = toResponse(distributionSetTag); tagsRest.add(response); } return tagsRest; } - static TagRest toResponse(final DistributionSetTag distributionSetTag) { - final TagRest response = new TagRest(); + static MgmtTag toResponse(final DistributionSetTag distributionSetTag) { + final MgmtTag response = new MgmtTag(); if (distributionSetTag == null) { return null; } mapTag(response, distributionSetTag); - response.add(linkTo(methodOn(DistributionSetTagRestApi.class).getDistributionSetTag(distributionSetTag.getId())) + response.add(linkTo(methodOn(MgmtDistributionSetTagRestApi.class).getDistributionSetTag(distributionSetTag.getId())) .withRel("self")); response.add(linkTo( - methodOn(DistributionSetTagRestApi.class).getAssignedDistributionSets(distributionSetTag.getId())) + methodOn(MgmtDistributionSetTagRestApi.class).getAssignedDistributionSets(distributionSetTag.getId())) .withRel("assignedDistributionSets")); return response; } - static List mapTargeTagFromRequest(final Iterable tags) { + static List mapTargeTagFromRequest(final Iterable tags) { final List mappedList = new ArrayList<>(); - for (final TagRequestBodyPut targetTagRest : tags) { + for (final MgmtTagRequestBodyPut targetTagRest : tags) { mappedList.add( new TargetTag(targetTagRest.getName(), targetTagRest.getDescription(), targetTagRest.getColour())); } return mappedList; } - static List mapDistributionSetTagFromRequest(final Iterable tags) { + static List mapDistributionSetTagFromRequest(final Iterable tags) { final List mappedList = new ArrayList<>(); - for (final TagRequestBodyPut targetTagRest : tags) { + for (final MgmtTagRequestBodyPut targetTagRest : tags) { mappedList.add(new DistributionSetTag(targetTagRest.getName(), targetTagRest.getDescription(), targetTagRest.getColour())); } return mappedList; } - private static void mapTag(final TagRest response, final Tag tag) { - RestModelMapper.mapNamedToNamed(response, tag); + private static void mapTag(final MgmtTag response, final Tag tag) { + MgmtRestModelMapper.mapNamedToNamed(response, tag); response.setTagId(tag.getId()); response.setColour(tag.getColour()); } - static void updateTag(final TagRequestBodyPut response, final Tag tag) { + static void updateTag(final MgmtTagRequestBodyPut response, final Tag tag) { if (response.getDescription() != null) { tag.setDescription(response.getDescription()); } @@ -131,7 +130,5 @@ final class TagMapper { if (response.getName() != null) { tag.setName(response.getName()); } - } - } diff --git a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/TargetMapper.java b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetMapper.java similarity index 63% rename from hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/TargetMapper.java rename to hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetMapper.java index b6c6c1539..afb941bc1 100644 --- a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/TargetMapper.java +++ b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetMapper.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource; +package org.eclipse.hawkbit.mgmt.rest.resource; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; @@ -17,30 +17,29 @@ import java.util.ArrayList; import java.util.Date; import java.util.List; +import org.eclipse.hawkbit.mgmt.json.model.MgmtPollStatus; +import org.eclipse.hawkbit.mgmt.json.model.action.MgmtAction; +import org.eclipse.hawkbit.mgmt.json.model.action.MgmtActionStatus; +import org.eclipse.hawkbit.mgmt.json.model.target.MgmtTarget; +import org.eclipse.hawkbit.mgmt.json.model.target.MgmtTargetRequestBody; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtTargetRestApi; import org.eclipse.hawkbit.repository.ActionFields; import org.eclipse.hawkbit.repository.model.Action; import org.eclipse.hawkbit.repository.model.ActionStatus; import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.repository.model.TargetInfo.PollStatus; import org.eclipse.hawkbit.repository.model.TargetUpdateStatus; -import org.eclipse.hawkbit.rest.resource.api.TargetRestApi; -import org.eclipse.hawkbit.rest.resource.model.PollStatusRest; -import org.eclipse.hawkbit.rest.resource.model.action.ActionRest; -import org.eclipse.hawkbit.rest.resource.model.action.ActionStatusRest; -import org.eclipse.hawkbit.rest.resource.model.action.ActionStatussRest; -import org.eclipse.hawkbit.rest.resource.model.action.ActionsRest; -import org.eclipse.hawkbit.rest.resource.model.target.TargetRequestBody; -import org.eclipse.hawkbit.rest.resource.model.target.TargetRest; -import org.eclipse.hawkbit.rest.resource.model.target.TargetsRest; +import org.eclipse.hawkbit.rest.data.SortDirection; /** * A mapper which maps repository model to RESTful model representation and * back. * */ -final public class TargetMapper { +public final class MgmtTargetMapper { - private TargetMapper() { + private MgmtTargetMapper() { // Utility class } @@ -50,31 +49,31 @@ final public class TargetMapper { * @param response * the target response */ - public static void addTargetLinks(final TargetRest response) { - response.add(linkTo(methodOn(TargetRestApi.class).getAssignedDistributionSet(response.getControllerId())) - .withRel(RestConstants.TARGET_V1_ASSIGNED_DISTRIBUTION_SET)); - response.add(linkTo(methodOn(TargetRestApi.class).getInstalledDistributionSet(response.getControllerId())) - .withRel(RestConstants.TARGET_V1_INSTALLED_DISTRIBUTION_SET)); - response.add(linkTo(methodOn(TargetRestApi.class).getAttributes(response.getControllerId())) - .withRel(RestConstants.TARGET_V1_ATTRIBUTES)); - response.add(linkTo(methodOn(TargetRestApi.class).getActionHistory(response.getControllerId(), 0, - RestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT_VALUE, + public static void addTargetLinks(final MgmtTarget response) { + response.add(linkTo(methodOn(MgmtTargetRestApi.class).getAssignedDistributionSet(response.getControllerId())) + .withRel(MgmtRestConstants.TARGET_V1_ASSIGNED_DISTRIBUTION_SET)); + response.add(linkTo(methodOn(MgmtTargetRestApi.class).getInstalledDistributionSet(response.getControllerId())) + .withRel(MgmtRestConstants.TARGET_V1_INSTALLED_DISTRIBUTION_SET)); + response.add(linkTo(methodOn(MgmtTargetRestApi.class).getAttributes(response.getControllerId())) + .withRel(MgmtRestConstants.TARGET_V1_ATTRIBUTES)); + response.add(linkTo(methodOn(MgmtTargetRestApi.class).getActionHistory(response.getControllerId(), 0, + MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT_VALUE, ActionFields.ID.getFieldName() + ":" + SortDirection.DESC, null)) - .withRel(RestConstants.TARGET_V1_ACTIONS)); + .withRel(MgmtRestConstants.TARGET_V1_ACTIONS)); } /** - * Add the pollstatus to a target response. + * Add the poll status to a target response. * * @param target * the target * @param targetRest * the response */ - public static void addPollStatus(final Target target, final TargetRest targetRest) { + public static void addPollStatus(final Target target, final MgmtTarget targetRest) { final PollStatus pollStatus = target.getTargetInfo().getPollStatus(); if (pollStatus != null) { - final PollStatusRest pollStatusRest = new PollStatusRest(); + final MgmtPollStatus pollStatusRest = new MgmtPollStatus(); pollStatusRest.setLastRequestAt( Date.from(pollStatus.getLastPollDate().atZone(ZoneId.systemDefault()).toInstant()).getTime()); pollStatusRest.setNextExpectedRequestAt( @@ -91,11 +90,11 @@ final public class TargetMapper { * the targets * @return the response */ - public static TargetsRest toResponseWithLinksAndPollStatus(final Iterable targets) { - final TargetsRest mappedList = new TargetsRest(); + public static List toResponseWithLinksAndPollStatus(final Iterable targets) { + final List mappedList = new ArrayList<>(); if (targets != null) { for (final Target target : targets) { - final TargetRest response = toResponse(target); + final MgmtTarget response = toResponse(target); addPollStatus(target, response); addTargetLinks(response); mappedList.add(response); @@ -111,11 +110,11 @@ final public class TargetMapper { * list of targets * @return the response */ - public static TargetsRest toResponse(final Iterable targets) { - final TargetsRest mappedList = new TargetsRest(); + public static List toResponse(final Iterable targets) { + final List mappedList = new ArrayList<>(); if (targets != null) { for (final Target target : targets) { - final TargetRest response = toResponse(target); + final MgmtTarget response = toResponse(target); mappedList.add(response); } } @@ -129,11 +128,11 @@ final public class TargetMapper { * the target * @return the response */ - public static TargetRest toResponse(final Target target) { + public static MgmtTarget toResponse(final Target target) { if (target == null) { return null; } - final TargetRest targetRest = new TargetRest(); + final MgmtTarget targetRest = new MgmtTarget(); targetRest.setControllerId(target.getControllerId()); targetRest.setDescription(target.getDescription()); targetRest.setName(target.getName()); @@ -164,32 +163,32 @@ final public class TargetMapper { targetRest.setInstalledAt(installationDate); } - targetRest.add(linkTo(methodOn(TargetRestApi.class).getTarget(target.getControllerId())).withRel("self")); + targetRest.add(linkTo(methodOn(MgmtTargetRestApi.class).getTarget(target.getControllerId())).withRel("self")); return targetRest; } - static List fromRequest(final Iterable targetsRest) { + static List fromRequest(final Iterable targetsRest) { final List mappedList = new ArrayList<>(); - for (final TargetRequestBody targetRest : targetsRest) { + for (final MgmtTargetRequestBody targetRest : targetsRest) { mappedList.add(fromRequest(targetRest)); } return mappedList; } - static Target fromRequest(final TargetRequestBody targetRest) { + static Target fromRequest(final MgmtTargetRequestBody targetRest) { final Target target = new Target(targetRest.getControllerId()); target.setDescription(targetRest.getDescription()); target.setName(targetRest.getName()); return target; } - static ActionStatussRest toActionStatusRestResponse(final Action action, final List actionStatus) { - final ActionStatussRest mappedList = new ActionStatussRest(); + static List toActionStatusRestResponse(final List actionStatus) { + final List mappedList = new ArrayList<>(); if (actionStatus != null) { for (final ActionStatus status : actionStatus) { - final ActionStatusRest response = toResponse(action, status); + final MgmtActionStatus response = toResponse(status); mappedList.add(response); } } @@ -197,30 +196,30 @@ final public class TargetMapper { return mappedList; } - static ActionRest toResponse(final String targetId, final Action action, final boolean isActive) { - final ActionRest result = new ActionRest(); + static MgmtAction toResponse(final String targetId, final Action action, final boolean isActive) { + final MgmtAction result = new MgmtAction(); result.setActionId(action.getId()); result.setType(getType(action)); if (isActive) { - result.setStatus(ActionRest.ACTION_PENDING); + result.setStatus(MgmtAction.ACTION_PENDING); } else { - result.setStatus(ActionRest.ACTION_FINISHED); + result.setStatus(MgmtAction.ACTION_FINISHED); } - RestModelMapper.mapBaseToBase(result, action); + MgmtRestModelMapper.mapBaseToBase(result, action); - result.add(linkTo(methodOn(TargetRestApi.class).getAction(targetId, action.getId())).withRel("self")); + result.add(linkTo(methodOn(MgmtTargetRestApi.class).getAction(targetId, action.getId())).withRel("self")); return result; } - static ActionsRest toResponse(final String targetId, final List actions) { - final ActionsRest mappedList = new ActionsRest(); + static List toResponse(final String targetId, final List actions) { + final List mappedList = new ArrayList<>(); for (final Action action : actions) { - final ActionRest response = toResponse(targetId, action, action.isActive()); + final MgmtAction response = toResponse(targetId, action, action.isActive()); mappedList.add(response); } return mappedList; @@ -231,22 +230,22 @@ final public class TargetMapper { switch (type) { case CANCELED: - result = ActionStatusRest.AS_CANCELED; + result = MgmtActionStatus.AS_CANCELED; break; case ERROR: - result = ActionStatusRest.AS_ERROR; + result = MgmtActionStatus.AS_ERROR; break; case FINISHED: - result = ActionStatusRest.AS_FINISHED; + result = MgmtActionStatus.AS_FINISHED; break; case RETRIEVED: - result = ActionStatusRest.AS_RETRIEVED; + result = MgmtActionStatus.AS_RETRIEVED; break; case RUNNING: - result = ActionStatusRest.AS_RUNNING; + result = MgmtActionStatus.AS_RUNNING; break; case WARNING: - result = ActionStatusRest.AS_WARNING; + result = MgmtActionStatus.AS_WARNING; break; default: return type.name().toLowerCase(); @@ -259,9 +258,9 @@ final public class TargetMapper { private static String getType(final Action action) { if (!action.isCancelingOrCanceled()) { - return ActionRest.ACTION_UPDATE; + return MgmtAction.ACTION_UPDATE; } else if (action.isCancelingOrCanceled()) { - return ActionRest.ACTION_CANCEL; + return MgmtAction.ACTION_CANCEL; } return null; @@ -293,8 +292,8 @@ final public class TargetMapper { return result; } - private static ActionStatusRest toResponse(final Action action, final ActionStatus actionStatus) { - final ActionStatusRest result = new ActionStatusRest(); + private static MgmtActionStatus toResponse(final ActionStatus actionStatus) { + final MgmtActionStatus result = new MgmtActionStatus(); result.setMessages(actionStatus.getMessages()); result.setReportedAt(actionStatus.getCreatedAt()); diff --git a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/TargetResource.java b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetResource.java similarity index 60% rename from hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/TargetResource.java rename to hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetResource.java index faa31a7cc..4a7c760e3 100644 --- a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/TargetResource.java +++ b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetResource.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource; +package org.eclipse.hawkbit.mgmt.rest.resource; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; @@ -15,9 +15,21 @@ import java.util.Iterator; import java.util.List; import java.util.Map; +import org.eclipse.hawkbit.mgmt.json.model.PagedList; +import org.eclipse.hawkbit.mgmt.json.model.action.MgmtAction; +import org.eclipse.hawkbit.mgmt.json.model.action.MgmtActionStatus; +import org.eclipse.hawkbit.mgmt.json.model.distributionset.MgmtDistributionSet; +import org.eclipse.hawkbit.mgmt.json.model.target.MgmtDistributionSetAssigment; +import org.eclipse.hawkbit.mgmt.json.model.target.MgmtTarget; +import org.eclipse.hawkbit.mgmt.json.model.target.MgmtTargetAttributes; +import org.eclipse.hawkbit.mgmt.json.model.target.MgmtTargetRequestBody; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtDistributionSetRestApi; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtTargetRestApi; import org.eclipse.hawkbit.repository.ActionFields; import org.eclipse.hawkbit.repository.ActionStatusFields; import org.eclipse.hawkbit.repository.DeploymentManagement; +import org.eclipse.hawkbit.repository.OffsetBasedPageRequest; import org.eclipse.hawkbit.repository.TargetFields; import org.eclipse.hawkbit.repository.TargetManagement; import org.eclipse.hawkbit.repository.exception.EntityNotFoundException; @@ -26,19 +38,7 @@ import org.eclipse.hawkbit.repository.model.Action.ActionType; import org.eclipse.hawkbit.repository.model.ActionStatus; import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.repository.rsql.RSQLUtility; -import org.eclipse.hawkbit.rest.resource.api.DistributionSetRestApi; -import org.eclipse.hawkbit.rest.resource.api.TargetRestApi; -import org.eclipse.hawkbit.rest.resource.helper.RestResourceConversionHelper; -import org.eclipse.hawkbit.rest.resource.model.action.ActionPagedList; -import org.eclipse.hawkbit.rest.resource.model.action.ActionRest; -import org.eclipse.hawkbit.rest.resource.model.action.ActionStatusPagedList; -import org.eclipse.hawkbit.rest.resource.model.distributionset.DistributionSetRest; -import org.eclipse.hawkbit.rest.resource.model.target.DistributionSetAssigmentRest; -import org.eclipse.hawkbit.rest.resource.model.target.TargetAttributes; -import org.eclipse.hawkbit.rest.resource.model.target.TargetPagedList; -import org.eclipse.hawkbit.rest.resource.model.target.TargetRequestBody; -import org.eclipse.hawkbit.rest.resource.model.target.TargetRest; -import org.eclipse.hawkbit.rest.resource.model.target.TargetsRest; +import org.eclipse.hawkbit.rest.data.SortDirection; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -49,6 +49,8 @@ import org.springframework.data.domain.Sort; import org.springframework.data.jpa.domain.Specification; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @@ -56,8 +58,8 @@ import org.springframework.web.bind.annotation.RestController; * REST Resource handling target CRUD operations. */ @RestController -public class TargetResource implements TargetRestApi { - private static final Logger LOG = LoggerFactory.getLogger(TargetResource.class); +public class MgmtTargetResource implements MgmtTargetRestApi { + private static final Logger LOG = LoggerFactory.getLogger(MgmtTargetResource.class); @Autowired private TargetManagement targetManagement; @@ -66,19 +68,22 @@ public class TargetResource implements TargetRestApi { private DeploymentManagement deploymentManagement; @Override - public ResponseEntity getTarget(final String targetId) { + public ResponseEntity getTarget(@PathVariable("targetId") final String targetId) { final Target findTarget = findTargetWithExceptionIfNotFound(targetId); // to single response include poll status - final TargetRest response = TargetMapper.toResponse(findTarget); - TargetMapper.addPollStatus(findTarget, response); - TargetMapper.addTargetLinks(response); + final MgmtTarget response = MgmtTargetMapper.toResponse(findTarget); + MgmtTargetMapper.addPollStatus(findTarget, response); + MgmtTargetMapper.addTargetLinks(response); return new ResponseEntity<>(response, HttpStatus.OK); } @Override - public ResponseEntity getTargets(final int pagingOffsetParam, final int pagingLimitParam, - final String sortParam, final String rsqlParam) { + public ResponseEntity> getTargets( + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam) { final int sanitizedOffsetParam = PagingUtility.sanitizeOffsetParam(pagingOffsetParam); final int sanitizedLimitParam = PagingUtility.sanitizePageLimitParam(pagingLimitParam); @@ -97,20 +102,22 @@ public class TargetResource implements TargetRestApi { countTargetsAll = this.targetManagement.countTargetsAll(); } - final List rest = TargetMapper.toResponse(findTargetsAll.getContent()); - return new ResponseEntity<>(new TargetPagedList(rest, countTargetsAll), HttpStatus.OK); + final List rest = MgmtTargetMapper.toResponse(findTargetsAll.getContent()); + return new ResponseEntity<>(new PagedList(rest, countTargetsAll), HttpStatus.OK); } @Override - public ResponseEntity createTargets(final List targets) { + public ResponseEntity> createTargets(@RequestBody final List targets) { LOG.debug("creating {} targets", targets.size()); - final Iterable createdTargets = this.targetManagement.createTargets(TargetMapper.fromRequest(targets)); + final Iterable createdTargets = this.targetManagement + .createTargets(MgmtTargetMapper.fromRequest(targets)); LOG.debug("{} targets created, return status {}", targets.size(), HttpStatus.CREATED); - return new ResponseEntity<>(TargetMapper.toResponse(createdTargets), HttpStatus.CREATED); + return new ResponseEntity<>(MgmtTargetMapper.toResponse(createdTargets), HttpStatus.CREATED); } @Override - public ResponseEntity updateTarget(final String targetId, final TargetRequestBody targetRest) { + public ResponseEntity updateTarget(@PathVariable("targetId") final String targetId, + @RequestBody final MgmtTargetRequestBody targetRest) { final Target existingTarget = findTargetWithExceptionIfNotFound(targetId); LOG.debug("updating target {}", existingTarget.getId()); if (targetRest.getDescription() != null) { @@ -121,11 +128,11 @@ public class TargetResource implements TargetRestApi { } final Target updateTarget = this.targetManagement.updateTarget(existingTarget); - return new ResponseEntity<>(TargetMapper.toResponse(updateTarget), HttpStatus.OK); + return new ResponseEntity<>(MgmtTargetMapper.toResponse(updateTarget), HttpStatus.OK); } @Override - public ResponseEntity deleteTarget(final String targetId) { + public ResponseEntity deleteTarget(@PathVariable("targetId") final String targetId) { final Target target = findTargetWithExceptionIfNotFound(targetId); this.targetManagement.deleteTargets(target.getId()); LOG.debug("{} target deleted, return status {}", targetId, HttpStatus.OK); @@ -133,22 +140,25 @@ public class TargetResource implements TargetRestApi { } @Override - public ResponseEntity getAttributes(final String targetId) { + public ResponseEntity getAttributes(@PathVariable("targetId") final String targetId) { final Target foundTarget = findTargetWithExceptionIfNotFound(targetId); final Map controllerAttributes = foundTarget.getTargetInfo().getControllerAttributes(); if (controllerAttributes.isEmpty()) { return new ResponseEntity<>(HttpStatus.NO_CONTENT); } - final TargetAttributes result = new TargetAttributes(); + final MgmtTargetAttributes result = new MgmtTargetAttributes(); result.putAll(controllerAttributes); return new ResponseEntity<>(result, HttpStatus.OK); } @Override - public ResponseEntity getActionHistory(final String targetId, final int pagingOffsetParam, - final int pagingLimitParam, final String sortParam, final String rsqlParam) { + public ResponseEntity> getActionHistory(@PathVariable("targetId") final String targetId, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam) { final Target foundTarget = findTargetWithExceptionIfNotFound(targetId); @@ -169,12 +179,13 @@ public class TargetResource implements TargetRestApi { } return new ResponseEntity<>( - new ActionPagedList(TargetMapper.toResponse(targetId, activeActions.getContent()), totalActionCount), + new PagedList<>(MgmtTargetMapper.toResponse(targetId, activeActions.getContent()), totalActionCount), HttpStatus.OK); } @Override - public ResponseEntity getAction(final String targetId, final Long actionId) { + public ResponseEntity getAction(@PathVariable("targetId") final String targetId, + @PathVariable("actionId") final Long actionId) { final Target target = findTargetWithExceptionIfNotFound(targetId); final Action action = findActionWithExceptionIfNotFound(actionId); @@ -183,28 +194,29 @@ public class TargetResource implements TargetRestApi { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } - final ActionRest result = TargetMapper.toResponse(targetId, action, action.isActive()); + final MgmtAction result = MgmtTargetMapper.toResponse(targetId, action, action.isActive()); if (!action.isCancelingOrCanceled()) { result.add(linkTo( - methodOn(DistributionSetRestApi.class).getDistributionSet(action.getDistributionSet().getId())) + methodOn(MgmtDistributionSetRestApi.class).getDistributionSet(action.getDistributionSet().getId())) .withRel("distributionset")); } else if (action.isCancelingOrCanceled()) { - result.add(linkTo(methodOn(TargetRestApi.class).getAction(targetId, action.getId())) - .withRel(RestConstants.TARGET_V1_CANCELED_ACTION)); + result.add(linkTo(methodOn(MgmtTargetRestApi.class).getAction(targetId, action.getId())) + .withRel(MgmtRestConstants.TARGET_V1_CANCELED_ACTION)); } - result.add(linkTo(methodOn(TargetRestApi.class).getActionStatusList(targetId, action.getId(), 0, - RestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT_VALUE, + result.add(linkTo(methodOn(MgmtTargetRestApi.class).getActionStatusList(targetId, action.getId(), 0, + MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT_VALUE, ActionStatusFields.ID.getFieldName() + ":" + SortDirection.DESC)) - .withRel(RestConstants.TARGET_V1_ACTION_STATUS)); + .withRel(MgmtRestConstants.TARGET_V1_ACTION_STATUS)); return new ResponseEntity<>(result, HttpStatus.OK); } @Override - public ResponseEntity cancelAction(final String targetId, final Long actionId, - @RequestParam(required = false, defaultValue = "false") final boolean force) { + public ResponseEntity cancelAction(@PathVariable("targetId") final String targetId, + @PathVariable("actionId") final Long actionId, + @RequestParam(value = "force", required = false, defaultValue = "false") final boolean force) { final Target target = findTargetWithExceptionIfNotFound(targetId); final Action action = findActionWithExceptionIfNotFound(actionId); @@ -214,14 +226,17 @@ public class TargetResource implements TargetRestApi { this.deploymentManagement.cancelAction(action, target); } // both functions will throw an exception, when action is in wrong - // state, which is mapped by ResponseExceptionHandler. + // state, which is mapped by MgmtResponseExceptionHandler. return new ResponseEntity<>(HttpStatus.NO_CONTENT); } @Override - public ResponseEntity getActionStatusList(final String targetId, final Long actionId, - final int pagingOffsetParam, final int pagingLimitParam, final String sortParam) { + public ResponseEntity> getActionStatusList( + @PathVariable("targetId") final String targetId, @PathVariable("actionId") final Long actionId, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam) { final Target target = findTargetWithExceptionIfNotFound(targetId); @@ -239,16 +254,17 @@ public class TargetResource implements TargetRestApi { new OffsetBasedPageRequest(sanitizedOffsetParam, sanitizedLimitParam, sorting), action, true); return new ResponseEntity<>( - new ActionStatusPagedList(TargetMapper.toActionStatusRestResponse(action, statusList.getContent()), + new PagedList<>(MgmtTargetMapper.toActionStatusRestResponse(statusList.getContent()), statusList.getTotalElements()), HttpStatus.OK); } @Override - public ResponseEntity getAssignedDistributionSet(final String targetId) { + public ResponseEntity getAssignedDistributionSet( + @PathVariable("targetId") final String targetId) { final Target findTarget = findTargetWithExceptionIfNotFound(targetId); - final DistributionSetRest distributionSetRest = DistributionSetMapper + final MgmtDistributionSet distributionSetRest = MgmtDistributionSetMapper .toResponse(findTarget.getAssignedDistributionSet()); final HttpStatus retStatus; if (distributionSetRest == null) { @@ -260,14 +276,14 @@ public class TargetResource implements TargetRestApi { } @Override - public ResponseEntity postAssignedDistributionSet(final String targetId, - final DistributionSetAssigmentRest dsId) { + public ResponseEntity postAssignedDistributionSet(@PathVariable("targetId") final String targetId, + @RequestBody final MgmtDistributionSetAssigment dsId) { findTargetWithExceptionIfNotFound(targetId); - final ActionType type = (dsId.getType() != null) - ? RestResourceConversionHelper.convertActionType(dsId.getType()) : ActionType.FORCED; + final ActionType type = (dsId.getType() != null) ? MgmtRestModelMapper.convertActionType(dsId.getType()) + : ActionType.FORCED; final Iterator changed = this.deploymentManagement - .assignDistributionSet(dsId.getId(), type, dsId.getForcetime(), targetId).getAssignedTargets() + .assignDistributionSet(dsId.getId(), type, dsId.getForcetime(), targetId).getAssignedEntity() .iterator(); if (changed.hasNext()) { return new ResponseEntity<>(HttpStatus.OK); @@ -280,9 +296,10 @@ public class TargetResource implements TargetRestApi { } @Override - public ResponseEntity getInstalledDistributionSet(final String targetId) { + public ResponseEntity getInstalledDistributionSet( + @PathVariable("targetId") final String targetId) { final Target findTarget = findTargetWithExceptionIfNotFound(targetId); - final DistributionSetRest distributionSetRest = DistributionSetMapper + final MgmtDistributionSet distributionSetRest = MgmtDistributionSetMapper .toResponse(findTarget.getTargetInfo().getInstalledDistributionSet()); final HttpStatus retStatus; if (distributionSetRest == null) { @@ -308,4 +325,5 @@ public class TargetResource implements TargetRestApi { } return findAction; } + } diff --git a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/TargetTagResource.java b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetTagResource.java similarity index 54% rename from hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/TargetTagResource.java rename to hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetTagResource.java index 76209a958..2bafecd8b 100644 --- a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/TargetTagResource.java +++ b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetTagResource.java @@ -6,27 +6,28 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource; +package org.eclipse.hawkbit.mgmt.rest.resource; import java.util.List; import java.util.stream.Collectors; +import org.eclipse.hawkbit.mgmt.json.model.PagedList; +import org.eclipse.hawkbit.mgmt.json.model.tag.MgmtAssignedTargetRequestBody; +import org.eclipse.hawkbit.mgmt.json.model.tag.MgmtTag; +import org.eclipse.hawkbit.mgmt.json.model.tag.MgmtTagRequestBodyPut; +import org.eclipse.hawkbit.mgmt.json.model.tag.MgmtTargetTagAssigmentResult; +import org.eclipse.hawkbit.mgmt.json.model.target.MgmtTarget; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtTargetTagRestApi; +import org.eclipse.hawkbit.repository.OffsetBasedPageRequest; import org.eclipse.hawkbit.repository.TagFields; import org.eclipse.hawkbit.repository.TagManagement; import org.eclipse.hawkbit.repository.TargetManagement; import org.eclipse.hawkbit.repository.exception.EntityNotFoundException; import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.repository.model.TargetTag; -import org.eclipse.hawkbit.repository.model.TargetTagAssigmentResult; +import org.eclipse.hawkbit.repository.model.TargetTagAssignmentResult; import org.eclipse.hawkbit.repository.rsql.RSQLUtility; -import org.eclipse.hawkbit.rest.resource.api.TargetTagRestApi; -import org.eclipse.hawkbit.rest.resource.model.tag.AssignedTargetRequestBody; -import org.eclipse.hawkbit.rest.resource.model.tag.TagPagedList; -import org.eclipse.hawkbit.rest.resource.model.tag.TagRequestBodyPut; -import org.eclipse.hawkbit.rest.resource.model.tag.TagRest; -import org.eclipse.hawkbit.rest.resource.model.tag.TagsRest; -import org.eclipse.hawkbit.rest.resource.model.tag.TargetTagAssigmentResultRest; -import org.eclipse.hawkbit.rest.resource.model.target.TargetsRest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -36,16 +37,18 @@ import org.springframework.data.domain.Slice; import org.springframework.data.domain.Sort; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; /** - * REST Resource handling for {@link Tag} CRUD operations. + * REST Resource handling for tag CRUD operations. * */ @RestController -public class TargetTagResource implements TargetTagRestApi { - private static final Logger LOG = LoggerFactory.getLogger(TargetTagResource.class); +public class MgmtTargetTagResource implements MgmtTargetTagRestApi { + private static final Logger LOG = LoggerFactory.getLogger(MgmtTargetTagResource.class); @Autowired private TagManagement tagManagement; @@ -54,8 +57,11 @@ public class TargetTagResource implements TargetTagRestApi { private TargetManagement targetManagement; @Override - public ResponseEntity getTargetTags(final int pagingOffsetParam, final int pagingLimitParam, - final String sortParam, final String rsqlParam) { + public ResponseEntity> getTargetTags( + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam, + @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SEARCH, required = false) final String rsqlParam) { final int sanitizedOffsetParam = PagingUtility.sanitizeOffsetParam(pagingOffsetParam); final int sanitizedLimitParam = PagingUtility.sanitizePageLimitParam(pagingLimitParam); @@ -76,39 +82,40 @@ public class TargetTagResource implements TargetTagRestApi { } - final List rest = TagMapper.toResponse(findTargetsAll.getContent()); - return new ResponseEntity<>(new TagPagedList(rest, countTargetsAll), HttpStatus.OK); + final List rest = MgmtTagMapper.toResponse(findTargetsAll.getContent()); + return new ResponseEntity<>(new PagedList<>(rest, countTargetsAll), HttpStatus.OK); } @Override - public ResponseEntity getTargetTag(final Long targetTagId) { + public ResponseEntity getTargetTag(@PathVariable("targetTagId") final Long targetTagId) { final TargetTag tag = findTargetTagById(targetTagId); - return new ResponseEntity<>(TagMapper.toResponse(tag), HttpStatus.OK); + return new ResponseEntity<>(MgmtTagMapper.toResponse(tag), HttpStatus.OK); } @Override - public ResponseEntity createTargetTags(@RequestBody final List tags) { + public ResponseEntity> createTargetTags(@RequestBody final List tags) { LOG.debug("creating {} target tags", tags.size()); final List createdTargetTags = this.tagManagement - .createTargetTags(TagMapper.mapTargeTagFromRequest(tags)); - return new ResponseEntity<>(TagMapper.toResponse(createdTargetTags), HttpStatus.CREATED); + .createTargetTags(MgmtTagMapper.mapTargeTagFromRequest(tags)); + return new ResponseEntity<>(MgmtTagMapper.toResponse(createdTargetTags), HttpStatus.CREATED); } @Override - public ResponseEntity updateTagretTag(final Long targetTagId, final TagRequestBodyPut restTargetTagRest) { + public ResponseEntity updateTagretTag(@PathVariable("targetTagId") final Long targetTagId, + @RequestBody final MgmtTagRequestBodyPut restTargetTagRest) { LOG.debug("update {} target tag", restTargetTagRest); final TargetTag targetTag = findTargetTagById(targetTagId); - TagMapper.updateTag(restTargetTagRest, targetTag); + MgmtTagMapper.updateTag(restTargetTagRest, targetTag); final TargetTag updateTargetTag = this.tagManagement.updateTargetTag(targetTag); LOG.debug("target tag updated"); - return new ResponseEntity<>(TagMapper.toResponse(updateTargetTag), HttpStatus.OK); + return new ResponseEntity<>(MgmtTagMapper.toResponse(updateTargetTag), HttpStatus.OK); } @Override - public ResponseEntity deleteTargetTag(final Long targetTagId) { + public ResponseEntity deleteTargetTag(@PathVariable("targetTagId") final Long targetTagId) { LOG.debug("Delete {} target tag", targetTagId); final TargetTag targetTag = findTargetTagById(targetTagId); @@ -118,39 +125,40 @@ public class TargetTagResource implements TargetTagRestApi { } @Override - public ResponseEntity getAssignedTargets(final Long targetTagId) { + public ResponseEntity> getAssignedTargets(@PathVariable("targetTagId") final Long targetTagId) { final TargetTag targetTag = findTargetTagById(targetTagId); - return new ResponseEntity<>(TargetMapper.toResponseWithLinksAndPollStatus(targetTag.getAssignedToTargets()), + return new ResponseEntity<>(MgmtTargetMapper.toResponseWithLinksAndPollStatus(targetTag.getAssignedToTargets()), HttpStatus.OK); } @Override - public ResponseEntity toggleTagAssignment(final Long targetTagId, - final List assignedTargetRequestBodies) { + public ResponseEntity toggleTagAssignment( + @PathVariable("targetTagId") final Long targetTagId, + @RequestBody final List assignedTargetRequestBodies) { LOG.debug("Toggle Target assignment {} for target tag {}", assignedTargetRequestBodies.size(), targetTagId); final TargetTag targetTag = findTargetTagById(targetTagId); - final TargetTagAssigmentResult assigmentResult = this.targetManagement + final TargetTagAssignmentResult assigmentResult = this.targetManagement .toggleTagAssignment(findTargetControllerIds(assignedTargetRequestBodies), targetTag.getName()); - final TargetTagAssigmentResultRest tagAssigmentResultRest = new TargetTagAssigmentResultRest(); - tagAssigmentResultRest.setAssignedTargets(TargetMapper.toResponse(assigmentResult.getAssignedTargets())); - tagAssigmentResultRest.setUnassignedTargets(TargetMapper.toResponse(assigmentResult.getUnassignedTargets())); + final MgmtTargetTagAssigmentResult tagAssigmentResultRest = new MgmtTargetTagAssigmentResult(); + tagAssigmentResultRest.setAssignedTargets(MgmtTargetMapper.toResponse(assigmentResult.getAssignedEntity())); + tagAssigmentResultRest.setUnassignedTargets(MgmtTargetMapper.toResponse(assigmentResult.getUnassignedEntity())); return new ResponseEntity<>(tagAssigmentResultRest, HttpStatus.OK); } @Override - public ResponseEntity assignTargets(final Long targetTagId, - final List assignedTargetRequestBodies) { + public ResponseEntity> assignTargets(@PathVariable("targetTagId") final Long targetTagId, + @RequestBody final List assignedTargetRequestBodies) { LOG.debug("Assign Targets {} for target tag {}", assignedTargetRequestBodies.size(), targetTagId); final TargetTag targetTag = findTargetTagById(targetTagId); final List assignedTarget = this.targetManagement .assignTag(findTargetControllerIds(assignedTargetRequestBodies), targetTag); - return new ResponseEntity<>(TargetMapper.toResponseWithLinksAndPollStatus(assignedTarget), HttpStatus.OK); + return new ResponseEntity<>(MgmtTargetMapper.toResponseWithLinksAndPollStatus(assignedTarget), HttpStatus.OK); } @Override - public ResponseEntity unassignTargets(final Long targetTagId) { + public ResponseEntity unassignTargets(@PathVariable("targetTagId") final Long targetTagId) { LOG.debug("Unassign all Targets for target tag {}", targetTagId); final TargetTag targetTag = findTargetTagById(targetTagId); if (targetTag.getAssignedToTargets() == null) { @@ -162,7 +170,8 @@ public class TargetTagResource implements TargetTagRestApi { } @Override - public ResponseEntity unassignTarget(final Long targetTagId, final String controllerId) { + public ResponseEntity unassignTarget(@PathVariable("targetTagId") final Long targetTagId, + @PathVariable("controllerId") final String controllerId) { LOG.debug("Unassign target {} for target tag {}", controllerId, targetTagId); final TargetTag targetTag = findTargetTagById(targetTagId); this.targetManagement.unAssignTag(controllerId, targetTag); @@ -177,8 +186,10 @@ public class TargetTagResource implements TargetTagRestApi { return tag; } - private List findTargetControllerIds(final List assignedTargetRequestBodies) { + private List findTargetControllerIds( + final List assignedTargetRequestBodies) { return assignedTargetRequestBodies.stream().map(request -> request.getControllerId()) .collect(Collectors.toList()); } + } diff --git a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/PagingUtility.java b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/PagingUtility.java similarity index 91% rename from hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/PagingUtility.java rename to hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/PagingUtility.java index ac45796e5..abd9e9ec4 100644 --- a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/PagingUtility.java +++ b/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/PagingUtility.java @@ -6,8 +6,9 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource; +package org.eclipse.hawkbit.mgmt.rest.resource; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants; import org.eclipse.hawkbit.repository.ActionFields; import org.eclipse.hawkbit.repository.ActionStatusFields; import org.eclipse.hawkbit.repository.DistributionSetFields; @@ -19,6 +20,7 @@ import org.eclipse.hawkbit.repository.SoftwareModuleFields; import org.eclipse.hawkbit.repository.SoftwareModuleMetadataFields; import org.eclipse.hawkbit.repository.SoftwareModuleTypeFields; import org.eclipse.hawkbit.repository.TargetFields; +import org.eclipse.hawkbit.rest.util.SortUtility; import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort.Direction; @@ -35,16 +37,16 @@ public final class PagingUtility { static int sanitizeOffsetParam(final int offset) { if (offset < 0) { - return Integer.parseInt(RestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET); + return Integer.parseInt(MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET); } return offset; } static int sanitizePageLimitParam(final int pageLimit) { if (pageLimit < 1) { - return Integer.parseInt(RestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT); - } else if (pageLimit > RestConstants.REQUEST_PARAMETER_PAGING_MAX_LIMIT) { - return RestConstants.REQUEST_PARAMETER_PAGING_MAX_LIMIT; + return Integer.parseInt(MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT); + } else if (pageLimit > MgmtRestConstants.REQUEST_PARAMETER_PAGING_MAX_LIMIT) { + return MgmtRestConstants.REQUEST_PARAMETER_PAGING_MAX_LIMIT; } return pageLimit; } diff --git a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/DistributionSetResourceTest.java b/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetResourceTest.java similarity index 86% rename from hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/DistributionSetResourceTest.java rename to hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetResourceTest.java index 6254da992..8cfef095e 100644 --- a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/DistributionSetResourceTest.java +++ b/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetResourceTest.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource; +package org.eclipse.hawkbit.mgmt.rest.resource; import static org.fest.assertions.api.Assertions.assertThat; import static org.hamcrest.CoreMatchers.equalTo; @@ -26,24 +26,19 @@ import java.util.Iterator; import java.util.List; import java.util.Set; -import org.eclipse.hawkbit.AbstractIntegrationTest; -import org.eclipse.hawkbit.MockMvcResultPrinter; import org.eclipse.hawkbit.TestDataUtil; import org.eclipse.hawkbit.WithUser; -import org.eclipse.hawkbit.repository.ActionRepository; -import org.eclipse.hawkbit.repository.ControllerManagement; -import org.eclipse.hawkbit.repository.DistributionSetManagement; -import org.eclipse.hawkbit.repository.SoftwareManagement; -import org.eclipse.hawkbit.repository.TargetManagement; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants; import org.eclipse.hawkbit.repository.exception.EntityNotFoundException; -import org.eclipse.hawkbit.repository.model.Action; import org.eclipse.hawkbit.repository.model.Action.Status; -import org.eclipse.hawkbit.repository.model.ActionStatus; import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.DistributionSetMetadata; import org.eclipse.hawkbit.repository.model.DsMetadataCompositeKey; import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.repository.model.Target; +import org.eclipse.hawkbit.rest.AbstractRestIntegrationTest; +import org.eclipse.hawkbit.rest.util.JsonBuilder; +import org.eclipse.hawkbit.rest.util.MockMvcResultPrinter; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; @@ -60,7 +55,7 @@ import ru.yandex.qatools.allure.annotations.Stories; @Features("Component Tests - Management API") @Stories("Distribution Set Resource") -public class DistributionSetResourceTest extends AbstractIntegrationTest { +public class MgmtDistributionSetResourceTest extends AbstractRestIntegrationTest { @Test @Description("This test verifies the call of all Software Modules that are assiged to a Distribution Set through the RESTful API.") @@ -68,7 +63,7 @@ public class DistributionSetResourceTest extends AbstractIntegrationTest { // Create DistributionSet with three software modules final DistributionSet set = TestDataUtil.generateDistributionSet("SMTest", softwareManagement, distributionSetManagement); - mvc.perform(get(RestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + set.getId() + "/assignedSM")) + mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + set.getId() + "/assignedSM")) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andExpect(jsonPath("$.size", equalTo(set.getModules().size()))); } @@ -89,7 +84,7 @@ public class DistributionSetResourceTest extends AbstractIntegrationTest { smList.put(new JSONObject().put("id", Long.valueOf(smID))); } // post assignment - mvc.perform(post(RestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + disSet.getId() + "/assignedSM") + mvc.perform(post(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + disSet.getId() + "/assignedSM") .contentType(MediaType.APPLICATION_JSON).content(smList.toString())).andDo(MockMvcResultPrinter.print()) .andExpect(status().isOk()); @@ -101,18 +96,19 @@ public class DistributionSetResourceTest extends AbstractIntegrationTest { list.put(new JSONObject().put("id", Long.valueOf(targetId))); } deploymentManagement.assignDistributionSet(disSet.getId(), knownTargetIds[0]); - mvc.perform(post(RestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + disSet.getId() + "/assignedTargets") - .contentType(MediaType.APPLICATION_JSON).content(list.toString())).andDo(MockMvcResultPrinter.print()) - .andExpect(status().isOk()).andExpect(jsonPath("$.assigned", equalTo(knownTargetIds.length - 1))) + mvc.perform( + post(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + disSet.getId() + "/assignedTargets") + .contentType(MediaType.APPLICATION_JSON).content(list.toString())) + .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) + .andExpect(jsonPath("$.assigned", equalTo(knownTargetIds.length - 1))) .andExpect(jsonPath("$.alreadyAssigned", equalTo(1))) .andExpect(jsonPath("$.total", equalTo(knownTargetIds.length))); // try to delete the Software Module from DistSet that has been assigned // to the target. - mvc.perform(delete( - RestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + disSet.getId() + "/assignedSM/" + smIDs.get(0)) - .contentType(MediaType.APPLICATION_JSON)) - .andDo(MockMvcResultPrinter.print()).andExpect(status().isLocked()) + mvc.perform(delete(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + disSet.getId() + "/assignedSM/" + + smIDs.get(0)).contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()) + .andExpect(status().isLocked()) .andExpect(jsonPath("$.errorCode", equalTo("hawkbit.server.error.entitiylocked"))); } @@ -132,7 +128,7 @@ public class DistributionSetResourceTest extends AbstractIntegrationTest { smList.put(new JSONObject().put("id", Long.valueOf(smID))); } // post assignment - mvc.perform(post(RestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + disSet.getId() + "/assignedSM") + mvc.perform(post(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + disSet.getId() + "/assignedSM") .contentType(MediaType.APPLICATION_JSON).content(smList.toString())).andDo(MockMvcResultPrinter.print()) .andExpect(status().isOk()); @@ -145,9 +141,11 @@ public class DistributionSetResourceTest extends AbstractIntegrationTest { } // assign DisSet to target and test assignment deploymentManagement.assignDistributionSet(disSet.getId(), knownTargetIds[0]); - mvc.perform(post(RestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + disSet.getId() + "/assignedTargets") - .contentType(MediaType.APPLICATION_JSON).content(list.toString())).andDo(MockMvcResultPrinter.print()) - .andExpect(status().isOk()).andExpect(jsonPath("$.assigned", equalTo(knownTargetIds.length - 1))) + mvc.perform( + post(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + disSet.getId() + "/assignedTargets") + .contentType(MediaType.APPLICATION_JSON).content(list.toString())) + .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) + .andExpect(jsonPath("$.assigned", equalTo(knownTargetIds.length - 1))) .andExpect(jsonPath("$.alreadyAssigned", equalTo(1))) .andExpect(jsonPath("$.total", equalTo(knownTargetIds.length))); @@ -161,7 +159,7 @@ public class DistributionSetResourceTest extends AbstractIntegrationTest { smList2.put(new JSONObject().put("id", Long.valueOf(smID))); } - mvc.perform(post(RestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + disSet.getId() + "/assignedSM") + mvc.perform(post(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + disSet.getId() + "/assignedSM") .contentType(MediaType.APPLICATION_JSON).content(smList2.toString())) .andDo(MockMvcResultPrinter.print()).andExpect(status().isLocked()) .andExpect(jsonPath("$.errorCode", equalTo("hawkbit.server.error.entitiylocked"))); @@ -175,7 +173,7 @@ public class DistributionSetResourceTest extends AbstractIntegrationTest { final DistributionSet disSet = TestDataUtil.generateDistributionSetWithNoSoftwareModules("Jupiter", "398,88", distributionSetManagement); // Test if size is 0 - mvc.perform(get(RestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + disSet.getId() + "/assignedSM")) + mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + disSet.getId() + "/assignedSM")) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andExpect(jsonPath("$.size", equalTo(disSet.getModules().size()))); // create Software Modules @@ -194,11 +192,11 @@ public class DistributionSetResourceTest extends AbstractIntegrationTest { list.put(new JSONObject().put("id", Long.valueOf(smID))); } // post assignment - mvc.perform(post(RestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + disSet.getId() + "/assignedSM") + mvc.perform(post(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + disSet.getId() + "/assignedSM") .contentType(MediaType.APPLICATION_JSON).content(list.toString())).andDo(MockMvcResultPrinter.print()) .andExpect(status().isOk()); // Test if size is 3 - mvc.perform(get(RestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + disSet.getId() + "/assignedSM")) + mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + disSet.getId() + "/assignedSM")) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andExpect(jsonPath("$.size", equalTo(smIDs.size()))); } @@ -211,16 +209,16 @@ public class DistributionSetResourceTest extends AbstractIntegrationTest { final DistributionSet set = TestDataUtil.generateDistributionSet("Venus", softwareManagement, distributionSetManagement); int amountOfSM = set.getModules().size(); - mvc.perform(get(RestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + set.getId() + "/assignedSM")) + mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + set.getId() + "/assignedSM")) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andExpect(jsonPath("$.size", equalTo(amountOfSM))); // test the removal of all software modules one by one for (final Iterator iter = set.getModules().iterator(); iter.hasNext();) { final Long smId = iter.next().getId(); mvc.perform(delete( - RestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + set.getId() + "/assignedSM/" + smId)) + MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + set.getId() + "/assignedSM/" + smId)) .andExpect(status().isOk()); - mvc.perform(get(RestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + set.getId() + "/assignedSM")) + mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + set.getId() + "/assignedSM")) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andExpect(jsonPath("$.size", equalTo(--amountOfSM))); } @@ -242,8 +240,8 @@ public class DistributionSetResourceTest extends AbstractIntegrationTest { // assign already one target to DS deploymentManagement.assignDistributionSet(createdDs.getId(), knownTargetIds[0]); - mvc.perform( - post(RestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + createdDs.getId() + "/assignedTargets") + mvc.perform(post( + MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + createdDs.getId() + "/assignedTargets") .contentType(MediaType.APPLICATION_JSON).content(list.toString())) .andExpect(status().isOk()).andExpect(jsonPath("$.assigned", equalTo(knownTargetIds.length - 1))) .andExpect(jsonPath("$.alreadyAssigned", equalTo(1))) @@ -263,8 +261,8 @@ public class DistributionSetResourceTest extends AbstractIntegrationTest { targetManagement.createTarget(new Target(knownTargetId)); deploymentManagement.assignDistributionSet(createdDs.getId(), knownTargetId); - mvc.perform( - get(RestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + createdDs.getId() + "/assignedTargets")) + mvc.perform(get( + MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + createdDs.getId() + "/assignedTargets")) .andExpect(status().isOk()).andExpect(jsonPath("$.size", equalTo(1))) .andExpect(jsonPath("$.content[0].controllerId", equalTo(knownTargetId))); } @@ -274,8 +272,8 @@ public class DistributionSetResourceTest extends AbstractIntegrationTest { public void getAssignedTargetsOfDistributionSetIsEmpty() throws Exception { final Set createDistributionSetsAlphabetical = createDistributionSetsAlphabetical(1); final DistributionSet createdDs = createDistributionSetsAlphabetical.iterator().next(); - mvc.perform( - get(RestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + createdDs.getId() + "/assignedTargets")) + mvc.perform(get( + MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + createdDs.getId() + "/assignedTargets")) .andExpect(status().isOk()).andExpect(jsonPath("$.size", equalTo(0))) .andExpect(jsonPath("$.total", equalTo(0))); } @@ -294,11 +292,11 @@ public class DistributionSetResourceTest extends AbstractIntegrationTest { // assign knownTargetId to distribution set deploymentManagement.assignDistributionSet(createdDs.getId(), knownTargetId); // make it in install state - sendUpdateActionStatusToTargets(controllerManagament, targetManagement, actionRepository, createdDs, - Lists.newArrayList(createTarget), Status.FINISHED, "some message"); + TestDataUtil.sendUpdateActionStatusToTargets(controllerManagament, targetManagement, actionRepository, + createdDs, Lists.newArrayList(createTarget), Status.FINISHED, "some message"); - mvc.perform( - get(RestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + createdDs.getId() + "/installedTargets")) + mvc.perform(get( + MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + createdDs.getId() + "/installedTargets")) .andExpect(status().isOk()).andExpect(jsonPath("$.size", equalTo(1))) .andExpect(jsonPath("$.content[0].controllerId", equalTo(knownTargetId))); } @@ -308,11 +306,11 @@ public class DistributionSetResourceTest extends AbstractIntegrationTest { public void getDistributionSetsWithoutAddtionalRequestParameters() throws Exception { final int sets = 5; createDistributionSetsAlphabetical(sets); - mvc.perform(get(RestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING)).andDo(MockMvcResultPrinter.print()) + mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING)).andDo(MockMvcResultPrinter.print()) .andExpect(status().isOk()) - .andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(sets))) - .andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(sets))) - .andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(sets))); + .andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(sets))) + .andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(sets))) + .andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(sets))); } @Test @@ -321,12 +319,12 @@ public class DistributionSetResourceTest extends AbstractIntegrationTest { final int sets = 5; final int limitSize = 1; createDistributionSetsAlphabetical(sets); - mvc.perform(get(RestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING) - .param(RestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(limitSize))) + mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING) + .param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(limitSize))) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) - .andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(sets))) - .andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(limitSize))) - .andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(limitSize))); + .andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(sets))) + .andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(limitSize))) + .andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(limitSize))); } @Test @@ -336,13 +334,13 @@ public class DistributionSetResourceTest extends AbstractIntegrationTest { final int offsetParam = 2; final int expectedSize = sets - offsetParam; createDistributionSetsAlphabetical(sets); - mvc.perform(get(RestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING) - .param(RestConstants.REQUEST_PARAMETER_PAGING_OFFSET, String.valueOf(offsetParam)) - .param(RestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(sets))) + mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING) + .param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, String.valueOf(offsetParam)) + .param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(sets))) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) - .andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(sets))) - .andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(expectedSize))) - .andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(expectedSize))); + .andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(sets))) + .andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(expectedSize))) + .andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(expectedSize))); } @Test @@ -394,7 +392,8 @@ public class DistributionSetResourceTest extends AbstractIntegrationTest { @WithUser(principal = "uploadTester", allSpPermissions = true) @Description("Ensures that single DS requested by ID is listed with expected payload.") public void getDistributionSet() throws Exception { - final DistributionSet set = createTestDistributionSet(softwareManagement, distributionSetManagement); + final DistributionSet set = TestDataUtil.createTestDistributionSet(softwareManagement, + distributionSetManagement); // perform request mvc.perform(get("/rest/v1/distributionsets/{dsId}", set.getId()).accept(MediaType.APPLICATION_JSON)) @@ -825,9 +824,9 @@ public class DistributionSetResourceTest extends AbstractIntegrationTest { final String rsqlFindTargetId1 = "controllerId==1"; - mvc.perform( - get(RestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + createdDs.getId() + "/assignedTargets?q=" - + rsqlFindTargetId1).contentType(MediaType.APPLICATION_JSON).content(list.toString())) + mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSET_V1_REQUEST_MAPPING + "/" + createdDs.getId() + + "/assignedTargets?q=" + rsqlFindTargetId1).contentType(MediaType.APPLICATION_JSON) + .content(list.toString())) .andExpect(status().isOk()).andExpect(jsonPath("total", equalTo(1))) .andExpect(jsonPath("size", equalTo(1))).andExpect(jsonPath("content[0].controllerId", equalTo("1"))); } @@ -864,54 +863,4 @@ public class DistributionSetResourceTest extends AbstractIntegrationTest { return created; } - public static List sendUpdateActionStatusToTargets(final ControllerManagement controllerManagament, - final TargetManagement targetManagement, final ActionRepository actionRepository, final DistributionSet dsA, - final Iterable targs, final Status status, final String... msgs) { - final List result = new ArrayList(); - for (final Target t : targs) { - final List findByTarget = actionRepository.findByTarget(t); - for (final Action action : findByTarget) { - result.add(sendUpdateActionStatusToTarget(controllerManagament, targetManagement, status, action, t, - msgs)); - } - } - return result; - } - - private static Target sendUpdateActionStatusToTarget(final ControllerManagement controllerManagament, - final TargetManagement targetManagement, final Status status, final Action updActA, final Target t, - final String... msgs) { - updActA.setStatus(status); - - final ActionStatus statusMessages = new ActionStatus(); - statusMessages.setAction(updActA); - statusMessages.setOccurredAt(System.currentTimeMillis()); - statusMessages.setStatus(status); - for (final String msg : msgs) { - statusMessages.addMessage(msg); - } - controllerManagament.addUpdateActionStatus(statusMessages, updActA); - return targetManagement.findTargetByControllerID(t.getControllerId()); - } - - public static DistributionSet createTestDistributionSet(final SoftwareManagement softwareManagement, - final DistributionSetManagement distributionSetManagement) { - - DistributionSet set = TestDataUtil.generateDistributionSet("one", softwareManagement, - distributionSetManagement); - set.setVersion("anotherVersion"); - set = distributionSetManagement.updateDistributionSet(set); - - set.getModules().forEach(module -> { - module.setDescription("updated description"); - softwareManagement.updateSoftwareModule(module); - }); - - // load also lazy stuff - set = distributionSetManagement.findDistributionSetByIdWithDetails(set.getId()); - - assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, false, true)).hasSize(1); - return set; - } - } diff --git a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/DistributionSetTypeResourceTest.java b/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTypeResourceTest.java similarity index 94% rename from hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/DistributionSetTypeResourceTest.java rename to hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTypeResourceTest.java index 9f3d2a89d..dcd78513b 100644 --- a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/DistributionSetTypeResourceTest.java +++ b/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDistributionSetTypeResourceTest.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource; +package org.eclipse.hawkbit.mgmt.rest.resource; import static org.fest.assertions.api.Assertions.assertThat; import static org.hamcrest.CoreMatchers.equalTo; @@ -23,13 +23,15 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. import java.util.ArrayList; import java.util.List; -import org.eclipse.hawkbit.AbstractIntegrationTest; -import org.eclipse.hawkbit.MockMvcResultPrinter; import org.eclipse.hawkbit.WithUser; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants; import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.DistributionSetType; import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.repository.model.SoftwareModuleType; +import org.eclipse.hawkbit.rest.AbstractRestIntegrationTest; +import org.eclipse.hawkbit.rest.util.JsonBuilder; +import org.eclipse.hawkbit.rest.util.MockMvcResultPrinter; import org.json.JSONException; import org.json.JSONObject; import org.junit.Test; @@ -44,12 +46,12 @@ import ru.yandex.qatools.allure.annotations.Features; import ru.yandex.qatools.allure.annotations.Stories; /** - * Test for {@link DistributionSetTypeResource}. + * Test for {@link MgmtDistributionSetTypeResource}. * */ @Features("Component Tests - Management API") @Stories("Distribution Set Type Resource") -public class DistributionSetTypeResourceTest extends AbstractIntegrationTest { +public class MgmtDistributionSetTypeResourceTest extends AbstractRestIntegrationTest { @Test @WithUser(principal = "uploadTester", allSpPermissions = true) @@ -101,7 +103,7 @@ public class DistributionSetTypeResourceTest extends AbstractIntegrationTest { // descending mvc.perform(get("/rest/v1/distributionsettypes").accept(MediaType.APPLICATION_JSON) - .param(RestConstants.REQUEST_PARAMETER_SORTING, "KEY:DESC")).andDo(MockMvcResultPrinter.print()) + .param(MgmtRestConstants.REQUEST_PARAMETER_SORTING, "KEY:DESC")).andDo(MockMvcResultPrinter.print()) .andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$content.[0].id", equalTo(testType.getId().intValue()))) .andExpect(jsonPath("$content.[0].name", equalTo("TestName123"))) @@ -114,7 +116,7 @@ public class DistributionSetTypeResourceTest extends AbstractIntegrationTest { // ascending mvc.perform(get("/rest/v1/distributionsettypes").accept(MediaType.APPLICATION_JSON) - .param(RestConstants.REQUEST_PARAMETER_SORTING, "KEY:ASC")).andDo(MockMvcResultPrinter.print()) + .param(MgmtRestConstants.REQUEST_PARAMETER_SORTING, "KEY:ASC")).andDo(MockMvcResultPrinter.print()) .andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$content.[3].id", equalTo(testType.getId().intValue()))) .andExpect(jsonPath("$content.[3].name", equalTo("TestName123"))) @@ -439,11 +441,11 @@ public class DistributionSetTypeResourceTest extends AbstractIntegrationTest { @Description("Checks the correct behaviour of /rest/v1/distributionsettypes GET requests with paging.") public void getDistributionSetTypesWithoutAddtionalRequestParameters() throws Exception { final int types = 3; - mvc.perform(get(RestConstants.DISTRIBUTIONSETTYPE_V1_REQUEST_MAPPING)).andDo(MockMvcResultPrinter.print()) + mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSETTYPE_V1_REQUEST_MAPPING)).andDo(MockMvcResultPrinter.print()) .andExpect(status().isOk()) - .andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(types))) - .andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(types))) - .andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(types))); + .andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(types))) + .andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(types))) + .andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(types))); } @Test @@ -451,12 +453,12 @@ public class DistributionSetTypeResourceTest extends AbstractIntegrationTest { public void getDistributionSetTypesWithPagingLimitRequestParameter() throws Exception { final int types = 3; final int limitSize = 1; - mvc.perform(get(RestConstants.DISTRIBUTIONSETTYPE_V1_REQUEST_MAPPING) - .param(RestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(limitSize))) + mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSETTYPE_V1_REQUEST_MAPPING) + .param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(limitSize))) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) - .andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(types))) - .andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(limitSize))) - .andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(limitSize))); + .andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(types))) + .andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(limitSize))) + .andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(limitSize))); } @Test @@ -465,13 +467,13 @@ public class DistributionSetTypeResourceTest extends AbstractIntegrationTest { final int types = 3; final int offsetParam = 2; final int expectedSize = types - offsetParam; - mvc.perform(get(RestConstants.DISTRIBUTIONSETTYPE_V1_REQUEST_MAPPING) - .param(RestConstants.REQUEST_PARAMETER_PAGING_OFFSET, String.valueOf(offsetParam)) - .param(RestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(types))) + mvc.perform(get(MgmtRestConstants.DISTRIBUTIONSETTYPE_V1_REQUEST_MAPPING) + .param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, String.valueOf(offsetParam)) + .param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(types))) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) - .andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(types))) - .andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(expectedSize))) - .andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(expectedSize))); + .andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(types))) + .andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(expectedSize))) + .andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(expectedSize))); } @Test diff --git a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/DownloadResourceTest.java b/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDownloadResourceTest.java similarity index 72% rename from hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/DownloadResourceTest.java rename to hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDownloadResourceTest.java index ee0fa52fe..17f23f888 100644 --- a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/DownloadResourceTest.java +++ b/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDownloadResourceTest.java @@ -6,20 +6,21 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource; +package org.eclipse.hawkbit.mgmt.rest.resource; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import org.eclipse.hawkbit.AbstractIntegrationTestWithMongoDB; -import org.eclipse.hawkbit.MockMvcResultPrinter; import org.eclipse.hawkbit.TestDataUtil; import org.eclipse.hawkbit.cache.CacheConstants; import org.eclipse.hawkbit.cache.DownloadArtifactCache; import org.eclipse.hawkbit.cache.DownloadType; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants; import org.eclipse.hawkbit.repository.model.Artifact; import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.SoftwareModule; +import org.eclipse.hawkbit.rest.AbstractRestIntegrationTestWithMongoDB; +import org.eclipse.hawkbit.rest.util.MockMvcResultPrinter; import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -32,7 +33,7 @@ import ru.yandex.qatools.allure.annotations.Stories; @Features("Component Tests - Management API") @Stories("Download Resource") -public class DownloadResourceTest extends AbstractIntegrationTestWithMongoDB { +public class MgmtDownloadResourceTest extends AbstractRestIntegrationTestWithMongoDB { @Autowired @Qualifier(CacheConstants.DOWNLOAD_ID_CACHE) @@ -57,9 +58,8 @@ public class DownloadResourceTest extends AbstractIntegrationTestWithMongoDB { @Test @Description("This test verifies the call of download artifact without a valid download id fails.") public void testNoDownloadIdAvailable() throws Exception { - mvc.perform( - get(RestConstants.DOWNLOAD_ID_V1_REQUEST_MAPPING_BASE + RestConstants.DOWNLOAD_ID_V1_REQUEST_MAPPING, - downloadIdNotAvailable)) + mvc.perform(get(MgmtRestConstants.DOWNLOAD_ID_V1_REQUEST_MAPPING_BASE + + MgmtRestConstants.DOWNLOAD_ID_V1_REQUEST_MAPPING, downloadIdNotAvailable)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound()); } @@ -67,16 +67,14 @@ public class DownloadResourceTest extends AbstractIntegrationTestWithMongoDB { @Test @Description("This test verifies the call of download artifact works and the download id will be removed.") public void testDownload() throws Exception { - mvc.perform( - get(RestConstants.DOWNLOAD_ID_V1_REQUEST_MAPPING_BASE + RestConstants.DOWNLOAD_ID_V1_REQUEST_MAPPING, - downloadIdSha1)) - .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); + mvc.perform(get(MgmtRestConstants.DOWNLOAD_ID_V1_REQUEST_MAPPING_BASE + + MgmtRestConstants.DOWNLOAD_ID_V1_REQUEST_MAPPING, downloadIdSha1)).andDo(MockMvcResultPrinter.print()) + .andExpect(status().isOk()); // because cache is empty - mvc.perform( - get(RestConstants.DOWNLOAD_ID_V1_REQUEST_MAPPING_BASE + RestConstants.DOWNLOAD_ID_V1_REQUEST_MAPPING, - downloadIdSha1)) - .andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound()); + mvc.perform(get(MgmtRestConstants.DOWNLOAD_ID_V1_REQUEST_MAPPING_BASE + + MgmtRestConstants.DOWNLOAD_ID_V1_REQUEST_MAPPING, downloadIdSha1)).andDo(MockMvcResultPrinter.print()) + .andExpect(status().isNotFound()); } diff --git a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/RolloutResourceTest.java b/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtRolloutResourceTest.java similarity index 96% rename from hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/RolloutResourceTest.java rename to hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtRolloutResourceTest.java index f27eb5186..09281721c 100644 --- a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/RolloutResourceTest.java +++ b/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtRolloutResourceTest.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource; +package org.eclipse.hawkbit.mgmt.rest.resource; import static org.fest.assertions.api.Assertions.assertThat; import static org.hamcrest.Matchers.equalTo; @@ -21,10 +21,9 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. import java.util.List; import java.util.concurrent.Callable; -import org.eclipse.hawkbit.AbstractIntegrationTest; -import org.eclipse.hawkbit.MockMvcResultPrinter; import org.eclipse.hawkbit.TestDataUtil; import org.eclipse.hawkbit.WithUser; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants; import org.eclipse.hawkbit.repository.RolloutGroupManagement; import org.eclipse.hawkbit.repository.RolloutManagement; import org.eclipse.hawkbit.repository.model.DistributionSet; @@ -34,6 +33,10 @@ import org.eclipse.hawkbit.repository.model.RolloutGroup; import org.eclipse.hawkbit.repository.model.RolloutGroup.RolloutGroupConditionBuilder; import org.eclipse.hawkbit.repository.model.RolloutGroup.RolloutGroupSuccessCondition; import org.eclipse.hawkbit.repository.model.Target; +import org.eclipse.hawkbit.rest.AbstractRestIntegrationTest; +import org.eclipse.hawkbit.rest.util.JsonBuilder; +import org.eclipse.hawkbit.rest.util.MockMvcResultPrinter; +import org.eclipse.hawkbit.rest.util.SuccessCondition; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Description; @@ -45,11 +48,11 @@ import ru.yandex.qatools.allure.annotations.Features; import ru.yandex.qatools.allure.annotations.Stories; /** - * Tests for covering the {@link RolloutResource}. + * Tests for covering the {@link MgmtRolloutResource}. */ @Features("Component Tests - Management API") @Stories("Rollout Resource") -public class RolloutResourceTest extends AbstractIntegrationTest { +public class MgmtRolloutResourceTest extends AbstractRestIntegrationTest { @Autowired private RolloutManagement rolloutManagement; @@ -449,7 +452,7 @@ public class RolloutResourceTest extends AbstractIntegrationTest { // starting rollout mvc.perform(post("/rest/v1/rollouts/{rolloutId}/start", rollout.getId()) - .param(RestConstants.REQUEST_PARAMETER_ASYNC, "true")).andDo(MockMvcResultPrinter.print()) + .param(MgmtRestConstants.REQUEST_PARAMETER_ASYNC, "true")).andDo(MockMvcResultPrinter.print()) .andExpect(status().isOk()); // check if running @@ -477,18 +480,18 @@ public class RolloutResourceTest extends AbstractIntegrationTest { createRollout("rollout3", 5, dsA.getId(), "controllerId==rollout3*"); createRollout("other1", 5, dsA.getId(), "controllerId==other1*"); - mvc.perform(get("/rest/v1/rollouts").param(RestConstants.REQUEST_PARAMETER_SEARCH, "name==*2")) + mvc.perform(get("/rest/v1/rollouts").param(MgmtRestConstants.REQUEST_PARAMETER_SEARCH, "name==*2")) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$content", hasSize(1))).andExpect(jsonPath("$total", equalTo(1))) .andExpect(jsonPath("$content[0].name", equalTo(rollout2.getName()))); - mvc.perform(get("/rest/v1/rollouts").param(RestConstants.REQUEST_PARAMETER_SEARCH, "name==rollout*")) + mvc.perform(get("/rest/v1/rollouts").param(MgmtRestConstants.REQUEST_PARAMETER_SEARCH, "name==rollout*")) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$content", hasSize(3))).andExpect(jsonPath("$total", equalTo(3))); - mvc.perform(get("/rest/v1/rollouts").param(RestConstants.REQUEST_PARAMETER_SEARCH, "name==*1")) + mvc.perform(get("/rest/v1/rollouts").param(MgmtRestConstants.REQUEST_PARAMETER_SEARCH, "name==*1")) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$content", hasSize(2))).andExpect(jsonPath("$total", equalTo(2))); @@ -509,18 +512,18 @@ public class RolloutResourceTest extends AbstractIntegrationTest { // retrieve rollout groups from created rollout mvc.perform(get("/rest/v1/rollouts/{rolloutId}/deploygroups", rollout.getId()) - .param(RestConstants.REQUEST_PARAMETER_SEARCH, "name==group-1")).andDo(MockMvcResultPrinter.print()) + .param(MgmtRestConstants.REQUEST_PARAMETER_SEARCH, "name==group-1")).andDo(MockMvcResultPrinter.print()) .andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$content", hasSize(1))).andExpect(jsonPath("$total", equalTo(1))) .andExpect(jsonPath("$content[0].name", equalTo("group-1"))); mvc.perform(get("/rest/v1/rollouts/{rolloutId}/deploygroups", rollout.getId()) - .param(RestConstants.REQUEST_PARAMETER_SEARCH, "name==group*")).andDo(MockMvcResultPrinter.print()) + .param(MgmtRestConstants.REQUEST_PARAMETER_SEARCH, "name==group*")).andDo(MockMvcResultPrinter.print()) .andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$content", hasSize(4))).andExpect(jsonPath("$total", equalTo(4))); mvc.perform(get("/rest/v1/rollouts/{rolloutId}/deploygroups", rollout.getId()) - .param(RestConstants.REQUEST_PARAMETER_SEARCH, "name==group-1,name==group-2")) + .param(MgmtRestConstants.REQUEST_PARAMETER_SEARCH, "name==group-1,name==group-2")) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$content", hasSize(2))).andExpect(jsonPath("$total", equalTo(2))); diff --git a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/SoftwareModuleResourceTest.java b/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleResourceTest.java similarity index 95% rename from hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/SoftwareModuleResourceTest.java rename to hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleResourceTest.java index 0b8503d6b..a63dd754f 100644 --- a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/SoftwareModuleResourceTest.java +++ b/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleResourceTest.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource; +package org.eclipse.hawkbit.mgmt.rest.resource; import static org.fest.assertions.api.Assertions.assertThat; import static org.hamcrest.CoreMatchers.equalTo; @@ -32,12 +32,12 @@ import java.util.List; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.RandomStringUtils; -import org.eclipse.hawkbit.AbstractIntegrationTestWithMongoDB; import org.eclipse.hawkbit.HashGeneratorUtils; -import org.eclipse.hawkbit.MockMvcResultPrinter; import org.eclipse.hawkbit.TestDataUtil; import org.eclipse.hawkbit.WithUser; import org.eclipse.hawkbit.exception.SpServerError; +import org.eclipse.hawkbit.mgmt.json.model.artifact.MgmtArtifact; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants; import org.eclipse.hawkbit.repository.exception.EntityNotFoundException; import org.eclipse.hawkbit.repository.model.Artifact; import org.eclipse.hawkbit.repository.model.DistributionSet; @@ -45,8 +45,10 @@ import org.eclipse.hawkbit.repository.model.LocalArtifact; import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.repository.model.SoftwareModuleMetadata; import org.eclipse.hawkbit.repository.model.SwMetadataCompositeKey; -import org.eclipse.hawkbit.rest.resource.model.ExceptionInfo; -import org.eclipse.hawkbit.rest.resource.model.artifact.ArtifactRest; +import org.eclipse.hawkbit.rest.AbstractRestIntegrationTestWithMongoDB; +import org.eclipse.hawkbit.rest.json.model.ExceptionInfo; +import org.eclipse.hawkbit.rest.util.JsonBuilder; +import org.eclipse.hawkbit.rest.util.MockMvcResultPrinter; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; @@ -64,12 +66,12 @@ import ru.yandex.qatools.allure.annotations.Features; import ru.yandex.qatools.allure.annotations.Stories; /** - * Tests for {@link SoftwareModuleResource} {@link RestController}. + * Tests for {@link MgmtSoftwareModuleResource} {@link RestController}. * */ @Features("Component Tests - Management API") @Stories("Software Module Resource") -public class SoftwareModuleResourceTest extends AbstractIntegrationTestWithMongoDB { +public class MgmtSoftwareModuleResourceTest extends AbstractRestIntegrationTestWithMongoDB { @Before public void assertPreparationOfRepo() { @@ -142,7 +144,7 @@ public class SoftwareModuleResourceTest extends AbstractIntegrationTestWithMongo .andExpect(jsonPath("$providedFilename", equalTo("origFilename"))).andReturn(); // check rest of response compared to DB - final ArtifactRest artResult = ResourceUtility + final MgmtArtifact artResult = ResourceUtility .convertArtifactResponse(mvcResult.getResponse().getContentAsString()); final Long artId = ((LocalArtifact) softwareManagement.findSoftwareModuleWithDetails(sm.getId()).getArtifacts() .get(0)).getId(); @@ -169,7 +171,7 @@ public class SoftwareModuleResourceTest extends AbstractIntegrationTestWithMongo artifactManagement .loadLocalArtifactBinary((LocalArtifact) softwareManagement .findSoftwareModuleWithDetails(sm.getId()).getArtifacts().get(0)) - .getFileInputStream())); + .getFileInputStream())); // hashes assertThat(artifactManagement.findLocalArtifactByFilename("origFilename").get(0).getSha1Hash()) @@ -473,11 +475,11 @@ public class SoftwareModuleResourceTest extends AbstractIntegrationTestWithMongo public void getSoftwareModulesWithoutAddtionalRequestParameters() throws Exception { final int modules = 5; createSoftwareModulesAlphabetical(modules); - mvc.perform(get(RestConstants.SOFTWAREMODULE_V1_REQUEST_MAPPING)).andDo(MockMvcResultPrinter.print()) + mvc.perform(get(MgmtRestConstants.SOFTWAREMODULE_V1_REQUEST_MAPPING)).andDo(MockMvcResultPrinter.print()) .andExpect(status().isOk()) - .andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(modules))) - .andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(modules))) - .andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(modules))); + .andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(modules))) + .andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(modules))) + .andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(modules))); } @Test @@ -486,12 +488,12 @@ public class SoftwareModuleResourceTest extends AbstractIntegrationTestWithMongo final int modules = 5; final int limitSize = 1; createSoftwareModulesAlphabetical(modules); - mvc.perform(get(RestConstants.SOFTWAREMODULE_V1_REQUEST_MAPPING) - .param(RestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(limitSize))) + mvc.perform(get(MgmtRestConstants.SOFTWAREMODULE_V1_REQUEST_MAPPING) + .param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(limitSize))) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) - .andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(modules))) - .andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(limitSize))) - .andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(limitSize))); + .andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(modules))) + .andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(limitSize))) + .andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(limitSize))); } @Test @@ -501,13 +503,13 @@ public class SoftwareModuleResourceTest extends AbstractIntegrationTestWithMongo final int offsetParam = 2; final int expectedSize = modules - offsetParam; createSoftwareModulesAlphabetical(modules); - mvc.perform(get(RestConstants.SOFTWAREMODULE_V1_REQUEST_MAPPING) - .param(RestConstants.REQUEST_PARAMETER_PAGING_OFFSET, String.valueOf(offsetParam)) - .param(RestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(modules))) + mvc.perform(get(MgmtRestConstants.SOFTWAREMODULE_V1_REQUEST_MAPPING) + .param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, String.valueOf(offsetParam)) + .param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(modules))) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) - .andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(modules))) - .andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(expectedSize))) - .andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(expectedSize))); + .andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(modules))) + .andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(expectedSize))) + .andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(expectedSize))); } @Test @@ -773,12 +775,12 @@ public class SoftwareModuleResourceTest extends AbstractIntegrationTestWithMongo .andExpect(jsonPath("[2].createdBy", equalTo("uploadTester"))) .andExpect(jsonPath("[2].createdAt", not(equalTo(0)))).andReturn(); - final SoftwareModule osCreated = softwareManagement.findSoftwareModuleByNameAndVersion("name1", "version1") - .get(0); - final SoftwareModule jvmCreated = softwareManagement.findSoftwareModuleByNameAndVersion("name2", "version1") - .get(0); - final SoftwareModule ahCreated = softwareManagement.findSoftwareModuleByNameAndVersion("name3", "version1") - .get(0); + final SoftwareModule osCreated = softwareManagement.findSoftwareModuleByNameAndVersion("name1", "version1", + osType); + final SoftwareModule jvmCreated = softwareManagement.findSoftwareModuleByNameAndVersion("name2", "version1", + runtimeType); + final SoftwareModule ahCreated = softwareManagement.findSoftwareModuleByNameAndVersion("name3", "version1", + appType); assertThat( JsonPath.compile("[0]_links.self.href").read(mvcResult.getResponse().getContentAsString()).toString()) @@ -930,8 +932,10 @@ public class SoftwareModuleResourceTest extends AbstractIntegrationTestWithMongo .andExpect(jsonPath("[1]key", equalTo(knownKey2))) .andExpect(jsonPath("[1]value", equalTo(knownValue2))); - final SoftwareModuleMetadata metaKey1 = softwareManagement.findOne(new SwMetadataCompositeKey(sm, knownKey1)); - final SoftwareModuleMetadata metaKey2 = softwareManagement.findOne(new SwMetadataCompositeKey(sm, knownKey2)); + final SoftwareModuleMetadata metaKey1 = softwareManagement + .findSoftwareModuleMetadata(new SwMetadataCompositeKey(sm, knownKey1)); + final SoftwareModuleMetadata metaKey2 = softwareManagement + .findSoftwareModuleMetadata(new SwMetadataCompositeKey(sm, knownKey2)); assertThat(metaKey1.getValue()).as("Metadata key is wrong").isEqualTo(knownValue1); assertThat(metaKey2.getValue()).as("Metadata key is wrong").isEqualTo(knownValue2); @@ -957,7 +961,8 @@ public class SoftwareModuleResourceTest extends AbstractIntegrationTestWithMongo .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("key", equalTo(knownKey))).andExpect(jsonPath("value", equalTo(updateValue))); - final SoftwareModuleMetadata assertDS = softwareManagement.findOne(new SwMetadataCompositeKey(sm, knownKey)); + final SoftwareModuleMetadata assertDS = softwareManagement + .findSoftwareModuleMetadata(new SwMetadataCompositeKey(sm, knownKey)); assertThat(assertDS.getValue()).as("Metadata is wrong").isEqualTo(updateValue); } @@ -976,7 +981,7 @@ public class SoftwareModuleResourceTest extends AbstractIntegrationTestWithMongo .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); try { - softwareManagement.findOne(new SwMetadataCompositeKey(sm, knownKey)); + softwareManagement.findSoftwareModuleMetadata(new SwMetadataCompositeKey(sm, knownKey)); fail("expected EntityNotFoundException but didn't throw"); } catch (final EntityNotFoundException e) { // ok as expected diff --git a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/SoftwareModuleTypeResourceTest.java b/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleTypeResourceTest.java similarity index 90% rename from hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/SoftwareModuleTypeResourceTest.java rename to hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleTypeResourceTest.java index a85e25bed..b69558e59 100644 --- a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/SoftwareModuleTypeResourceTest.java +++ b/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtSoftwareModuleTypeResourceTest.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource; +package org.eclipse.hawkbit.mgmt.rest.resource; import static org.fest.assertions.api.Assertions.assertThat; import static org.hamcrest.CoreMatchers.equalTo; @@ -23,11 +23,13 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. import java.util.ArrayList; import java.util.List; -import org.eclipse.hawkbit.AbstractIntegrationTest; -import org.eclipse.hawkbit.MockMvcResultPrinter; import org.eclipse.hawkbit.WithUser; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants; import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.repository.model.SoftwareModuleType; +import org.eclipse.hawkbit.rest.AbstractRestIntegrationTest; +import org.eclipse.hawkbit.rest.util.JsonBuilder; +import org.eclipse.hawkbit.rest.util.MockMvcResultPrinter; import org.json.JSONException; import org.json.JSONObject; import org.junit.Test; @@ -41,12 +43,12 @@ import ru.yandex.qatools.allure.annotations.Features; import ru.yandex.qatools.allure.annotations.Stories; /** - * Test for {@link SoftwareModuleTypeResource}. + * Test for {@link MgmtSoftwareModuleTypeResource}. * */ @Features("Component Tests - Management API") @Stories("Software Module Type Resource") -public class SoftwareModuleTypeResourceTest extends AbstractIntegrationTest { +public class MgmtSoftwareModuleTypeResourceTest extends AbstractRestIntegrationTest { @Test @WithUser(principal = "uploadTester", allSpPermissions = true) @@ -101,7 +103,7 @@ public class SoftwareModuleTypeResourceTest extends AbstractIntegrationTest { // descending mvc.perform(get("/rest/v1/softwaremoduletypes").accept(MediaType.APPLICATION_JSON) - .param(RestConstants.REQUEST_PARAMETER_SORTING, "MAXASSIGNMENTS:DESC")) + .param(MgmtRestConstants.REQUEST_PARAMETER_SORTING, "MAXASSIGNMENTS:DESC")) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$content.[0].id", equalTo(testType.getId().intValue()))) @@ -116,7 +118,7 @@ public class SoftwareModuleTypeResourceTest extends AbstractIntegrationTest { // ascending mvc.perform(get("/rest/v1/softwaremoduletypes").accept(MediaType.APPLICATION_JSON) - .param(RestConstants.REQUEST_PARAMETER_SORTING, "MAXASSIGNMENTS:ASC")) + .param(MgmtRestConstants.REQUEST_PARAMETER_SORTING, "MAXASSIGNMENTS:ASC")) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$content.[3].id", equalTo(testType.getId().intValue()))) @@ -252,11 +254,11 @@ public class SoftwareModuleTypeResourceTest extends AbstractIntegrationTest { @Description("Checks the correct behaviour of /rest/v1/softwaremoduletypes GET requests with paging.") public void getSoftwareModuleTypesWithoutAddtionalRequestParameters() throws Exception { final int types = 3; - mvc.perform(get(RestConstants.SOFTWAREMODULETYPE_V1_REQUEST_MAPPING)).andDo(MockMvcResultPrinter.print()) + mvc.perform(get(MgmtRestConstants.SOFTWAREMODULETYPE_V1_REQUEST_MAPPING)).andDo(MockMvcResultPrinter.print()) .andExpect(status().isOk()) - .andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(types))) - .andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(types))) - .andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(types))); + .andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(types))) + .andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(types))) + .andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(types))); } @Test @@ -264,12 +266,12 @@ public class SoftwareModuleTypeResourceTest extends AbstractIntegrationTest { public void getSoftwareModuleTypesWithPagingLimitRequestParameter() throws Exception { final int types = 3; final int limitSize = 1; - mvc.perform(get(RestConstants.SOFTWAREMODULETYPE_V1_REQUEST_MAPPING) - .param(RestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(limitSize))) + mvc.perform(get(MgmtRestConstants.SOFTWAREMODULETYPE_V1_REQUEST_MAPPING) + .param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(limitSize))) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) - .andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(types))) - .andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(limitSize))) - .andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(limitSize))); + .andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(types))) + .andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(limitSize))) + .andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(limitSize))); } @Test @@ -278,13 +280,13 @@ public class SoftwareModuleTypeResourceTest extends AbstractIntegrationTest { final int types = 3; final int offsetParam = 2; final int expectedSize = types - offsetParam; - mvc.perform(get(RestConstants.SOFTWAREMODULETYPE_V1_REQUEST_MAPPING) - .param(RestConstants.REQUEST_PARAMETER_PAGING_OFFSET, String.valueOf(offsetParam)) - .param(RestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(types))) + mvc.perform(get(MgmtRestConstants.SOFTWAREMODULETYPE_V1_REQUEST_MAPPING) + .param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, String.valueOf(offsetParam)) + .param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(types))) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) - .andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(types))) - .andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(expectedSize))) - .andExpect(jsonPath(TargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(expectedSize))); + .andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_TOTAL, equalTo(types))) + .andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_SIZE, equalTo(expectedSize))) + .andExpect(jsonPath(MgmtTargetResourceTest.JSON_PATH_PAGED_LIST_CONTENT, hasSize(expectedSize))); } @Test diff --git a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/TargetResourceTest.java b/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetResourceTest.java similarity index 84% rename from hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/TargetResourceTest.java rename to hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetResourceTest.java index a8ebfdd9d..c8d33edc9 100644 --- a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/TargetResourceTest.java +++ b/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtTargetResourceTest.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource; +package org.eclipse.hawkbit.mgmt.rest.resource; import static org.fest.assertions.api.Assertions.assertThat; import static org.hamcrest.CoreMatchers.equalTo; @@ -29,12 +29,11 @@ import java.util.List; import java.util.Map; import java.util.stream.Collectors; -import org.eclipse.hawkbit.AbstractIntegrationTest; -import org.eclipse.hawkbit.MockMvcResultPrinter; import org.eclipse.hawkbit.TestDataUtil; import org.eclipse.hawkbit.WithUser; import org.eclipse.hawkbit.exception.SpServerError; import org.eclipse.hawkbit.im.authentication.SpPermission; +import org.eclipse.hawkbit.mgmt.rest.api.MgmtRestConstants; import org.eclipse.hawkbit.repository.ActionFields; import org.eclipse.hawkbit.repository.ActionStatusFields; import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException; @@ -46,7 +45,11 @@ import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.repository.model.TargetInfo; -import org.eclipse.hawkbit.rest.resource.model.ExceptionInfo; +import org.eclipse.hawkbit.rest.AbstractRestIntegrationTest; +import org.eclipse.hawkbit.rest.exception.MessageNotReadableException; +import org.eclipse.hawkbit.rest.json.model.ExceptionInfo; +import org.eclipse.hawkbit.rest.util.JsonBuilder; +import org.eclipse.hawkbit.rest.util.MockMvcResultPrinter; import org.eclipse.hawkbit.util.IpUtil; import org.json.JSONException; import org.json.JSONObject; @@ -68,12 +71,12 @@ import ru.yandex.qatools.allure.annotations.Features; import ru.yandex.qatools.allure.annotations.Stories; /** - * Spring MVC Tests against the TargetResource. + * Spring MVC Tests against the MgmtTargetResource. * */ @Features("Component Tests - Management API") @Stories("Target Resource") -public class TargetResourceTest extends AbstractIntegrationTest { +public class MgmtTargetResourceTest extends AbstractRestIntegrationTest { private static final String TARGET_DESCRIPTION_TEST = "created in test"; @@ -117,10 +120,10 @@ public class TargetResourceTest extends AbstractIntegrationTest { .get(0).getActionStatus().stream().sorted((e1, e2) -> Long.compare(e2.getId(), e1.getId())) .collect(Collectors.toList()).get(0); - mvc.perform(get(RestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" - + RestConstants.TARGET_V1_ACTIONS + "/" + actions.get(0).getId() + "/status") - .param(RestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(limitSize)) - .param(RestConstants.REQUEST_PARAMETER_SORTING, "ID:DESC")) + mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" + + MgmtRestConstants.TARGET_V1_ACTIONS + "/" + actions.get(0).getId() + "/status") + .param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(limitSize)) + .param(MgmtRestConstants.REQUEST_PARAMETER_SORTING, "ID:DESC")) .andExpect(status().isOk()).andDo(MockMvcResultPrinter.print()) .andExpect(jsonPath(JSON_PATH_PAGED_LIST_TOTAL, equalTo(3))) .andExpect(jsonPath(JSON_PATH_PAGED_LIST_SIZE, equalTo(limitSize))) @@ -139,7 +142,7 @@ public class TargetResourceTest extends AbstractIntegrationTest { final String knownControllerId = "knownControllerId"; targetManagement.createTarget(new Target(knownControllerId)); - mvc.perform(get(RestConstants.TARGET_V1_REQUEST_MAPPING + "/{targetId}", knownControllerId)) + mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/{targetId}", knownControllerId)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andExpect(jsonPath("securityToken").doesNotExist()); } @@ -152,7 +155,7 @@ public class TargetResourceTest extends AbstractIntegrationTest { final String knownControllerId = "knownControllerId"; final Target createTarget = targetManagement.createTarget(new Target(knownControllerId)); - mvc.perform(get(RestConstants.TARGET_V1_REQUEST_MAPPING + "/{targetId}", knownControllerId)) + mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/{targetId}", knownControllerId)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andExpect(jsonPath("securityToken", equalTo(createTarget.getSecurityToken()))); } @@ -168,7 +171,7 @@ public class TargetResourceTest extends AbstractIntegrationTest { createTarget(knownControllerId2); // test - mvc.perform(get(RestConstants.TARGET_V1_REQUEST_MAPPING)).andDo(MockMvcResultPrinter.print()) + mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING)).andDo(MockMvcResultPrinter.print()) .andExpect(status().isOk()).andExpect(jsonPath("total", equalTo(2))) .andExpect(jsonPath("size", equalTo(2))) .andExpect(jsonPath("$content.[?(@.controllerId==" + knownControllerId1 + ")][0].ipAddress", @@ -204,22 +207,22 @@ public class TargetResourceTest extends AbstractIntegrationTest { final String rsqlFinishedStatus = "status==finished"; final String rsqlPendingOrFinishedStatus = rsqlFinishedStatus + "," + rsqlPendingStatus; // pending status one result - mvc.perform(get(RestConstants.TARGET_V1_REQUEST_MAPPING + "/{targetId}/actions?q=" + rsqlPendingStatus, + mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/{targetId}/actions?q=" + rsqlPendingStatus, createTarget.getControllerId())).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andExpect(jsonPath("total", equalTo(1))).andExpect(jsonPath("size", equalTo(1))) .andExpect(jsonPath("content[0].status", equalTo("pending"))); // finished status none result - mvc.perform(get(RestConstants.TARGET_V1_REQUEST_MAPPING + "/{targetId}/actions?q=" + rsqlFinishedStatus, + mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/{targetId}/actions?q=" + rsqlFinishedStatus, createTarget.getControllerId())).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andExpect(jsonPath("total", equalTo(0))).andExpect(jsonPath("size", equalTo(0))); // pending or finished status one result - mvc.perform( - get(RestConstants.TARGET_V1_REQUEST_MAPPING + "/{targetId}/actions?q=" + rsqlPendingOrFinishedStatus, - createTarget.getControllerId())) - .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()).andExpect(jsonPath("total", equalTo(1))) - .andExpect(jsonPath("size", equalTo(1))).andExpect(jsonPath("content[0].status", equalTo("pending"))); + mvc.perform(get( + MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/{targetId}/actions?q=" + rsqlPendingOrFinishedStatus, + createTarget.getControllerId())).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) + .andExpect(jsonPath("total", equalTo(1))).andExpect(jsonPath("size", equalTo(1))) + .andExpect(jsonPath("content[0].status", equalTo("pending"))); } @Test @@ -229,7 +232,7 @@ public class TargetResourceTest extends AbstractIntegrationTest { final Target tA = createTargetAndStartAction(); // test - cancel the active action - mvc.perform(delete(RestConstants.TARGET_V1_REQUEST_MAPPING + "/{targetId}/actions/{actionId}", + mvc.perform(delete(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/{targetId}/actions/{actionId}", tA.getControllerId(), tA.getActions().get(0).getId())).andDo(MockMvcResultPrinter.print()) .andExpect(status().isNoContent()); @@ -261,7 +264,7 @@ public class TargetResourceTest extends AbstractIntegrationTest { assertThat(cancelActions).hasSize(1); // test - cancel an cancel action returns forbidden - mvc.perform(delete(RestConstants.TARGET_V1_REQUEST_MAPPING + "/{targetId}/actions/{actionId}", + mvc.perform(delete(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/{targetId}/actions/{actionId}", tA.getControllerId(), cancelActions.get(0).getId())).andDo(MockMvcResultPrinter.print()) .andExpect(status().isMethodNotAllowed()); } @@ -282,7 +285,7 @@ public class TargetResourceTest extends AbstractIntegrationTest { assertThat(cancelActions.get(0).isCancelingOrCanceled()).isTrue(); // test - force quit an canceled action should return 204 - mvc.perform(delete(RestConstants.TARGET_V1_REQUEST_MAPPING + "/{targetId}/actions/{actionId}?force=true", + mvc.perform(delete(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/{targetId}/actions/{actionId}?force=true", tA.getControllerId(), cancelActions.get(0).getId())).andDo(MockMvcResultPrinter.print()) .andExpect(status().isNoContent()); } @@ -294,7 +297,7 @@ public class TargetResourceTest extends AbstractIntegrationTest { final Target tA = createTargetAndStartAction(); // test - cancel an cancel action returns forbidden - mvc.perform(delete(RestConstants.TARGET_V1_REQUEST_MAPPING + "/{targetId}/actions/{actionId}?force=true", + mvc.perform(delete(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/{targetId}/actions/{actionId}?force=true", tA.getControllerId(), tA.getActions().get(0).getId())).andDo(MockMvcResultPrinter.print()) .andExpect(status().isMethodNotAllowed()); } @@ -305,7 +308,7 @@ public class TargetResourceTest extends AbstractIntegrationTest { final String knownControllerId = "knownControllerIdDelete"; targetManagement.createTarget(new Target(knownControllerId)); - mvc.perform(delete(RestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownControllerId)) + mvc.perform(delete(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownControllerId)) .andExpect(status().isOk()); final Target findTargetByControllerID = targetManagement.findTargetByControllerID(knownControllerId); @@ -317,7 +320,7 @@ public class TargetResourceTest extends AbstractIntegrationTest { public void deleteTargetWhichDoesNotExistsLeadsToEntityNotFound() throws Exception { final String knownControllerId = "knownControllerIdDelete"; - mvc.perform(delete(RestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownControllerId)) + mvc.perform(delete(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownControllerId)) .andExpect(status().isNotFound()); } @@ -325,7 +328,7 @@ public class TargetResourceTest extends AbstractIntegrationTest { @Description("Ensures that update is refused with not found if target does not exist.") public void updateTargetWhichDoesNotExistsLeadsToEntityNotFound() throws Exception { final String knownControllerId = "knownControllerIdUpdate"; - mvc.perform(put(RestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownControllerId).content("{}") + mvc.perform(put(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownControllerId).content("{}") .contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()) .andExpect(status().isNotFound()); } @@ -344,7 +347,7 @@ public class TargetResourceTest extends AbstractIntegrationTest { t.setName(knownNameNotModiy); targetManagement.createTarget(t); - mvc.perform(put(RestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownControllerId).content(body) + mvc.perform(put(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownControllerId).content(body) .contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andExpect(jsonPath("$.controllerId", equalTo(knownControllerId))) .andExpect(jsonPath("$.description", equalTo(knownNewDescription))) @@ -364,7 +367,7 @@ public class TargetResourceTest extends AbstractIntegrationTest { final String idC = "c"; final String linksHrefPrefix = "http://localhost/rest/v1/targets/"; createTargetsAlphabetical(knownTargetAmount); - mvc.perform(get(RestConstants.TARGET_V1_REQUEST_MAPPING)).andExpect(status().isOk()) + mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING)).andExpect(status().isOk()) .andDo(MockMvcResultPrinter.print()) .andExpect(jsonPath(JSON_PATH_PAGED_LIST_TOTAL, equalTo(knownTargetAmount))) .andExpect(jsonPath(JSON_PATH_PAGED_LIST_SIZE, equalTo(knownTargetAmount))) @@ -404,8 +407,9 @@ public class TargetResourceTest extends AbstractIntegrationTest { final String idA = "a"; final String linksHrefPrefix = "http://localhost/rest/v1/targets/"; - mvc.perform(get(RestConstants.TARGET_V1_REQUEST_MAPPING).param(RestConstants.REQUEST_PARAMETER_PAGING_LIMIT, - String.valueOf(limitSize))).andExpect(status().isOk()).andDo(MockMvcResultPrinter.print()) + mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING) + .param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(limitSize))) + .andExpect(status().isOk()).andDo(MockMvcResultPrinter.print()) .andExpect(jsonPath(JSON_PATH_PAGED_LIST_TOTAL, equalTo(knownTargetAmount))) .andExpect(jsonPath(JSON_PATH_PAGED_LIST_SIZE, equalTo(limitSize))) .andExpect(jsonPath(JSON_PATH_PAGED_LIST_CONTENT, hasSize(limitSize))) @@ -431,9 +435,9 @@ public class TargetResourceTest extends AbstractIntegrationTest { final String linksHrefPrefix = "http://localhost/rest/v1/targets/"; createTargetsAlphabetical(knownTargetAmount); - mvc.perform(get(RestConstants.TARGET_V1_REQUEST_MAPPING) - .param(RestConstants.REQUEST_PARAMETER_PAGING_OFFSET, String.valueOf(offsetParam)) - .param(RestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(knownTargetAmount))) + mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING) + .param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, String.valueOf(offsetParam)) + .param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(knownTargetAmount))) .andExpect(status().isOk()).andDo(MockMvcResultPrinter.print()) .andExpect(jsonPath(JSON_PATH_PAGED_LIST_TOTAL, equalTo(knownTargetAmount))) .andExpect(jsonPath(JSON_PATH_PAGED_LIST_SIZE, equalTo(expectedSize))) @@ -472,7 +476,7 @@ public class TargetResourceTest extends AbstractIntegrationTest { createSingleTarget(knownControllerId, knownName); final String hrefPrefix = "http://localhost/rest/v1/targets/" + knownControllerId + "/"; // test - mvc.perform(get(RestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownControllerId)) + mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownControllerId)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andExpect(jsonPath(JSON_PATH_NAME, equalTo(knownName))) .andExpect(jsonPath(JSON_PATH_CONTROLLERID, equalTo(knownControllerId))) @@ -491,7 +495,8 @@ public class TargetResourceTest extends AbstractIntegrationTest { final String targetIdNotExists = "bubu"; // test - final MvcResult mvcResult = mvc.perform(get(RestConstants.TARGET_V1_REQUEST_MAPPING + "/" + targetIdNotExists)) + final MvcResult mvcResult = mvc + .perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + targetIdNotExists)) .andExpect(status().isNotFound()).andReturn(); // verify response json exception message @@ -509,7 +514,7 @@ public class TargetResourceTest extends AbstractIntegrationTest { // test - mvc.perform(get(RestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownControllerId + "/assignedDS")) + mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownControllerId + "/assignedDS")) .andExpect(status().isNoContent()).andExpect(content().string("")); } @@ -529,7 +534,7 @@ public class TargetResourceTest extends AbstractIntegrationTest { final SoftwareModule os = ds.findFirstModuleByType(osType); final SoftwareModule jvm = ds.findFirstModuleByType(runtimeType); final SoftwareModule bApp = ds.findFirstModuleByType(appType); - mvc.perform(get(RestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownControllerId + "/assignedDS")) + mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownControllerId + "/assignedDS")) .andExpect(status().isOk()).andDo(MockMvcResultPrinter.print()) .andExpect(jsonPath(JSON_PATH_ID, equalTo(ds.getId().intValue()))) .andExpect(jsonPath(JSON_PATH_NAME, equalTo(ds.getName()))) @@ -579,7 +584,7 @@ public class TargetResourceTest extends AbstractIntegrationTest { // test - mvc.perform(get(RestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownControllerId + "/installedDS")) + mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownControllerId + "/installedDS")) .andExpect(status().isNoContent()).andExpect(content().string("")); } @@ -602,7 +607,7 @@ public class TargetResourceTest extends AbstractIntegrationTest { final SoftwareModule os = ds.findFirstModuleByType(osType); final SoftwareModule jvm = ds.findFirstModuleByType(runtimeType); final SoftwareModule bApp = ds.findFirstModuleByType(appType); - mvc.perform(get(RestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownControllerId + "/installedDS")) + mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownControllerId + "/installedDS")) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andExpect(jsonPath(JSON_PATH_ID, equalTo(ds.getId().intValue()))) .andExpect(jsonPath(JSON_PATH_NAME, equalTo(ds.getName()))) @@ -646,7 +651,7 @@ public class TargetResourceTest extends AbstractIntegrationTest { public void createTargetWithoutPayloadBadRequest() throws Exception { final MvcResult mvcResult = mvc - .perform(post(RestConstants.TARGET_V1_REQUEST_MAPPING).contentType(MediaType.APPLICATION_JSON)) + .perform(post(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING).contentType(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isBadRequest()).andReturn(); assertThat(targetManagement.countTargetsAll()).isEqualTo(0); @@ -663,7 +668,7 @@ public class TargetResourceTest extends AbstractIntegrationTest { final String notJson = "abc"; final MvcResult mvcResult = mvc - .perform(post(RestConstants.TARGET_V1_REQUEST_MAPPING).content(notJson) + .perform(post(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING).content(notJson) .contentType(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isBadRequest()).andReturn(); @@ -743,7 +748,7 @@ public class TargetResourceTest extends AbstractIntegrationTest { final String knownDescription = "someDescription"; final String createTargetsJson = getCreateTargetsListJsonString(knownControllerId, knownName, knownDescription); - mvc.perform(post(RestConstants.TARGET_V1_REQUEST_MAPPING).content(createTargetsJson) + mvc.perform(post(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING).content(createTargetsJson) .contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()) .andExpect(status().is2xxSuccessful()); @@ -764,12 +769,12 @@ public class TargetResourceTest extends AbstractIntegrationTest { // create a taret first to provoke a already exists error - mvc.perform(post(RestConstants.TARGET_V1_REQUEST_MAPPING).content(createTargetsJson) + mvc.perform(post(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING).content(createTargetsJson) .contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()) .andExpect(status().is2xxSuccessful()); // create another one to retrieve the entity already exists exception final MvcResult mvcResult = mvc - .perform(post(RestConstants.TARGET_V1_REQUEST_MAPPING).content(createTargetsJson) + .perform(post(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING).content(createTargetsJson) .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().is(HttpStatus.CONFLICT.value())).andReturn(); @@ -792,7 +797,7 @@ public class TargetResourceTest extends AbstractIntegrationTest { final String createTargetsJson = getCreateTargetsListJsonStringWithAdditionalNotExistingAttribute( knownControllerId, knownName, knownDescription); - mvc.perform(post(RestConstants.TARGET_V1_REQUEST_MAPPING).content(createTargetsJson) + mvc.perform(post(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING).content(createTargetsJson) .contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()) .andExpect(status().is2xxSuccessful()); @@ -810,10 +815,10 @@ public class TargetResourceTest extends AbstractIntegrationTest { final Target target = new Target(knownTargetId); targetManagement.createTarget(target); - mvc.perform(get( - RestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" + RestConstants.TARGET_V1_ACTIONS)) - .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()).andExpect(jsonPath("size", equalTo(0))) - .andExpect(jsonPath("content", hasSize(0))).andExpect(jsonPath("total", equalTo(0))); + mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" + + MgmtRestConstants.TARGET_V1_ACTIONS)).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) + .andExpect(jsonPath("size", equalTo(0))).andExpect(jsonPath("content", hasSize(0))) + .andExpect(jsonPath("total", equalTo(0))); } @Test @@ -821,9 +826,10 @@ public class TargetResourceTest extends AbstractIntegrationTest { final String knownTargetId = "targetId"; final List actions = generateTargetWithTwoUpdatesWithOneOverride(knownTargetId); - mvc.perform(get(RestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" - + RestConstants.TARGET_V1_ACTIONS + "/" + actions.get(0).getId())).andDo(MockMvcResultPrinter.print()) - .andExpect(status().isOk()).andExpect(jsonPath("id", equalTo(actions.get(0).getId().intValue()))) + mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" + + MgmtRestConstants.TARGET_V1_ACTIONS + "/" + actions.get(0).getId())) + .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) + .andExpect(jsonPath("id", equalTo(actions.get(0).getId().intValue()))) .andExpect(jsonPath("type", equalTo("cancel"))).andExpect(jsonPath("status", equalTo("pending"))) .andExpect(jsonPath("_links.self.href", equalTo(generateActionSelfLink(knownTargetId, actions.get(0))))) .andExpect(jsonPath("_links.canceledaction.href", @@ -837,9 +843,8 @@ public class TargetResourceTest extends AbstractIntegrationTest { final String knownTargetId = "targetId"; final List actions = generateTargetWithTwoUpdatesWithOneOverride(knownTargetId); - mvc.perform(get( - RestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" + RestConstants.TARGET_V1_ACTIONS) - .param(RestConstants.REQUEST_PARAMETER_SORTING, "ID:ASC")) + mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" + + MgmtRestConstants.TARGET_V1_ACTIONS).param(MgmtRestConstants.REQUEST_PARAMETER_SORTING, "ID:ASC")) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andExpect(jsonPath("content.[1].id", equalTo(actions.get(1).getId().intValue()))) .andExpect(jsonPath("content.[1].type", equalTo("update"))) @@ -866,9 +871,10 @@ public class TargetResourceTest extends AbstractIntegrationTest { .sorted((e1, e2) -> Long.compare(e2.getId(), e1.getId())).collect(Collectors.toList()); // sort is default descending order, latest status first - mvc.perform(get(RestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" - + RestConstants.TARGET_V1_ACTIONS + "/" + action.getId() + "/" + RestConstants.TARGET_V1_ACTION_STATUS)) - .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) + mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" + + MgmtRestConstants.TARGET_V1_ACTIONS + "/" + action.getId() + "/" + + MgmtRestConstants.TARGET_V1_ACTION_STATUS)).andDo(MockMvcResultPrinter.print()) + .andExpect(status().isOk()) .andExpect(jsonPath("content.[0].id", equalTo(actionStatus.get(0).getId().intValue()))) .andExpect(jsonPath("content.[0].type", equalTo("canceling"))) .andExpect(jsonPath("content.[0].messages", hasItem("manual cancelation requested"))) @@ -890,9 +896,10 @@ public class TargetResourceTest extends AbstractIntegrationTest { .sorted((e1, e2) -> Long.compare(e1.getId(), e2.getId())).collect(Collectors.toList()); // descending order - mvc.perform(get(RestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" - + RestConstants.TARGET_V1_ACTIONS + "/" + action.getId() + "/" + RestConstants.TARGET_V1_ACTION_STATUS) - .param(RestConstants.REQUEST_PARAMETER_SORTING, "REPORTEDAT:DESC")) + mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" + + MgmtRestConstants.TARGET_V1_ACTIONS + "/" + action.getId() + "/" + + MgmtRestConstants.TARGET_V1_ACTION_STATUS).param(MgmtRestConstants.REQUEST_PARAMETER_SORTING, + "REPORTEDAT:DESC")) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andExpect(jsonPath("content.[0].id", equalTo(actionStatus.get(1).getId().intValue()))) .andExpect(jsonPath("content.[0].type", equalTo("canceling"))) @@ -906,9 +913,10 @@ public class TargetResourceTest extends AbstractIntegrationTest { .andExpect(jsonPath(JSON_PATH_PAGED_LIST_CONTENT, hasSize(2))); // ascending order - mvc.perform(get(RestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" - + RestConstants.TARGET_V1_ACTIONS + "/" + action.getId() + "/" + RestConstants.TARGET_V1_ACTION_STATUS) - .param(RestConstants.REQUEST_PARAMETER_SORTING, "REPORTEDAT:ASC")) + mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" + + MgmtRestConstants.TARGET_V1_ACTIONS + "/" + action.getId() + "/" + + MgmtRestConstants.TARGET_V1_ACTION_STATUS).param(MgmtRestConstants.REQUEST_PARAMETER_SORTING, + "REPORTEDAT:ASC")) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andExpect(jsonPath("content.[1].id", equalTo(actionStatus.get(1).getId().intValue()))) .andExpect(jsonPath("content.[1].type", equalTo("canceling"))) @@ -932,9 +940,10 @@ public class TargetResourceTest extends AbstractIntegrationTest { .sorted((e1, e2) -> Long.compare(e1.getId(), e2.getId())).collect(Collectors.toList()); // Page 1 - mvc.perform(get(RestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" - + RestConstants.TARGET_V1_ACTIONS + "/" + action.getId() + "/" + RestConstants.TARGET_V1_ACTION_STATUS) - .param(RestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(1))) + mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" + + MgmtRestConstants.TARGET_V1_ACTIONS + "/" + action.getId() + "/" + + MgmtRestConstants.TARGET_V1_ACTION_STATUS).param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, + String.valueOf(1))) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andExpect(jsonPath("content.[0].id", equalTo(actionStatus.get(1).getId().intValue()))) .andExpect(jsonPath("content.[0].type", equalTo("canceling"))) @@ -945,10 +954,11 @@ public class TargetResourceTest extends AbstractIntegrationTest { .andExpect(jsonPath(JSON_PATH_PAGED_LIST_CONTENT, hasSize(1))); // Page 2 - mvc.perform(get(RestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" - + RestConstants.TARGET_V1_ACTIONS + "/" + action.getId() + "/" + RestConstants.TARGET_V1_ACTION_STATUS) - .param(RestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(1)) - .param(RestConstants.REQUEST_PARAMETER_PAGING_OFFSET, String.valueOf(1))) + mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" + + MgmtRestConstants.TARGET_V1_ACTIONS + "/" + action.getId() + "/" + + MgmtRestConstants.TARGET_V1_ACTION_STATUS) + .param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(1)) + .param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, String.valueOf(1))) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andExpect(jsonPath("content.[0].id", equalTo(actionStatus.get(0).getId().intValue()))) .andExpect(jsonPath("content.[0].type", equalTo("running"))) @@ -964,10 +974,10 @@ public class TargetResourceTest extends AbstractIntegrationTest { final List actions = generateTargetWithTwoUpdatesWithOneOverride(knownTargetId); // page 1: one entry - mvc.perform(get( - RestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" + RestConstants.TARGET_V1_ACTIONS) - .param(RestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(1)) - .param(RestConstants.REQUEST_PARAMETER_SORTING, "ID:ASC")) + mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" + + MgmtRestConstants.TARGET_V1_ACTIONS) + .param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(1)) + .param(MgmtRestConstants.REQUEST_PARAMETER_SORTING, "ID:ASC")) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andExpect(jsonPath("content.[0].id", equalTo(actions.get(0).getId().intValue()))) .andExpect(jsonPath("content.[0].type", equalTo("cancel"))) @@ -979,12 +989,12 @@ public class TargetResourceTest extends AbstractIntegrationTest { .andExpect(jsonPath(JSON_PATH_PAGED_LIST_CONTENT, hasSize(1))); // page 2: one entry - mvc.perform(get( - RestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" + RestConstants.TARGET_V1_ACTIONS) - .param(RestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(1)) - .param(RestConstants.REQUEST_PARAMETER_PAGING_OFFSET, String.valueOf(1)) - .param(RestConstants.REQUEST_PARAMETER_PAGING_OFFSET, String.valueOf(1)) - .param(RestConstants.REQUEST_PARAMETER_SORTING, "ID:ASC")) + mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" + + MgmtRestConstants.TARGET_V1_ACTIONS) + .param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, String.valueOf(1)) + .param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, String.valueOf(1)) + .param(MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, String.valueOf(1)) + .param(MgmtRestConstants.REQUEST_PARAMETER_SORTING, "ID:ASC")) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) .andExpect(jsonPath("content.[0].id", equalTo(actions.get(1).getId().intValue()))) .andExpect(jsonPath("content.[0].type", equalTo("update"))) @@ -997,19 +1007,19 @@ public class TargetResourceTest extends AbstractIntegrationTest { } private String generateActionSelfLink(final String knownTargetId, final Action action) { - return "http://localhost" + RestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" - + RestConstants.TARGET_V1_ACTIONS + "/" + action.getId(); + return "http://localhost" + MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" + + MgmtRestConstants.TARGET_V1_ACTIONS + "/" + action.getId(); } private String generateCanceledactionreferenceLink(final String knownTargetId, final Action action) { - return "http://localhost" + RestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" - + RestConstants.TARGET_V1_ACTIONS + "/" + action.getId(); + return "http://localhost" + MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" + + MgmtRestConstants.TARGET_V1_ACTIONS + "/" + action.getId(); } private String generateStatusreferenceLink(final String knownTargetId, final Action action) { - return "http://localhost" + RestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" - + RestConstants.TARGET_V1_ACTIONS + "/" + action.getId() + "/" + RestConstants.TARGET_V1_ACTION_STATUS - + "?offset=0&limit=50&sort=id:DESC"; + return "http://localhost" + MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" + + MgmtRestConstants.TARGET_V1_ACTIONS + "/" + action.getId() + "/" + + MgmtRestConstants.TARGET_V1_ACTION_STATUS + "?offset=0&limit=50&sort=id:DESC"; } private List generateTargetWithTwoUpdatesWithOneOverride(final String knownTargetId) @@ -1029,7 +1039,7 @@ public class TargetResourceTest extends AbstractIntegrationTest { // Update final List updatedTargets = deploymentManagement.assignDistributionSet(one, targets) - .getAssignedTargets(); + .getAssignedEntity(); // 2nd update // sleep 10ms to ensure that we can sort by reportedAt Thread.sleep(10); @@ -1047,9 +1057,10 @@ public class TargetResourceTest extends AbstractIntegrationTest { final String knownTargetId = "targetId"; final List actions = generateTargetWithTwoUpdatesWithOneOverride(knownTargetId); - mvc.perform(get(RestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" - + RestConstants.TARGET_V1_ACTIONS + "/" + actions.get(1).getId())).andDo(MockMvcResultPrinter.print()) - .andExpect(status().isOk()).andExpect(jsonPath("id", equalTo(actions.get(1).getId().intValue()))) + mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" + + MgmtRestConstants.TARGET_V1_ACTIONS + "/" + actions.get(1).getId())) + .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) + .andExpect(jsonPath("id", equalTo(actions.get(1).getId().intValue()))) .andExpect(jsonPath("type", equalTo("update"))).andExpect(jsonPath("status", equalTo("pending"))) .andExpect(jsonPath("_links.self.href", equalTo(generateActionSelfLink(knownTargetId, actions.get(1))))) .andExpect(jsonPath("_links.distributionset.href", @@ -1066,7 +1077,7 @@ public class TargetResourceTest extends AbstractIntegrationTest { final DistributionSet set = TestDataUtil.generateDistributionSet("one", softwareManagement, distributionSetManagement); - mvc.perform(post(RestConstants.TARGET_V1_REQUEST_MAPPING + "/fsdfsd/assignedDS") + mvc.perform(post(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/fsdfsd/assignedDS") .content("{\"id\":" + set.getId() + "}").contentType(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); @@ -1084,7 +1095,7 @@ public class TargetResourceTest extends AbstractIntegrationTest { final String body = new JSONObject().put("id", set.getId()).put("type", "timeforced") .put("forcetime", forceTime).toString(); - mvc.perform(post(RestConstants.TARGET_V1_REQUEST_MAPPING + "/fsdfsd/assignedDS").content(body) + mvc.perform(post(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/fsdfsd/assignedDS").content(body) .contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()) .andExpect(status().isOk()); @@ -1101,25 +1112,25 @@ public class TargetResourceTest extends AbstractIntegrationTest { final DistributionSet set = TestDataUtil.generateDistributionSet("one", softwareManagement, distributionSetManagement); - mvc.perform(post(RestConstants.TARGET_V1_REQUEST_MAPPING + "/fsdfsd/assignedDS") + mvc.perform(post(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/fsdfsd/assignedDS") .content("{\"id\":" + set.getId() + "}").contentType(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound()); targetManagement.createTarget(new Target("fsdfsd")); - mvc.perform(post(RestConstants.TARGET_V1_REQUEST_MAPPING + "/fsdfsd/assignedDS") + mvc.perform(post(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/fsdfsd/assignedDS") .content("{\"id\":" + set.getId() + "}").contentType(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); - mvc.perform(post(RestConstants.TARGET_V1_REQUEST_MAPPING + "/fsdfsd/assignedDS").content("{\"id\":12345678}") - .contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()) - .andExpect(status().isNotFound()); + mvc.perform(post(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/fsdfsd/assignedDS") + .content("{\"id\":12345678}").contentType(MediaType.APPLICATION_JSON)) + .andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound()); - mvc.perform(delete(RestConstants.TARGET_V1_REQUEST_MAPPING + "/fsdfsd/assignedDS") + mvc.perform(delete(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/fsdfsd/assignedDS") .contentType(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()) .andExpect(status().isMethodNotAllowed()); - mvc.perform(put(RestConstants.TARGET_V1_REQUEST_MAPPING + "/fsdfsd/assignedDS") + mvc.perform(put(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/fsdfsd/assignedDS") .content("{\"id\":" + set.getId() + "}").contentType(MediaType.APPLICATION_JSON)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isMethodNotAllowed()); @@ -1130,28 +1141,28 @@ public class TargetResourceTest extends AbstractIntegrationTest { final String knownTargetId = "targetId"; // target does not exist - mvc.perform(get( - RestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" + RestConstants.TARGET_V1_ACTIONS)) - .andDo(MockMvcResultPrinter.print()).andExpect(status().isNotFound()); + mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" + + MgmtRestConstants.TARGET_V1_ACTIONS)).andDo(MockMvcResultPrinter.print()) + .andExpect(status().isNotFound()); final List actions = generateTargetWithTwoUpdatesWithOneOverride(knownTargetId); final Long actionId = actions.get(0).getId(); // should work now - mvc.perform(get(RestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" - + RestConstants.TARGET_V1_ACTIONS + "/" + actionId)).andDo(MockMvcResultPrinter.print()) + mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" + + MgmtRestConstants.TARGET_V1_ACTIONS + "/" + actionId)).andDo(MockMvcResultPrinter.print()) .andExpect(status().isOk()); // action does not exist - mvc.perform(get(RestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" - + RestConstants.TARGET_V1_ACTIONS + "/12321")).andDo(MockMvcResultPrinter.print()) + mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" + + MgmtRestConstants.TARGET_V1_ACTIONS + "/12321")).andDo(MockMvcResultPrinter.print()) .andExpect(status().isNotFound()); // not allowed methods - mvc.perform(put(RestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" - + RestConstants.TARGET_V1_ACTIONS + "/" + actionId)).andDo(MockMvcResultPrinter.print()) + mvc.perform(put(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" + + MgmtRestConstants.TARGET_V1_ACTIONS + "/" + actionId)).andDo(MockMvcResultPrinter.print()) .andExpect(status().isMethodNotAllowed()); - mvc.perform(post(RestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" - + RestConstants.TARGET_V1_ACTIONS + "/" + actionId)).andDo(MockMvcResultPrinter.print()) + mvc.perform(post(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" + + MgmtRestConstants.TARGET_V1_ACTIONS + "/" + actionId)).andDo(MockMvcResultPrinter.print()) .andExpect(status().isMethodNotAllowed()); } @@ -1160,31 +1171,31 @@ public class TargetResourceTest extends AbstractIntegrationTest { final String knownTargetId = "targetId"; // target does not exist - mvc.perform(get(RestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" - + RestConstants.TARGET_V1_ACTIONS + "/1/status")).andDo(MockMvcResultPrinter.print()) + mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" + + MgmtRestConstants.TARGET_V1_ACTIONS + "/1/status")).andDo(MockMvcResultPrinter.print()) .andExpect(status().isNotFound()); final List actions = generateTargetWithTwoUpdatesWithOneOverride(knownTargetId); final Long actionId = actions.get(0).getId(); // should work now - mvc.perform(get(RestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" - + RestConstants.TARGET_V1_ACTIONS + "/" + actionId + "/status")).andDo(MockMvcResultPrinter.print()) + mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" + + MgmtRestConstants.TARGET_V1_ACTIONS + "/" + actionId + "/status")).andDo(MockMvcResultPrinter.print()) .andExpect(status().isOk()); // action does not exist - mvc.perform(get(RestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" - + RestConstants.TARGET_V1_ACTIONS + "/12321/status")).andDo(MockMvcResultPrinter.print()) + mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" + + MgmtRestConstants.TARGET_V1_ACTIONS + "/12321/status")).andDo(MockMvcResultPrinter.print()) .andExpect(status().isNotFound()); // not allowed methods - mvc.perform(delete(RestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" - + RestConstants.TARGET_V1_ACTIONS + "/" + actionId + "/status")).andDo(MockMvcResultPrinter.print()) + mvc.perform(delete(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" + + MgmtRestConstants.TARGET_V1_ACTIONS + "/" + actionId + "/status")).andDo(MockMvcResultPrinter.print()) .andExpect(status().isMethodNotAllowed()); - mvc.perform(put(RestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" - + RestConstants.TARGET_V1_ACTIONS + "/" + actionId + "/status")).andDo(MockMvcResultPrinter.print()) + mvc.perform(put(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" + + MgmtRestConstants.TARGET_V1_ACTIONS + "/" + actionId + "/status")).andDo(MockMvcResultPrinter.print()) .andExpect(status().isMethodNotAllowed()); - mvc.perform(post(RestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" - + RestConstants.TARGET_V1_ACTIONS + "/" + actionId + "/status")).andDo(MockMvcResultPrinter.print()) + mvc.perform(post(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/" + + MgmtRestConstants.TARGET_V1_ACTIONS + "/" + actionId + "/status")).andDo(MockMvcResultPrinter.print()) .andExpect(status().isMethodNotAllowed()); } @@ -1200,7 +1211,7 @@ public class TargetResourceTest extends AbstractIntegrationTest { controllerManagament.updateControllerAttributes(knownTargetId, knownControllerAttrs); // test query target over rest resource - mvc.perform(get(RestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/attributes")) + mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/attributes")) .andDo(MockMvcResultPrinter.print()).andExpect(status().is2xxSuccessful()) .andExpect(jsonPath("$.a", equalTo("1"))).andExpect(jsonPath("$.b", equalTo("2"))); } @@ -1213,7 +1224,7 @@ public class TargetResourceTest extends AbstractIntegrationTest { targetManagement.createTarget(target); // test query target over rest resource - mvc.perform(get(RestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/attributes")) + mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + knownTargetId + "/attributes")) .andDo(MockMvcResultPrinter.print()).andExpect(status().is(HttpStatus.NO_CONTENT.value())); } @@ -1224,7 +1235,7 @@ public class TargetResourceTest extends AbstractIntegrationTest { final String rsqlFindAOrB = "controllerId==a,controllerId==b"; - mvc.perform(get(RestConstants.TARGET_V1_REQUEST_MAPPING + "?q=" + rsqlFindAOrB)) + mvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "?q=" + rsqlFindAOrB)) .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()).andExpect(jsonPath("size", equalTo(2))) .andExpect(jsonPath("total", equalTo(2))).andExpect(jsonPath("content[0].controllerId", equalTo("a"))) .andExpect(jsonPath("content[1].controllerId", equalTo("b"))); diff --git a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/ResourceUtility.java b/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/ResourceUtility.java similarity index 77% rename from hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/ResourceUtility.java rename to hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/ResourceUtility.java index 9e99031e9..e94d1b857 100644 --- a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/ResourceUtility.java +++ b/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/ResourceUtility.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.rest.resource; +package org.eclipse.hawkbit.mgmt.rest.resource; import java.io.IOException; -import org.eclipse.hawkbit.rest.resource.model.ExceptionInfo; -import org.eclipse.hawkbit.rest.resource.model.PagedList; -import org.eclipse.hawkbit.rest.resource.model.artifact.ArtifactRest; +import org.eclipse.hawkbit.mgmt.json.model.PagedList; +import org.eclipse.hawkbit.mgmt.json.model.artifact.MgmtArtifact; +import org.eclipse.hawkbit.rest.json.model.ExceptionInfo; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; @@ -33,9 +33,9 @@ public final class ResourceUtility { return mapper.readValue(jsonExceptionResponse, ExceptionInfo.class); } - static ArtifactRest convertArtifactResponse(final String jsonResponse) + static MgmtArtifact convertArtifactResponse(final String jsonResponse) throws JsonParseException, JsonMappingException, IOException { - return mapper.readValue(jsonResponse, ArtifactRest.class); + return mapper.readValue(jsonResponse, MgmtArtifact.class); } diff --git a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/SMRessourceMisingMongoDbConnectionTest.java b/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/SMRessourceMisingMongoDbConnectionTest.java similarity index 92% rename from hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/SMRessourceMisingMongoDbConnectionTest.java rename to hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/SMRessourceMisingMongoDbConnectionTest.java index 664dc861c..15d22c703 100644 --- a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/SMRessourceMisingMongoDbConnectionTest.java +++ b/hawkbit-mgmt-resource/src/test/java/org/eclipse/hawkbit/mgmt/rest/resource/SMRessourceMisingMongoDbConnectionTest.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource; +package org.eclipse.hawkbit.mgmt.rest.resource; import static org.fest.assertions.api.Assertions.assertThat; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.fileUpload; @@ -14,10 +14,10 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. import org.apache.commons.lang3.RandomStringUtils; import org.eclipse.hawkbit.AbstractIntegrationTest; -import org.eclipse.hawkbit.MockMvcResultPrinter; import org.eclipse.hawkbit.exception.SpServerError; import org.eclipse.hawkbit.repository.model.SoftwareModule; -import org.eclipse.hawkbit.rest.resource.model.ExceptionInfo; +import org.eclipse.hawkbit.rest.json.model.ExceptionInfo; +import org.eclipse.hawkbit.rest.util.MockMvcResultPrinter; import org.junit.BeforeClass; import org.junit.Test; import org.springframework.mock.web.MockMultipartFile; @@ -28,7 +28,8 @@ import ru.yandex.qatools.allure.annotations.Features; import ru.yandex.qatools.allure.annotations.Stories; /** - * Tests {@link SoftwareModuleResource} in case of missing MongoDB connection. + * Tests {@link MgmtSoftwareModuleResource} in case of missing MongoDB + * connection. * */ @Features("Component Tests - Management API") diff --git a/hawkbit-rest-resource/src/test/resources/application-test.properties b/hawkbit-mgmt-resource/src/test/resources/application-test.properties similarity index 100% rename from hawkbit-rest-resource/src/test/resources/application-test.properties rename to hawkbit-mgmt-resource/src/test/resources/application-test.properties diff --git a/hawkbit-rest-resource/src/test/resources/log4j2.xml b/hawkbit-mgmt-resource/src/test/resources/log4j2.xml similarity index 100% rename from hawkbit-rest-resource/src/test/resources/log4j2.xml rename to hawkbit-mgmt-resource/src/test/resources/log4j2.xml diff --git a/hawkbit-repository/pom.xml b/hawkbit-repository/pom.xml index 7259262de..28d20af3e 100644 --- a/hawkbit-repository/pom.xml +++ b/hawkbit-repository/pom.xml @@ -67,6 +67,10 @@ org.hibernate hibernate-validator + + javax.validation + validation-api + com.google.guava guava @@ -126,12 +130,6 @@ spring-context-support test - - org.eclipse.hawkbit - hawkbit-rest-api - ${project.version} - test - ru.yandex.qatools.allure allure-junit-adaptor diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/Constants.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/Constants.java index 5f3f772b0..ef0b70438 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/Constants.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/Constants.java @@ -11,9 +11,6 @@ package org.eclipse.hawkbit; /** * A constant class which holds only static constants used within the SP server. * - * - * - * */ public final class Constants { @@ -27,7 +24,7 @@ public final class Constants { public static final int MAX_ENTRIES_IN_STATEMENT = 999; /** - * constant class only private constructor. + * Constant class only private constructor. */ private Constants() { diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/MultiTenantJpaTransactionManager.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/MultiTenantJpaTransactionManager.java index 7b97f5037..b3821e5f3 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/MultiTenantJpaTransactionManager.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/MultiTenantJpaTransactionManager.java @@ -11,9 +11,6 @@ package org.eclipse.hawkbit; import javax.persistence.EntityManager; import javax.transaction.Transaction; -import org.eclipse.hawkbit.repository.RolloutManagement; -import org.eclipse.hawkbit.repository.SystemManagement; -import org.eclipse.hawkbit.repository.exception.TenantNotExistException; import org.eclipse.hawkbit.tenancy.TenantAware; import org.eclipse.persistence.config.PersistenceUnitProperties; import org.springframework.beans.factory.annotation.Autowired; @@ -38,38 +35,12 @@ public class MultiTenantJpaTransactionManager extends JpaTransactionManager { protected void doBegin(final Object transaction, final TransactionDefinition definition) { super.doBegin(transaction, definition); - final EntityManagerHolder emHolder = (EntityManagerHolder) TransactionSynchronizationManager - .getResource(getEntityManagerFactory()); - final EntityManager em = emHolder.getEntityManager(); - - if (notTenantManagement(definition) && notCurrentTenantKeyGenerator(definition) - && notRolloutScheduler(definition) && notGetOrCreateTenantMetadata(definition)) { - - final String currentTenant = tenantAware.getCurrentTenant(); - if (currentTenant == null) { - throw new TenantNotExistException("Tenant Unknown. Canceling transaction."); - } - + final String currentTenant = tenantAware.getCurrentTenant(); + if (currentTenant != null) { + final EntityManagerHolder emHolder = (EntityManagerHolder) TransactionSynchronizationManager + .getResource(getEntityManagerFactory()); + final EntityManager em = emHolder.getEntityManager(); em.setProperty(PersistenceUnitProperties.MULTITENANT_PROPERTY_DEFAULT, currentTenant.toUpperCase()); } } - - private boolean notGetOrCreateTenantMetadata(final TransactionDefinition definition) { - return !definition.getName() - .startsWith(SystemManagement.class.getCanonicalName() + ".getOrCreateTenantMetadata"); - } - - private boolean notRolloutScheduler(final TransactionDefinition definition) { - return !definition.getName().startsWith(RolloutManagement.class.getCanonicalName() + ".rolloutScheduler"); - } - - private boolean notCurrentTenantKeyGenerator(final TransactionDefinition definition) { - return !definition.getName() - .startsWith(SystemManagement.class.getCanonicalName() + ".currentTenantKeyGenerator"); - } - - private boolean notTenantManagement(final TransactionDefinition definition) { - return !definition.getName().startsWith(SystemManagement.class.getCanonicalName() + ".deleteTenant") - && !definition.getName().startsWith(SystemManagement.class.getCanonicalName() + ".findTenants"); - } } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/RepositoryApplicationConfiguration.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/RepositoryApplicationConfiguration.java index bf805f3dd..d5e8db96f 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/RepositoryApplicationConfiguration.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/RepositoryApplicationConfiguration.java @@ -13,13 +13,16 @@ import java.util.Map; import org.eclipse.hawkbit.aspects.ExceptionMappingAspectHandler; import org.eclipse.hawkbit.repository.SystemManagement; -import org.eclipse.hawkbit.repository.model.helper.AfterTransactionCommitExecutorHolder; import org.eclipse.hawkbit.repository.TenantConfigurationManagement; +import org.eclipse.hawkbit.repository.model.helper.AfterTransactionCommitExecutorHolder; import org.eclipse.hawkbit.repository.model.helper.CacheManagerHolder; import org.eclipse.hawkbit.repository.model.helper.SecurityTokenGeneratorHolder; import org.eclipse.hawkbit.repository.model.helper.SystemManagementHolder; +import org.eclipse.hawkbit.repository.model.helper.SystemSecurityContextHolder; import org.eclipse.hawkbit.repository.model.helper.TenantAwareHolder; +import org.eclipse.hawkbit.repository.model.helper.TenantConfigurationManagementHolder; import org.eclipse.hawkbit.security.SecurityTokenGenerator; +import org.eclipse.hawkbit.security.SystemSecurityContext; import org.eclipse.hawkbit.tenancy.TenantAware; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration; @@ -48,14 +51,24 @@ import org.springframework.validation.beanvalidation.MethodValidationPostProcess @EnableAutoConfiguration public class RepositoryApplicationConfiguration extends JpaBaseConfiguration { + /** + * @return the {@link SystemSecurityContext} singleton bean which make it + * accessible in beans which cannot access the service directly, + * e.g. JPA entities. + */ + @Bean + public SystemSecurityContextHolder systemSecurityContextHolder() { + return SystemSecurityContextHolder.getInstance(); + } + /** * @return the {@link TenantConfigurationManagement} singleton bean which * make it accessible in beans which cannot access the service * directly, e.g. JPA entities. */ @Bean - public TenantConfigurationManagement tenantConfigurationManagement() { - return TenantConfigurationManagement.getInstance(); + public TenantConfigurationManagementHolder tenantConfigurationManagementHolder() { + return TenantConfigurationManagementHolder.getInstance(); } /** @@ -127,23 +140,11 @@ public class RepositoryApplicationConfiguration extends JpaBaseConfiguration { return new ExceptionMappingAspectHandler(); } - /* - * (non-Javadoc) - * - * @see org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration# - * createJpaVendorAdapter() - */ @Override protected AbstractJpaVendorAdapter createJpaVendorAdapter() { return new EclipseLinkJpaVendorAdapter(); } - /* - * (non-Javadoc) - * - * @see org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration# - * getVendorProperties() - */ @Override protected Map getVendorProperties() { diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/aspects/ExceptionMappingAspectHandler.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/aspects/ExceptionMappingAspectHandler.java index 75145778e..c3da509aa 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/aspects/ExceptionMappingAspectHandler.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/aspects/ExceptionMappingAspectHandler.java @@ -90,6 +90,8 @@ public class ExceptionMappingAspectHandler implements Ordered { + " || execution( * org.eclipse.hawkbit.controller.*.*(..)) " + " || execution( * org.eclipse.hawkbit.rest.resource.*.*(..)) " + " || execution( * org.eclipse.hawkbit.service.*.*(..)) )", throwing = "ex") + // Exception squid:S00112 - Is aspectJ proxy + @SuppressWarnings({ "squid:S00112" }) public void catchAndWrapJpaExceptionsService(final Exception ex) throws Throwable { LOG.trace("exception occured", ex); Exception translatedAccessException = translateEclipseLinkExceptionIfPossible(ex); @@ -167,11 +169,6 @@ public class ExceptionMappingAspectHandler implements Ordered { return null; } - /* - * (non-Javadoc) - * - * @see org.springframework.core.Ordered#getOrder() - */ @Override public int getOrder() { return 1; diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/EntityChangeEventListener.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/EntityChangeEventListener.java index b25a72fbc..7bfbd957e 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/EntityChangeEventListener.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/EntityChangeEventListener.java @@ -20,9 +20,9 @@ import org.eclipse.hawkbit.eventbus.event.TargetDeletedEvent; import org.eclipse.hawkbit.eventbus.event.TargetInfoUpdateEvent; import org.eclipse.hawkbit.executor.AfterTransactionCommitExecutor; import org.eclipse.hawkbit.repository.TargetRepository; -import org.eclipse.hawkbit.repository.model.BaseEntity; import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.repository.model.TargetInfo; +import org.eclipse.hawkbit.repository.model.TenantAwareBaseEntity; import org.eclipse.hawkbit.tenancy.TenantAware; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @@ -31,7 +31,7 @@ import com.google.common.eventbus.EventBus; /** * An aspect implementation which wraps the necessary repository services for - * saving {@link BaseEntity}s to publish create or update events. + * saving {@link TenantAwareBaseEntity}s to publish create or update events. * * * @@ -67,6 +67,8 @@ public class EntityChangeEventListener { * {@link ProceedingJoinPoint#proceed()} */ @Around("execution(* org.eclipse.hawkbit.repository.TargetInfoRepository.save(..))") + // Exception squid:S00112 - Is aspectJ proxy + @SuppressWarnings({ "squid:S00112" }) public Object targetCreated(final ProceedingJoinPoint joinpoint) throws Throwable { final boolean isNew = isTargetInfoNew(joinpoint.getArgs()[0]); final Object result = joinpoint.proceed(); @@ -92,6 +94,8 @@ public class EntityChangeEventListener { * {@link ProceedingJoinPoint#proceed()} */ @Around("execution(* org.eclipse.hawkbit.repository.TargetRepository.deleteByIdIn(..))") + // Exception squid:S00112 - Is aspectJ proxy + @SuppressWarnings({ "squid:S00112" }) public Object targetDeletedById(final ProceedingJoinPoint joinpoint) throws Throwable { final String currentTenant = tenantAware.getCurrentTenant(); final Object result = joinpoint.proceed(); @@ -111,8 +115,9 @@ public class EntityChangeEventListener { * in case exception happens in the * {@link ProceedingJoinPoint#proceed()} */ - @SuppressWarnings("unchecked") @Around("execution(* org.eclipse.hawkbit.repository.TargetRepository.delete(..))") + // Exception squid:S00112 - Is aspectJ proxy + @SuppressWarnings({ "squid:S00112", "unchecked" }) public Object targetDeleted(final ProceedingJoinPoint joinpoint) throws Throwable { final String currentTenant = tenantAware.getCurrentTenant(); final Object result = joinpoint.proceed(); diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/EntityPropertyChangeListener.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/EntityPropertyChangeListener.java index 8b632ee6a..28b5e677c 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/EntityPropertyChangeListener.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/EntityPropertyChangeListener.java @@ -18,9 +18,9 @@ import org.eclipse.hawkbit.eventbus.event.RolloutGroupPropertyChangeEvent; import org.eclipse.hawkbit.eventbus.event.RolloutPropertyChangeEvent; import org.eclipse.hawkbit.executor.AfterTransactionCommitExecutor; import org.eclipse.hawkbit.repository.model.Action; -import org.eclipse.hawkbit.repository.model.BaseEntity; import org.eclipse.hawkbit.repository.model.Rollout; import org.eclipse.hawkbit.repository.model.RolloutGroup; +import org.eclipse.hawkbit.repository.model.TenantAwareBaseEntity; import org.eclipse.hawkbit.repository.model.helper.AfterTransactionCommitExecutorHolder; import org.eclipse.hawkbit.repository.model.helper.EventBusHolder; import org.eclipse.persistence.descriptors.DescriptorEvent; @@ -36,13 +36,7 @@ import com.google.common.eventbus.EventBus; * */ public class EntityPropertyChangeListener extends DescriptorEventAdapter { - /* - * (non-Javadoc) - * - * @see - * org.eclipse.persistence.descriptors.DescriptorEventAdapter#postInsert - * (org.eclipse.persistence.descriptors.DescriptorEvent) - */ + @Override public void postInsert(final DescriptorEvent event) { if (event.getObject().getClass().equals(Action.class)) { @@ -56,45 +50,30 @@ public class EntityPropertyChangeListener extends DescriptorEventAdapter { } - /* - * (non-Javadoc) - * - * @see - * org.eclipse.persistence.descriptors.DescriptorEventAdapter#postUpdate - * (org.eclipse.persistence.descriptors.DescriptorEvent) - */ @Override public void postUpdate(final DescriptorEvent event) { if (event.getObject().getClass().equals(Action.class)) { - getAfterTransactionCommmitExecutor().afterCommit( - () -> getEventBus() - .post(new ActionPropertyChangeEvent((Action) event.getObject(), getChangeSet(Action.class, - event)))); + getAfterTransactionCommmitExecutor().afterCommit(() -> getEventBus().post( + new ActionPropertyChangeEvent((Action) event.getObject(), getChangeSet(Action.class, event)))); } else if (event.getObject().getClass().equals(Rollout.class)) { - getAfterTransactionCommmitExecutor().afterCommit( - () -> getEventBus().post( - new RolloutPropertyChangeEvent((Rollout) event.getObject(), getChangeSet(Rollout.class, - event)))); + getAfterTransactionCommmitExecutor().afterCommit(() -> getEventBus().post( + new RolloutPropertyChangeEvent((Rollout) event.getObject(), getChangeSet(Rollout.class, event)))); } else if (event.getObject().getClass().equals(RolloutGroup.class)) { getAfterTransactionCommmitExecutor().afterCommit( - () -> getEventBus().post( - new RolloutGroupPropertyChangeEvent((RolloutGroup) event.getObject(), getChangeSet( - RolloutGroup.class, event)))); + () -> getEventBus().post(new RolloutGroupPropertyChangeEvent((RolloutGroup) event.getObject(), + getChangeSet(RolloutGroup.class, event)))); } } - private Map.Values> getChangeSet( + private Map.Values> getChangeSet( final Class clazz, final DescriptorEvent event) { final T rolloutGroup = clazz.cast(event.getObject()); final ObjectChangeSet changeSet = ((UpdateObjectQuery) event.getQuery()).getObjectChangeSet(); - return changeSet - .getChanges() - .stream() - .filter(record -> record instanceof DirectToFieldChangeRecord) + return changeSet.getChanges().stream().filter(record -> record instanceof DirectToFieldChangeRecord) .map(record -> (DirectToFieldChangeRecord) record) - .collect( - Collectors.toMap(record -> record.getAttribute(), record -> new AbstractPropertyChangeEvent( - rolloutGroup, null).new Values(record.getOldValue(), record.getNewValue()))); + .collect(Collectors.toMap(record -> record.getAttribute(), + record -> new AbstractPropertyChangeEvent(rolloutGroup, null).new Values( + record.getOldValue(), record.getNewValue()))); } private AfterTransactionCommitExecutor getAfterTransactionCommmitExecutor() { diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/AbstractBaseEntityEvent.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/AbstractBaseEntityEvent.java index 7d0973f74..d27669ade 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/AbstractBaseEntityEvent.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/AbstractBaseEntityEvent.java @@ -8,18 +8,19 @@ */ package org.eclipse.hawkbit.eventbus.event; -import org.eclipse.hawkbit.repository.model.BaseEntity; +import org.eclipse.hawkbit.repository.model.TenantAwareBaseEntity; /** - * An abstract definition class for {@link EntityEvent} for {@link BaseEntity}s, - * which holds the {@link BaseEntity}. + * An abstract definition class for {@link EntityEvent} for + * {@link TenantAwareBaseEntity}s, which holds the {@link TenantAwareBaseEntity} + * . * * * * @param - * the type of the {@link BaseEntity} + * the type of the {@link TenantAwareBaseEntity} */ -public abstract class AbstractBaseEntityEvent extends AbstractDistributedEvent +public abstract class AbstractBaseEntityEvent extends AbstractDistributedEvent implements EntityEvent { /** @@ -37,33 +38,16 @@ public abstract class AbstractBaseEntityEvent extends Abst this.entity = baseEntity; } - /* - * (non-Javadoc) - * - * @see org.eclipse.hawkbit.server.eventbus.event.EntityEvent#getEntity() - */ @Override public E getEntity() { return entity; } - /* - * (non-Javadoc) - * - * @see - * org.eclipse.hawkbit.server.eventbus.event.EntityEvent#getEntity(java.lang - * .Class) - */ @Override public T getEntity(final Class entityClass) { return entityClass.cast(entity); } - /* - * (non-Javadoc) - * - * @see org.eclipse.hawkbit.server.eventbus.event.EntityEvent#getTenant() - */ @Override public String getTenant() { return entity.getTenant(); diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/AbstractEntityBulkEvent.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/AbstractEntityBulkEvent.java index 0a0ce88ce..56f3e585a 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/AbstractEntityBulkEvent.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/AbstractEntityBulkEvent.java @@ -11,7 +11,7 @@ package org.eclipse.hawkbit.eventbus.event; import java.util.Arrays; import java.util.List; -import org.eclipse.hawkbit.repository.model.BaseEntity; +import org.eclipse.hawkbit.repository.model.TenantAwareBaseEntity; /** * @@ -19,7 +19,7 @@ import org.eclipse.hawkbit.repository.model.BaseEntity; * * @param */ -public abstract class AbstractEntityBulkEvent implements EntityBulkEvent { +public abstract class AbstractEntityBulkEvent implements EntityBulkEvent { private static final long serialVersionUID = 1L; diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/AbstractPropertyChangeEvent.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/AbstractPropertyChangeEvent.java index 8a596eeb5..795f6ff88 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/AbstractPropertyChangeEvent.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/AbstractPropertyChangeEvent.java @@ -10,14 +10,14 @@ package org.eclipse.hawkbit.eventbus.event; import java.util.Map; -import org.eclipse.hawkbit.repository.model.BaseEntity; +import org.eclipse.hawkbit.repository.model.TenantAwareBaseEntity; /** * Property change event. * * @param */ -public class AbstractPropertyChangeEvent extends AbstractBaseEntityEvent { +public class AbstractPropertyChangeEvent extends AbstractBaseEntityEvent { private static final long serialVersionUID = -3671601415138242311L; private final transient Map changeSet; diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/DistributionSetTagAssigmentResultEvent.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/DistributionSetTagAssigmentResultEvent.java index 9a8a485b4..e10b9a51f 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/DistributionSetTagAssigmentResultEvent.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/DistributionSetTagAssigmentResultEvent.java @@ -8,14 +8,14 @@ */ package org.eclipse.hawkbit.eventbus.event; -import org.eclipse.hawkbit.repository.model.DistributionSetTagAssigmentResult; +import org.eclipse.hawkbit.repository.model.DistributionSetTagAssignmentResult; /** * A event for assignment target tag. */ public class DistributionSetTagAssigmentResultEvent { - private final DistributionSetTagAssigmentResult assigmentResult; + private final DistributionSetTagAssignmentResult assigmentResult; /** * Constructor. @@ -23,11 +23,11 @@ public class DistributionSetTagAssigmentResultEvent { * @param assigmentResult * the assignment result- */ - public DistributionSetTagAssigmentResultEvent(final DistributionSetTagAssigmentResult assigmentResult) { + public DistributionSetTagAssigmentResultEvent(final DistributionSetTagAssignmentResult assigmentResult) { this.assigmentResult = assigmentResult; } - public DistributionSetTagAssigmentResult getAssigmentResult() { + public DistributionSetTagAssignmentResult getAssigmentResult() { return assigmentResult; } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/EntityBulkEvent.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/EntityBulkEvent.java index 2004d3017..eac1b6bb9 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/EntityBulkEvent.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/EntityBulkEvent.java @@ -11,7 +11,7 @@ package org.eclipse.hawkbit.eventbus.event; import java.io.Serializable; import java.util.List; -import org.eclipse.hawkbit.repository.model.BaseEntity; +import org.eclipse.hawkbit.repository.model.TenantAwareBaseEntity; /** * An event interface which declares event types that an entities has been @@ -20,7 +20,7 @@ import org.eclipse.hawkbit.repository.model.BaseEntity; * @param * the entity type */ -public interface EntityBulkEvent extends Serializable, Event { +public interface EntityBulkEvent extends Serializable, Event { /** * A typesafe way to retrieve the the entities from the event, which might diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/TargetAssignDistributionSetEvent.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/TargetAssignDistributionSetEvent.java index b286ac6ea..68b3f1289 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/TargetAssignDistributionSetEvent.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/TargetAssignDistributionSetEvent.java @@ -16,8 +16,6 @@ import org.eclipse.hawkbit.repository.model.SoftwareModule; /** * Event that gets sent when a distribution set gets assigned to a target. * - * - * */ public class TargetAssignDistributionSetEvent extends AbstractEvent { @@ -25,6 +23,7 @@ public class TargetAssignDistributionSetEvent extends AbstractEvent { private final String controllerId; private final Long actionId; private final URI targetAdress; + private final String targetToken; /** * Creates a new {@link TargetAssignDistributionSetEvent}. @@ -41,14 +40,18 @@ public class TargetAssignDistributionSetEvent extends AbstractEvent { * the software modules which have been assigned to the target * @param targetAdress * the targetAdress of the target + * @param targetToken + * the authentication token of the target */ public TargetAssignDistributionSetEvent(final long revision, final String tenant, final String controllerId, - final Long actionId, final Collection softwareModules, final URI targetAdress) { + final Long actionId, final Collection softwareModules, final URI targetAdress, + final String targetToken) { super(revision, tenant); this.controllerId = controllerId; this.actionId = actionId; this.softwareModules = softwareModules; this.targetAdress = targetAdress; + this.targetToken = targetToken; } /** @@ -77,4 +80,7 @@ public class TargetAssignDistributionSetEvent extends AbstractEvent { return targetAdress; } + public String getTargetToken() { + return targetToken; + } } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/TargetTagAssigmentResultEvent.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/TargetTagAssigmentResultEvent.java index 405595de0..6bdc3aebd 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/TargetTagAssigmentResultEvent.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/eventbus/event/TargetTagAssigmentResultEvent.java @@ -8,14 +8,14 @@ */ package org.eclipse.hawkbit.eventbus.event; -import org.eclipse.hawkbit.repository.model.TargetTagAssigmentResult; +import org.eclipse.hawkbit.repository.model.TargetTagAssignmentResult; /** * A event for assignment target tag. */ public class TargetTagAssigmentResultEvent { - private final TargetTagAssigmentResult assigmentResult; + private final TargetTagAssignmentResult assigmentResult; /** * Constructor. @@ -23,11 +23,11 @@ public class TargetTagAssigmentResultEvent { * @param assigmentResult * the assignment result- */ - public TargetTagAssigmentResultEvent(final TargetTagAssigmentResult assigmentResult) { + public TargetTagAssigmentResultEvent(final TargetTagAssignmentResult assigmentResult) { this.assigmentResult = assigmentResult; } - public TargetTagAssigmentResult getAssigmentResult() { + public TargetTagAssignmentResult getAssigmentResult() { return assigmentResult; } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/executor/AfterTransactionCommitDefaultServiceExecutor.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/executor/AfterTransactionCommitDefaultServiceExecutor.java index 38ad38345..0d65b291e 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/executor/AfterTransactionCommitDefaultServiceExecutor.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/executor/AfterTransactionCommitDefaultServiceExecutor.java @@ -29,6 +29,8 @@ public class AfterTransactionCommitDefaultServiceExecutor extends TransactionSyn private static final ThreadLocal> THREAD_LOCAL_RUNNABLES = new ThreadLocal<>(); @Override + // Exception squid:S1217 - Is aspectJ proxy + @SuppressWarnings({ "squid:S1217" }) public void afterCommit() { final List afterCommitRunnables = THREAD_LOCAL_RUNNABLES.get(); LOGGER.debug("Transaction successfully committed, executing {} runnables", afterCommitRunnables.size()); @@ -60,6 +62,7 @@ public class AfterTransactionCommitDefaultServiceExecutor extends TransactionSyn } @Override + @SuppressWarnings({ "squid:S1217" }) public void afterCompletion(final int status) { final String transactionStatus = status == STATUS_COMMITTED ? "COMMITTED" : "ROLLEDBACK"; LOGGER.debug("Transaction completed after commit with status {}", transactionStatus); diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ActionRepository.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ActionRepository.java index 8221fa0ca..742a7d731 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ActionRepository.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ActionRepository.java @@ -29,13 +29,14 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; +import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Transactional; /** * {@link Action} repository. * */ -@Transactional(readOnly = true) +@Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) public interface ActionRepository extends BaseEntityRepository, JpaSpecificationExecutor { /** * Retrieves an Action with all lazy attributes. @@ -172,7 +173,7 @@ public interface ActionRepository extends BaseEntityRepository, Jp * active */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @Query("UPDATE Action a SET a.active = false WHERE a IN :keySet AND a.target IN :targetsIds") void setToInactive(@Param("keySet") List keySet, @Param("targetsIds") List targetsIds); @@ -191,7 +192,7 @@ public interface ActionRepository extends BaseEntityRepository, Jp * the current status of the actions which are affected */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @Query("UPDATE Action a SET a.status = :statusToSet WHERE a.target IN :targetsIds AND a.active = :active AND a.status = :currentStatus AND a.distributionSet.requiredMigrationStep = false") void switchStatus(@Param("statusToSet") Action.Status statusToSet, @Param("targetsIds") List targetIds, @Param("active") boolean active, @Param("currentStatus") Action.Status currentStatus); @@ -211,7 +212,7 @@ public interface ActionRepository extends BaseEntityRepository, Jp * the current status of the actions which are affected */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @Query("UPDATE Action a SET a.status = :statusToSet WHERE a.rollout = :rollout AND a.active = :active AND a.status = :currentStatus") void switchStatus(@Param("statusToSet") Action.Status statusToSet, @Param("rollout") Rollout rollout, @Param("active") boolean active, @Param("currentStatus") Action.Status currentStatus); @@ -386,6 +387,4 @@ public interface ActionRepository extends BaseEntityRepository, Jp @Query("SELECT NEW org.eclipse.hawkbit.repository.model.TotalTargetCountActionStatus(a.rolloutGroup.id, a.status , COUNT(a.target)) FROM Action a WHERE a.rolloutGroup.id IN ?1 GROUP BY a.rolloutGroup.id, a.status") List getStatusCountByRolloutGroupId(List rolloutGroupId); - // Asha-ends here - } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ActionStatusRepository.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ActionStatusRepository.java index 2705b9ac6..2a0e8cfb3 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ActionStatusRepository.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ActionStatusRepository.java @@ -16,13 +16,14 @@ import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.EntityGraph; import org.springframework.data.jpa.repository.EntityGraph.EntityGraphType; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; +import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Transactional; /** * {@link ActionStatus} repository. * */ -@Transactional(readOnly = true) +@Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) public interface ActionStatusRepository extends BaseEntityRepository, JpaSpecificationExecutor { 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..024ec11cb 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 @@ -43,17 +43,15 @@ import org.springframework.data.jpa.repository.Modifying; import org.springframework.hateoas.Identifiable; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Transactional; import org.springframework.validation.annotation.Validated; /** - * service for {@link Artifact} management operations. - * - * - * + * Service for {@link Artifact} management operations. * */ -@Transactional(readOnly = true) +@Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) @Validated @Service public class ArtifactManagement { @@ -108,7 +106,7 @@ public class ArtifactManagement { * if check against provided SHA1 checksum failed */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY) public LocalArtifact createLocalArtifact(@NotNull final InputStream stream, @NotNull final Long moduleId, @NotEmpty final String filename, final String providedMd5Sum, final String providedSha1Sum, @@ -138,7 +136,7 @@ public class ArtifactManagement { return storeArtifactMetadata(softwareModule, filename, result, existing); } - private LocalArtifact checkForExistingArtifact(final String filename, final boolean overrideExisting, + private static LocalArtifact checkForExistingArtifact(final String filename, final boolean overrideExisting, final SoftwareModule softwareModule) { if (softwareModule.getLocalArtifactByFilename(filename).isPresent()) { if (overrideExisting) { @@ -222,9 +220,7 @@ public class ArtifactManagement { artifact.setSize(result.getSize()); LOG.debug("storing new artifact into repository {}", artifact); - final LocalArtifact artifactPersisted = localArtifactRepository.save(artifact); - - return artifactPersisted; + return localArtifactRepository.save(artifact); } /** @@ -242,7 +238,7 @@ public class ArtifactManagement { * @return created {@link ExternalArtifactProvider} */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY) public ExternalArtifactProvider createExternalArtifactProvider(@NotEmpty final String name, final String description, @NotNull final String basePath, final String defaultUrlSuffix) { @@ -268,16 +264,13 @@ public class ArtifactManagement { * if {@link SoftwareModule} with given ID does not exist */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY) public ExternalArtifact createExternalArtifact(@NotNull final ExternalArtifactProvider externalRepository, final String urlSuffix, @NotNull final Long moduleId) { final SoftwareModule module = getModuleAndThrowExceptionIfThatFails(moduleId); - final ExternalArtifact result = externalArtifactRepository - .save(new ExternalArtifact(externalRepository, urlSuffix, module)); - - return result; + return externalArtifactRepository.save(new ExternalArtifact(externalRepository, urlSuffix, module)); } /** @@ -290,7 +283,7 @@ public class ArtifactManagement { * */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_REPOSITORY) public void deleteLocalArtifact(@NotNull final Long id) { final LocalArtifact existing = localArtifactRepository.findOne(id); @@ -313,7 +306,7 @@ public class ArtifactManagement { * the related local artifact */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_REPOSITORY) public void deleteGridFsArtifact(@NotNull final LocalArtifact existing) { if (existing == null) { @@ -321,9 +314,10 @@ 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()) { + && Long.compare(lArtifact.getSoftwareModule().getId(), existing.getSoftwareModule().getId()) != 0) { artifactIsOnlyUsedByOneSoftwareModule = false; break; } @@ -349,7 +343,7 @@ public class ArtifactManagement { * */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_REPOSITORY) public void deleteExternalArtifact(@NotNull final Long id) { final ExternalArtifact existing = externalArtifactRepository.findOne(id); @@ -403,7 +397,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) { @@ -424,17 +418,17 @@ public class ArtifactManagement { * @param filename * of the artifact * @param overrideExisting - * to true if the artifact binary can be overdiden + * to true if the artifact binary can be overridden * if it already exists * @param contentType * the contentType of the file * * @return uploaded {@link LocalArtifact} * - * @throw ArtifactUploadFailedException if upload failes + * @throw ArtifactUploadFailedException if upload fails */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) public LocalArtifact createLocalArtifact(final InputStream inputStream, final Long moduleId, final String filename, final boolean overrideExisting, final String contentType) { @@ -460,7 +454,7 @@ public class ArtifactManagement { * @throw ArtifactUploadFailedException if upload failes */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) public LocalArtifact createLocalArtifact(final InputStream inputStream, final Long moduleId, final String filename, final boolean overrideExisting) { diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/BaseEntityRepository.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/BaseEntityRepository.java index 539d20f71..16f80596d 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/BaseEntityRepository.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/BaseEntityRepository.java @@ -10,17 +10,15 @@ package org.eclipse.hawkbit.repository; import java.io.Serializable; -import org.eclipse.hawkbit.repository.model.BaseEntity; +import org.eclipse.hawkbit.repository.model.TenantAwareBaseEntity; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.repository.NoRepositoryBean; import org.springframework.data.repository.PagingAndSortingRepository; +import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Transactional; /** - * Command repository operations for all {@link BaseEntity}s. - * - * - * + * Command repository operations for all {@link TenantAwareBaseEntity}s. * * @param * type if the entity type @@ -28,18 +26,18 @@ import org.springframework.transaction.annotation.Transactional; * of the entity type */ @NoRepositoryBean -@Transactional(readOnly = true) -public interface BaseEntityRepository +@Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) +public interface BaseEntityRepository extends PagingAndSortingRepository { /** - * Deletes all {@link BaseEntity} of a given tenant. + * Deletes all {@link TenantAwareBaseEntity} of a given tenant. * * @param tenant * to delete data from */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) void deleteByTenantIgnoreCase(String tenant); } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ControllerManagement.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ControllerManagement.java index 7131bbe0a..11879edfd 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ControllerManagement.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ControllerManagement.java @@ -28,12 +28,14 @@ import org.eclipse.hawkbit.repository.model.Action.Status; import org.eclipse.hawkbit.repository.model.ActionStatus; import org.eclipse.hawkbit.repository.model.ActionStatus_; 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.repository.model.Target; import org.eclipse.hawkbit.repository.model.TargetInfo; import org.eclipse.hawkbit.repository.model.TargetUpdateStatus; import org.eclipse.hawkbit.repository.model.Target_; import org.eclipse.hawkbit.repository.model.TenantConfiguration; +import org.eclipse.hawkbit.repository.specifications.ActionSpecifications; import org.eclipse.hawkbit.security.HawkbitSecurityProperties; import org.eclipse.hawkbit.tenancy.configuration.TenantConfigurationKey; import org.hibernate.validator.constraints.NotEmpty; @@ -44,6 +46,7 @@ import org.springframework.data.jpa.domain.Specification; import org.springframework.data.jpa.repository.Modifying; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Transactional; import org.springframework.validation.annotation.Validated; @@ -54,13 +57,15 @@ import org.springframework.validation.annotation.Validated; * * */ -@Transactional(readOnly = true) +@Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) @Validated @Service public class ControllerManagement { private static final Logger LOG = LoggerFactory.getLogger(ControllerManagement.class); private static final Logger LOG_DOS = LoggerFactory.getLogger("server-security.dos"); + public static final String SERVER_MESSAGE_PREFIX = "Update Server: "; + @Autowired private EntityManager entityManager; @@ -129,7 +134,7 @@ public class ControllerManagement { * if target with given ID could not be found */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @PreAuthorize(SpringEvalExpressions.IS_CONTROLLER) public Target updateLastTargetQuery(@NotEmpty final String targetid, final URI address) { final Target target = targetRepository.findByControllerId(targetid); @@ -166,6 +171,31 @@ public class ControllerManagement { return action.get(0); } + /** + * Checks if a given target has currently or has even been assigned to the + * given artifact through the action history list. This can e.g. indicate if + * a target is allowed to download a given artifact because it has currently + * assigned or had ever been assigned to the target and so it's visible to a + * specific target e.g. for downloading. + * + * @param targetId + * the ID of the target to check + * @param localArtifact + * the artifact to verify if the given target had even been + * assigned to + * @return {@code true} if the given target has currently or had ever a + * relation to the given artifact through the action history, + * otherwise {@code false} + */ + public boolean hasTargetArtifactAssigned(@NotNull final String targetId, + @NotNull final LocalArtifact localArtifact) { + final Target target = targetRepository.findByControllerId(targetId); + if (target == null) { + return false; + } + return actionRepository.count(ActionSpecifications.hasTargetAssignedArtifact(target, localArtifact)) > 0; + } + /** * Refreshes the time of the last time the controller has been connected to * the server. @@ -178,7 +208,7 @@ public class ControllerManagement { * */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @PreAuthorize(SpringEvalExpressions.IS_CONTROLLER) public TargetInfo updateLastTargetQuery(@NotNull final TargetInfo target, final URI address) { return updateTargetStatus(target, null, System.currentTimeMillis(), address); @@ -235,7 +265,7 @@ public class ControllerManagement { * @return target reference */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @PreAuthorize(SpringEvalExpressions.IS_CONTROLLER) public Target findOrRegisterTargetIfItDoesNotexist(@NotEmpty final String targetid, final URI address) { final Specification spec = (targetRoot, query, cb) -> cb.equal(targetRoot.get(Target_.controllerId), @@ -271,7 +301,7 @@ public class ControllerManagement { * @return the updated TargetInfo */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @PreAuthorize(SpringEvalExpressions.IS_CONTROLLER) public TargetInfo updateTargetStatus(@NotNull final TargetInfo targetInfo, final TargetUpdateStatus status, final Long lastTargetQuery, final URI address) { @@ -300,7 +330,7 @@ public class ControllerManagement { * */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @PreAuthorize(SpringEvalExpressions.IS_CONTROLLER) public Action addCancelActionStatus(@NotNull final ActionStatus actionStatus, final Action action) { @@ -314,13 +344,14 @@ public class ControllerManagement { break; case CANCELED: case FINISHED: - // in case of successful cancelation we also report the success at + // in case of successful cancellation we also report the success at // the canceled action itself. - actionStatus.addMessage("Cancelation completion is finished sucessfully."); + actionStatus.addMessage( + ControllerManagement.SERVER_MESSAGE_PREFIX + "Cancellation completion is finished sucessfully."); deploymentManagement.successCancellation(action); break; case RETRIEVED: - actionStatus.addMessage("Cancelation request retrieved"); + actionStatus.addMessage(ControllerManagement.SERVER_MESSAGE_PREFIX + "Cancellation request retrieved."); break; default: } @@ -346,7 +377,7 @@ public class ControllerManagement { * inserted */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @PreAuthorize(SpringEvalExpressions.IS_CONTROLLER) public Action addUpdateActionStatus(@NotNull final ActionStatus actionStatus, final Action action) { @@ -376,16 +407,9 @@ public class ControllerManagement { switch (actionStatus.getStatus()) { case ERROR: mergedTarget = deploymentManagement.updateTargetInfo(mergedTarget, TargetUpdateStatus.ERROR, false); - // set action inactive - mergedAction.setActive(false); - mergedAction.setStatus(Status.ERROR); - mergedTarget.setAssignedDistributionSet(null); - targetManagement.updateTarget(mergedTarget); + handleErrorOnAction(mergedAction, mergedTarget); break; case FINISHED: - // set action inactive - mergedAction.setActive(false); - mergedAction.setStatus(Status.FINISHED); handleFinishedAndStoreInTargetStatus(mergedTarget, mergedAction); break; case CANCELED: @@ -404,6 +428,13 @@ public class ControllerManagement { return actionRepository.save(mergedAction); } + private void handleErrorOnAction(final Action mergedAction, final Target mergedTarget) { + mergedAction.setActive(false); + mergedAction.setStatus(Status.ERROR); + mergedTarget.setAssignedDistributionSet(null); + targetManagement.updateTarget(mergedTarget); + } + private void checkForToManyStatusEntries(final Action action) { if (securityProperties.getDos().getMaxStatusEntriesPerAction() > 0) { @@ -420,6 +451,8 @@ public class ControllerManagement { } private void handleFinishedAndStoreInTargetStatus(final Target target, final Action action) { + action.setActive(false); + action.setStatus(Status.FINISHED); final TargetInfo targetInfo = target.getTargetInfo(); final DistributionSet ds = entityManager.merge(action.getDistributionSet()); targetInfo.setInstalledDistributionSet(ds); @@ -452,7 +485,7 @@ public class ControllerManagement { */ @Modifying @NotNull - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @PreAuthorize(SpringEvalExpressions.IS_CONTROLLER) public Target updateControllerAttributes(@NotEmpty final String targetid, @NotNull final Map data) { final Target target = targetRepository.findByControllerId(targetid); @@ -490,7 +523,7 @@ public class ControllerManagement { * {@link Status#RETRIEVED} */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @PreAuthorize(SpringEvalExpressions.IS_CONTROLLER) public Action registerRetrieved(final Action action, final String message) { return handleRegisterRetrieved(action, message); @@ -554,7 +587,7 @@ public class ControllerManagement { */ @PreAuthorize(SpringEvalExpressions.IS_CONTROLLER) @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) public void addActionStatusMessage(final ActionStatus statusMessage) { actionStatusRepository.save(statusMessage); } @@ -571,7 +604,7 @@ public class ControllerManagement { * @return the security context of the target, in case no target exists for * the given controllerId {@code null} is returned */ - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) public String getSecurityTokenByControllerId(final String controllerId) { final Target target = targetRepository.findByControllerId(controllerId); return target != null ? target.getSecurityToken() : null; diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DeploymentManagement.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DeploymentManagement.java index 77f71bebf..1e58ea938 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DeploymentManagement.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DeploymentManagement.java @@ -54,6 +54,7 @@ import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.repository.model.TargetInfo; import org.eclipse.hawkbit.repository.model.TargetUpdateStatus; import org.eclipse.hawkbit.repository.specifications.TargetSpecifications; +import org.eclipse.hawkbit.security.SystemSecurityContext; import org.hibernate.validator.constraints.NotEmpty; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -67,6 +68,7 @@ import org.springframework.data.jpa.domain.Specification; import org.springframework.data.jpa.repository.Modifying; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Transactional; import org.springframework.validation.annotation.Validated; @@ -78,7 +80,7 @@ import com.google.common.eventbus.EventBus; * * */ -@Transactional(readOnly = true) +@Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) @Validated @Service public class DeploymentManagement { @@ -117,6 +119,9 @@ public class DeploymentManagement { @Autowired private AfterTransactionCommitExecutor afterCommit; + @Autowired + private SystemSecurityContext systemSecurityContext; + /** * method assigns the {@link DistributionSet} to all {@link Target}s. * @@ -133,7 +138,7 @@ public class DeploymentManagement { * {@link SoftwareModuleType} are not assigned as define by the * {@link DistributionSetType}. * */ - @Transactional + @Transactional(isolation = Isolation.READ_COMMITTED) @Modifying @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY_AND_UPDATE_TARGET) @CacheEvict(value = { "distributionUsageAssigned" }, allEntries = true) @@ -167,7 +172,7 @@ public class DeploymentManagement { * {@link DistributionSetType}. */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_COMMITTED) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY_AND_UPDATE_TARGET) @CacheEvict(value = { "distributionUsageAssigned" }, allEntries = true) public DistributionSetAssignmentResult assignDistributionSet(@NotNull final Long dsID, @@ -195,9 +200,12 @@ public class DeploymentManagement { * {@link DistributionSetType}. */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY_AND_UPDATE_TARGET) @CacheEvict(value = { "distributionUsageAssigned" }, allEntries = true) + // Exception squid:S2095: see + // https://jira.sonarsource.com/browse/SONARJAVA-1478 + @SuppressWarnings({ "squid:S2095" }) public DistributionSetAssignmentResult assignDistributionSet(@NotNull final Long dsID, final ActionType actionType, final long forcedTimestamp, @NotEmpty final String... targetIDs) { return assignDistributionSet(dsID, Arrays.stream(targetIDs) @@ -219,7 +227,7 @@ public class DeploymentManagement { * {@link DistributionSetType}. */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_COMMITTED) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY_AND_UPDATE_TARGET) @CacheEvict(value = { "distributionUsageAssigned" }, allEntries = true) public DistributionSetAssignmentResult assignDistributionSet(@NotNull final Long dsID, @@ -243,8 +251,8 @@ public class DeploymentManagement { * a list of all targets and their action type * @param rollout * the rollout for this assignment - * @param rolloutgroup - * the rolloutgroup for this assignment + * @param rolloutGroup + * the rollout group for this assignment * @return the assignment result * * @throw IncompleteDistributionSetException if mandatory @@ -252,7 +260,7 @@ public class DeploymentManagement { * {@link DistributionSetType}. */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_COMMITTED) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY_AND_UPDATE_TARGET) @CacheEvict(value = { "distributionUsageAssigned" }, allEntries = true) public DistributionSetAssignmentResult assignDistributionSet(@NotNull final Long dsID, @@ -276,8 +284,8 @@ public class DeploymentManagement { * a list of all targets and their action type * @param rollout * the rollout for this assignment - * @param rolloutgroup - * the rolloutgroup for this assignment + * @param rolloutGroup + * the rollout group for this assignment * @return the assignment result * * @throw IncompleteDistributionSetException if mandatory @@ -389,8 +397,8 @@ public class DeploymentManagement { softwareModules)); } - private Action createTargetAction(final Map targetsWithActionMap, final Target target, - final DistributionSet set, final Rollout rollout, final RolloutGroup rolloutGroup) { + private static Action createTargetAction(final Map targetsWithActionMap, + final Target target, final DistributionSet set, final Rollout rollout, final RolloutGroup rolloutGroup) { final Action actionForTarget = new Action(); final TargetWithActionType targetWithActionType = targetsWithActionMap.get(target.getControllerId()); actionForTarget.setActionType(targetWithActionType.getActionType()); @@ -418,16 +426,20 @@ public class DeploymentManagement { private void assignDistributionSetEvent(final Target target, final Long actionId, final List softwareModules) { target.getTargetInfo().setUpdateStatus(TargetUpdateStatus.PENDING); + final String targetSecurityToken = systemSecurityContext.runAsSystem(() -> { + return target.getSecurityToken(); + }); afterCommit.afterCommit(() -> { eventBus.post(new TargetInfoUpdateEvent(target.getTargetInfo())); eventBus.post(new TargetAssignDistributionSetEvent(target.getOptLockRevision(), target.getTenant(), - target.getControllerId(), actionId, softwareModules, target.getTargetInfo().getAddress())); + target.getControllerId(), actionId, softwareModules, target.getTargetInfo().getAddress(), + targetSecurityToken)); }); } /** * Removes {@link UpdateAction}s that are no longer necessary and sends - * cancelations to the controller. + * cancellations to the controller. * * @param myTarget * to override {@link UpdateAction}s @@ -512,7 +524,7 @@ public class DeploymentManagement { * action */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_COMMITTED) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_TARGET) public Action cancelAction(@NotNull final Action action, @NotNull final Target target) { LOG.debug("cancelAction({}, {})", action, target); @@ -569,7 +581,7 @@ public class DeploymentManagement { * in case the given action is not active */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_COMMITTED) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_TARGET) public Action forceQuitAction(@NotNull final Action action) { final Action mergedAction = entityManager.merge(action); @@ -614,7 +626,7 @@ public class DeploymentManagement { * the rolloutgroup for this action */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_COMMITTED) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_TARGET) public void createScheduledAction(final List targets, final DistributionSet distributionSet, final ActionType actionType, final long forcedTime, final Rollout rollout, @@ -648,7 +660,7 @@ public class DeploymentManagement { * @return the action which has been started */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_COMMITTED) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET + SpringEvalExpressions.HAS_AUTH_OR + SpringEvalExpressions.IS_SYSTEM_CODE) public Action startScheduledAction(@NotNull final Action action) { @@ -911,7 +923,7 @@ public class DeploymentManagement { * @return the updated or the found {@link TargetAction} */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_TARGET) public Action forceTargetAction(final Long actionId) { final Action action = actionRepository.findOne(actionId); @@ -923,7 +935,7 @@ public class DeploymentManagement { } /** - * retrieves all the {@link ActionStatus} entries of the given + * Retrieves all the {@link ActionStatus} entries of the given * {@link Action} and {@link Target}. * * @param pageReq @@ -981,11 +993,11 @@ public class DeploymentManagement { * @param rollout * the rollout the actions belong to * @param rolloutGroupParent - * the parent rolloutgroup the actions should reference + * the parent rollout group the actions should reference * @param actionStatus * the status the actions have * @return the actions referring a specific rollout and a specific parent - * rolloutgroup in a specific status + * rollout group in a specific status */ @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET + SpringEvalExpressions.HAS_AUTH_OR + SpringEvalExpressions.IS_SYSTEM_CODE) diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DistributionSetAssignmentResult.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DistributionSetAssignmentResult.java index 3e61e4499..85e707652 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DistributionSetAssignmentResult.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DistributionSetAssignmentResult.java @@ -8,6 +8,7 @@ */ package org.eclipse.hawkbit.repository; +import java.util.Collections; import java.util.List; import org.eclipse.hawkbit.repository.model.AssignmentResult; @@ -19,7 +20,7 @@ import org.eclipse.hawkbit.repository.model.Target; * how much of the assignments had already been existed. * */ -public class DistributionSetAssignmentResult extends AssignmentResult { +public class DistributionSetAssignmentResult extends AssignmentResult { private final List assignedTargets; private final List actions; @@ -45,17 +46,15 @@ public class DistributionSetAssignmentResult extends AssignmentResult { */ public DistributionSetAssignmentResult(final List assignedTargets, final int assigned, final int alreadyAssigned, final List actions, final TargetManagement targetManagement) { - super(assigned, alreadyAssigned); + super(assigned, alreadyAssigned, 0, Collections.emptyList(), Collections.emptyList()); this.assignedTargets = assignedTargets; this.actions = actions; this.targetManagement = targetManagement; } - - /** - * @return the assignedTargets - */ - public List getAssignedTargets() { - return targetManagement.findTargetsByControllerID(assignedTargets); + + @Override + public List getAssignedEntity() { + return targetManagement.findTargetByControllerID(assignedTargets); } /** diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DistributionSetManagement.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DistributionSetManagement.java index 8b07c9bf8..db1ade60e 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DistributionSetManagement.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DistributionSetManagement.java @@ -38,7 +38,7 @@ import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.DistributionSetMetadata; import org.eclipse.hawkbit.repository.model.DistributionSetMetadata_; import org.eclipse.hawkbit.repository.model.DistributionSetTag; -import org.eclipse.hawkbit.repository.model.DistributionSetTagAssigmentResult; +import org.eclipse.hawkbit.repository.model.DistributionSetTagAssignmentResult; import org.eclipse.hawkbit.repository.model.DistributionSetType; import org.eclipse.hawkbit.repository.model.DistributionSetTypeElement; import org.eclipse.hawkbit.repository.model.DistributionSet_; @@ -59,6 +59,7 @@ import org.springframework.data.jpa.domain.Specification; import org.springframework.data.jpa.repository.Modifying; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Transactional; import org.springframework.validation.annotation.Validated; @@ -68,11 +69,8 @@ import com.google.common.eventbus.EventBus; /** * Business facade for managing the {@link DistributionSet}s. * - * - * - * */ -@Transactional(readOnly = true) +@Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) @Validated @Service public class DistributionSetManagement { @@ -140,15 +138,15 @@ public class DistributionSetManagement { * @param sets * to toggle for * @param tag - * to toogle - * @return {@link DistributionSetTagAssigmentResult} with all metadata of + * to toggle + * @return {@link DistributionSetTagAssignmentResult} with all meta data of * the assignment outcome. */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @NotNull @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) - public DistributionSetTagAssigmentResult toggleTagAssignment(@NotEmpty final List sets, + public DistributionSetTagAssignmentResult toggleTagAssignment(@NotEmpty final List sets, @NotNull final DistributionSetTag tag) { return toggleTagAssignment(sets.stream().map(ds -> ds.getId()).collect(Collectors.toList()), tag.getName()); } @@ -163,44 +161,44 @@ public class DistributionSetManagement { * to toggle for * @param tagName * to toggle - * @return {@link DistributionSetTagAssigmentResult} with all metadata of + * @return {@link DistributionSetTagAssignmentResult} with all meta data of * the assignment outcome. */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @NotNull @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) - public DistributionSetTagAssigmentResult toggleTagAssignment(@NotEmpty final Collection dsIds, + public DistributionSetTagAssignmentResult toggleTagAssignment(@NotEmpty final Collection dsIds, @NotNull final String tagName) { final Iterable sets = findDistributionSetListWithDetails(dsIds); final DistributionSetTag myTag = tagManagement.findDistributionSetTag(tagName); - DistributionSetTagAssigmentResult result = null; - final List allDSs = new ArrayList<>(); + DistributionSetTagAssignmentResult result; + final List toBeChangedDSs = new ArrayList<>(); for (final DistributionSet set : sets) { if (set.getTags().add(myTag)) { - allDSs.add(set); + toBeChangedDSs.add(set); } } - // unassigment case - if (allDSs.isEmpty()) { + // un-assignment case + if (toBeChangedDSs.isEmpty()) { for (final DistributionSet set : sets) { if (set.getTags().remove(myTag)) { - allDSs.add(set); + toBeChangedDSs.add(set); } } - result = new DistributionSetTagAssigmentResult(dsIds.size() - allDSs.size(), 0, allDSs.size(), - Collections.emptyList(), distributionSetRepository.save(allDSs), myTag); + result = new DistributionSetTagAssignmentResult(dsIds.size() - toBeChangedDSs.size(), 0, + toBeChangedDSs.size(), Collections.emptyList(), distributionSetRepository.save(toBeChangedDSs), + myTag); } else { - result = new DistributionSetTagAssigmentResult(dsIds.size() - allDSs.size(), allDSs.size(), 0, - distributionSetRepository.save(allDSs), Collections.emptyList(), myTag); + result = new DistributionSetTagAssignmentResult(dsIds.size() - toBeChangedDSs.size(), toBeChangedDSs.size(), + 0, distributionSetRepository.save(toBeChangedDSs), Collections.emptyList(), myTag); } - final DistributionSetTagAssigmentResult resultAssignment = result; - afterCommit - .afterCommit(() -> eventBus.post(new DistributionSetTagAssigmentResultEvent(resultAssignment))); + final DistributionSetTagAssignmentResult resultAssignment = result; + afterCommit.afterCommit(() -> eventBus.post(new DistributionSetTagAssigmentResultEvent(resultAssignment))); // no reason to persist the tag entityManager.detach(myTag); @@ -232,7 +230,7 @@ public class DistributionSetManagement { * @throw DataDependencyViolationException in case of illegal update */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) public DistributionSet updateDistributionSet(@NotNull final DistributionSet ds) { checkNotNull(ds.getId()); @@ -257,7 +255,7 @@ public class DistributionSetManagement { * to delete */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_REPOSITORY) public void deleteDistributionSet(@NotNull final DistributionSet set) { deleteDistributionSet(set.getId()); @@ -272,7 +270,7 @@ public class DistributionSetManagement { * to be deleted */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_REPOSITORY) public void deleteDistributionSet(@NotEmpty final Long... distributionSetIDs) { final List toHardDelete = new ArrayList<>(); @@ -313,7 +311,7 @@ public class DistributionSetManagement { * {@link SoftwareModule}s. */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY) public DistributionSet createDistributionSet(@NotNull final DistributionSet dSet) { prepareDsSave(dSet); @@ -347,11 +345,14 @@ public class DistributionSetManagement { * {@link SoftwareModule}s. */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY) public List createDistributionSets(@NotNull final Iterable distributionSets) { for (final DistributionSet ds : distributionSets) { prepareDsSave(ds); + if (ds.getType() == null) { + ds.setType(systemManagement.getTenantMetadata().getDefaultDsType()); + } } return distributionSetRepository.save(distributionSets); } @@ -366,7 +367,7 @@ public class DistributionSetManagement { * @return the updated {@link DistributionSet}. */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) public DistributionSet assignSoftwareModules(@NotNull final DistributionSet ds, final Set softwareModules) { @@ -388,7 +389,7 @@ public class DistributionSetManagement { * @return the updated {@link DistributionSet}. */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) public DistributionSet unassignSoftwareModule(@NotNull final DistributionSet ds, final SoftwareModule softwareModule) { @@ -413,7 +414,7 @@ public class DistributionSetManagement { * s while the DS type is already in use. */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) public DistributionSetType updateDistributionSetType(@NotNull final DistributionSetType dsType) { checkNotNull(dsType.getId()); @@ -437,7 +438,7 @@ public class DistributionSetManagement { * @param spec * of the search * @param pageable - * parametsr for paging + * parameter for paging * * @return the found {@link SoftwareModuleType}s */ @@ -715,7 +716,7 @@ public class DistributionSetManagement { * @return created {@link Entity} */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY) public DistributionSetType createDistributionSetType(@NotNull final DistributionSetType type) { if (type.getId() != null) { @@ -732,7 +733,7 @@ public class DistributionSetManagement { * to delete */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_REPOSITORY) public void deleteDistributionSetType(@NotNull final DistributionSetType type) { @@ -755,14 +756,14 @@ public class DistributionSetManagement { * in case the meta data entry already exists for the specific * key */ - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @Modifying @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) public DistributionSetMetadata createDistributionSetMetadata(@NotNull final DistributionSetMetadata metadata) { if (distributionSetMetadataRepository.exists(metadata.getId())) { throwMetadataKeyAlreadyExists(metadata.getId().getKey()); } - // merge base software module so optLockRevision gets updated and audit + // merge base distribution set so optLockRevision gets updated and audit // log written because // modifying metadata is modifying the base distribution set itself for // auditing purposes. @@ -780,7 +781,7 @@ public class DistributionSetManagement { * in case one of the meta data entry already exists for the * specific key */ - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @Modifying @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) public List createDistributionSetMetadata( @@ -802,7 +803,7 @@ public class DistributionSetManagement { * in case the meta data entry does not exists and cannot be * updated */ - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @Modifying @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) public DistributionSetMetadata updateDistributionSetMetadata(@NotNull final DistributionSetMetadata metadata) { @@ -820,7 +821,7 @@ public class DistributionSetManagement { * @param id * the ID of the distribution set meta data to delete */ - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @Modifying @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) public void deleteDistributionSetMetadata(@NotNull final DsMetadataCompositeKey id) { @@ -870,7 +871,7 @@ public class DistributionSetManagement { cb) -> cb.and( cb.equal(root.get(DistributionSetMetadata_.distributionSet) .get(DistributionSet_.id), distributionSetId), - spec.toPredicate(root, query, cb)), + spec.toPredicate(root, query, cb)), pageable); } @@ -913,10 +914,10 @@ public class DistributionSetManagement { * @return created {@link Entity} */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY) public List createDistributionSetTypes(@NotNull final Collection types) { - return types.stream().map(type -> createDistributionSetType(type)).collect(Collectors.toList()); + return types.stream().map(this::createDistributionSetType).collect(Collectors.toList()); } /** @@ -926,7 +927,7 @@ public class DistributionSetManagement { * @param softwareModules */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) public void checkDistributionSetAlreadyUse(final DistributionSet distributionSet) { checkDistributionSetSoftwareModulesIsAllowedToModify(distributionSet); @@ -992,14 +993,14 @@ public class DistributionSetManagement { } } - private Boolean isDSWithNoTagSelected(final DistributionSetFilter distributionSetFilter) { + private static Boolean isDSWithNoTagSelected(final DistributionSetFilter distributionSetFilter) { if (distributionSetFilter.getSelectDSWithNoTag() != null && distributionSetFilter.getSelectDSWithNoTag()) { return true; } return false; } - private Boolean isTagsSelected(final DistributionSetFilter distributionSetFilter) { + private static Boolean isTagsSelected(final DistributionSetFilter distributionSetFilter) { if (distributionSetFilter.getTagNames() != null && !distributionSetFilter.getTagNames().isEmpty()) { return true; } @@ -1033,7 +1034,7 @@ public class DistributionSetManagement { } } - private void throwMetadataKeyAlreadyExists(final String metadataKey) { + private static void throwMetadataKeyAlreadyExists(final String metadataKey) { throw new EntityAlreadyExistsException("Metadata entry with key '" + metadataKey + "' already exists"); } @@ -1048,7 +1049,7 @@ public class DistributionSetManagement { * @return list of assigned ds */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @NotNull @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_TARGET) public List assignTag(@NotEmpty final Collection dsIds, @@ -1060,7 +1061,7 @@ public class DistributionSetManagement { afterCommit.afterCommit(() -> { - final DistributionSetTagAssigmentResult result = new DistributionSetTagAssigmentResult(0, save.size(), 0, + final DistributionSetTagAssignmentResult result = new DistributionSetTagAssignmentResult(0, save.size(), 0, save, Collections.emptyList(), tag); eventBus.post(new DistributionSetTagAssigmentResultEvent(result)); }); @@ -1077,7 +1078,7 @@ public class DistributionSetManagement { * @return list of unassigned ds */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @NotNull @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_TARGET) public List unAssignAllDistributionSetsByTag(@NotNull final DistributionSetTag tag) { @@ -1095,7 +1096,7 @@ public class DistributionSetManagement { * @return the unassigned ds or if no ds is unassigned */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_TARGET) public DistributionSet unAssignTag(@NotNull final Long dsId, @NotNull final DistributionSetTag distributionSetTag) { final List allDs = findDistributionSetListWithDetails(Arrays.asList(dsId)); diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DistributionSetMetadataRepository.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DistributionSetMetadataRepository.java index 1ff6c1ca5..c042a32d0 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DistributionSetMetadataRepository.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DistributionSetMetadataRepository.java @@ -12,6 +12,7 @@ import org.eclipse.hawkbit.repository.model.DistributionSetMetadata; import org.eclipse.hawkbit.repository.model.DsMetadataCompositeKey; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.repository.PagingAndSortingRepository; +import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Transactional; /** @@ -20,7 +21,7 @@ import org.springframework.transaction.annotation.Transactional; * * */ -@Transactional(readOnly = true) +@Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) public interface DistributionSetMetadataRepository extends PagingAndSortingRepository, JpaSpecificationExecutor { diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DistributionSetRepository.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DistributionSetRepository.java index 1a59fdca7..f2138bb2d 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DistributionSetRepository.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DistributionSetRepository.java @@ -21,6 +21,7 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; +import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Transactional; /** @@ -29,7 +30,7 @@ import org.springframework.transaction.annotation.Transactional; * * */ -@Transactional(readOnly = true) +@Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) public interface DistributionSetRepository extends BaseEntityRepository, JpaSpecificationExecutor { @@ -50,7 +51,7 @@ public interface DistributionSetRepository * to be deleted */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @Query("update DistributionSet d set d.deleted = 1 where d.id in :ids") void deleteDistributionSet(@Param("ids") Long... ids); @@ -62,7 +63,7 @@ public interface DistributionSetRepository * @return number of affected/deleted records */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) // Workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=349477 @Query("DELETE FROM DistributionSet d WHERE d.id IN ?1") int deleteByIdIn(Collection ids); @@ -82,7 +83,7 @@ public interface DistributionSetRepository * yet to an {@link UpdateAction}, i.e. unused. * * @param ids - * to searcgh for + * to search for * @return */ @Query("select ac.distributionSet.id from Action ac where ac.distributionSet.id in :ids") diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DistributionSetTagRepository.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DistributionSetTagRepository.java index c00713fc4..8521a96b9 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DistributionSetTagRepository.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DistributionSetTagRepository.java @@ -15,15 +15,14 @@ import org.eclipse.hawkbit.repository.model.DistributionSetTag; import org.eclipse.hawkbit.repository.model.TargetTag; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Modifying; +import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Transactional; /** * {@link TargetTag} repository. * - * - * */ -@Transactional(readOnly = true) +@Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) public interface DistributionSetTagRepository extends BaseEntityRepository, JpaSpecificationExecutor { /** @@ -34,7 +33,7 @@ public interface DistributionSetTagRepository * @return 1 if tag was deleted */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) Long deleteByName(final String tagName); /** diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DistributionSetTypeRepository.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DistributionSetTypeRepository.java index b9da6b3cc..289dd6c09 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DistributionSetTypeRepository.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/DistributionSetTypeRepository.java @@ -14,16 +14,14 @@ import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.repository.PagingAndSortingRepository; +import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Transactional; /** * {@link PagingAndSortingRepository} for {@link DistributionSetType}. * - * - * - * */ -@Transactional(readOnly = true) +@Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) public interface DistributionSetTypeRepository extends BaseEntityRepository, JpaSpecificationExecutor { diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/EclipseLinkTargetInfoRepository.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/EclipseLinkTargetInfoRepository.java index c9be0bf38..e37a51d6c 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/EclipseLinkTargetInfoRepository.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/EclipseLinkTargetInfoRepository.java @@ -13,7 +13,6 @@ import java.util.List; import javax.persistence.EntityManager; import javax.persistence.Query; -import javax.transaction.Transactional; import org.eclipse.hawkbit.repository.model.TargetInfo; import org.eclipse.hawkbit.repository.model.TargetUpdateStatus; @@ -21,16 +20,16 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheEvict; import org.springframework.data.jpa.repository.Modifying; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Transactional; /** * Custom repository implementation as standard spring repository fails as of * https://bugs.eclipse.org/bugs/show_bug.cgi?id=415027 . * - * - * */ @Service -@Transactional +@Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) public class EclipseLinkTargetInfoRepository implements TargetInfoRepository { @Autowired @@ -38,6 +37,7 @@ public class EclipseLinkTargetInfoRepository implements TargetInfoRepository { @Override @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) public void setTargetUpdateStatus(final TargetUpdateStatus status, final List targets) { final Query query = entityManager.createQuery( "update TargetInfo ti set ti.updateStatus = :status where ti.targetId in :targets and ti.updateStatus != :status"); @@ -48,6 +48,7 @@ public class EclipseLinkTargetInfoRepository implements TargetInfoRepository { @Override @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @CacheEvict(value = { "targetStatus", "distributionUsageInstalled", "targetsLastPoll" }, allEntries = true) public S save(final S entity) { @@ -61,6 +62,7 @@ public class EclipseLinkTargetInfoRepository implements TargetInfoRepository { @Override @Modifying + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @CacheEvict(value = { "targetStatus", "distributionUsageInstalled", "targetsLastPoll" }, allEntries = true) public void deleteByTargetIdIn(final Collection targetIDs) { final javax.persistence.Query query = entityManager diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ExternalArtifactProviderRepository.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ExternalArtifactProviderRepository.java index 05634ef63..d0802d242 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ExternalArtifactProviderRepository.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ExternalArtifactProviderRepository.java @@ -9,16 +9,14 @@ package org.eclipse.hawkbit.repository; import org.eclipse.hawkbit.repository.model.ExternalArtifactProvider; +import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Transactional; /** * Repository for {@link ExternalArtifactProvider}. * - * - * - * */ -@Transactional(readOnly = true) +@Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) public interface ExternalArtifactProviderRepository extends BaseEntityRepository { } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ExternalArtifactRepository.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ExternalArtifactRepository.java index c7ece2445..d20da8013 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ExternalArtifactRepository.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ExternalArtifactRepository.java @@ -11,15 +11,14 @@ package org.eclipse.hawkbit.repository; import org.eclipse.hawkbit.repository.model.ExternalArtifact; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; +import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Transactional; /** * {@link ExternalArtifact} repository. * - * - * */ -@Transactional(readOnly = true) +@Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) public interface ExternalArtifactRepository extends BaseEntityRepository { /** diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/LocalArtifactRepository.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/LocalArtifactRepository.java index 5bbac1dd1..4c106957d 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/LocalArtifactRepository.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/LocalArtifactRepository.java @@ -15,13 +15,14 @@ import org.eclipse.hawkbit.repository.model.LocalArtifact; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.Query; +import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Transactional; /** * {@link LocalArtifact} repository. * */ -@Transactional(readOnly = true) +@Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) public interface LocalArtifactRepository extends BaseEntityRepository { /** diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/NoCountPagingRepository.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/NoCountPagingRepository.java index 79f54a3f0..0624f269a 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/NoCountPagingRepository.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/NoCountPagingRepository.java @@ -29,9 +29,6 @@ import org.springframework.stereotype.Repository; * Workaround as spring data does not provide a {@link Slice} based * {@link JpaRepository#findAll()}. * - * - * - * */ @Repository public class NoCountPagingRepository { @@ -104,15 +101,6 @@ public class NoCountPagingRepository { super(domainClass, em); } - /* - * (non-Javadoc) - * - * @see - * org.springframework.data.jpa.repository.support.SimpleJpaRepository# - * readPage(javax.persistence .TypedQuery, - * org.springframework.data.domain.Pageable, - * org.springframework.data.jpa.domain.Specification) - */ @Override protected Page readPage(final TypedQuery query, final Pageable pageable, final Specification spec) { query.setFirstResult(pageable.getOffset()); diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ReportManagement.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ReportManagement.java index eab926b4b..326442283 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ReportManagement.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/ReportManagement.java @@ -48,14 +48,15 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Transactional; import org.springframework.validation.annotation.Validated; /** - * Service layer for generating SP reportings. + * Service layer for generating hawkBit reports. * */ -@Transactional(readOnly = true) +@Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) @Validated @Service public class ReportManagement { @@ -404,7 +405,7 @@ public class ReportManagement { return innerOuterReport; } - private final class InnerOuter { + private static final class InnerOuter { final DSName name; long count; final List outer; @@ -433,9 +434,6 @@ public class ReportManagement { /** * Object contains the name and the id of an entity. * - * - * - * */ private static final class DSName { @@ -458,11 +456,6 @@ public class ReportManagement { return name; } - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ @Override public int hashCode() { final int prime = 31; @@ -471,11 +464,6 @@ public class ReportManagement { return result; } - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ @Override public boolean equals(final Object obj) { // NOSONAR - as this is // generated @@ -499,11 +487,6 @@ public class ReportManagement { return true; } - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ @Override public String toString() { return "DSName [name=" + name + "]"; @@ -523,14 +506,8 @@ public class ReportManagement { /** * Return DateTypes. - * - * - * */ public static final class DateTypes implements Serializable { - /** - * - */ private static final long serialVersionUID = 1L; private static final PerMonth PER_MONTH = new PerMonth(); @@ -585,12 +562,6 @@ public class ReportManagement { private static final long serialVersionUID = 1L; private static final String DATE_PATTERN = "yyyy-MM"; - /* - * (non-Javadoc) - * - * @see org.eclipse.hawkbit.server.repository.ReportManagement.DateType# - * format(java. lang.String) - */ @Override public LocalDate format(final String s) { final DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DATE_PATTERN); @@ -598,23 +569,11 @@ public class ReportManagement { return ym.atDay(1); } - /* - * (non-Javadoc) - * - * @see org.eclipse.hawkbit.server.repository.ReportManagement.DateType# - * h2Format() - */ @Override public String h2Format() { return DATE_PATTERN; } - /* - * (non-Javadoc) - * - * @see org.eclipse.hawkbit.server.repository.ReportManagement.DateType# - * mySqlFormat( ) - */ @Override public String mySqlFormat() { return "%Y-%m"; diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/RolloutGroupManagement.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/RolloutGroupManagement.java index 54ff37e87..d204154d0 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/RolloutGroupManagement.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/RolloutGroupManagement.java @@ -43,6 +43,7 @@ import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.domain.Specification; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Transactional; import org.springframework.validation.annotation.Validated; @@ -52,7 +53,7 @@ import org.springframework.validation.annotation.Validated; */ @Validated @Service -@Transactional(readOnly = true) +@Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) public class RolloutGroupManagement { @Autowired @@ -189,7 +190,7 @@ public class RolloutGroupManagement { final ListJoin rolloutTargetJoin = root.join(Target_.rolloutTargetGroup); return criteriaBuilder.and(specification.toPredicate(root, query, criteriaBuilder), criteriaBuilder.equal(rolloutTargetJoin.get(RolloutTargetGroup_.rolloutGroup), rolloutGroup)); - } , page); + }, page); } /** @@ -213,7 +214,7 @@ public class RolloutGroupManagement { return targetRepository.findByActionsRolloutGroup(rolloutGroup, page); } - private boolean isRolloutStatusReady(final RolloutGroup rolloutGroup) { + private static boolean isRolloutStatusReady(final RolloutGroup rolloutGroup) { return rolloutGroup != null && RolloutStatus.READY.equals(rolloutGroup.getRollout().getStatus()); } @@ -259,5 +260,4 @@ public class RolloutGroupManagement { .collect(Collectors.toList()); return new PageImpl<>(targetWithActionStatus, pageRequest, totalCount); } - -} \ No newline at end of file +} diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/RolloutGroupRepository.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/RolloutGroupRepository.java index cf3f3d729..e0cb4cc27 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/RolloutGroupRepository.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/RolloutGroupRepository.java @@ -18,12 +18,13 @@ import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; +import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Transactional; /** * The repository interface for the {@link RolloutGroup} model. */ -@Transactional(readOnly = true) +@Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) public interface RolloutGroupRepository extends BaseEntityRepository, JpaSpecificationExecutor { diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/RolloutManagement.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/RolloutManagement.java index 1573048ec..09decfc03 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/RolloutManagement.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/RolloutManagement.java @@ -58,6 +58,8 @@ import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Service; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.support.DefaultTransactionDefinition; import org.springframework.transaction.support.TransactionTemplate; @@ -72,7 +74,7 @@ import org.springframework.validation.annotation.Validated; @Validated @Service @EnableScheduling -@Transactional(readOnly = true) +@Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) public class RolloutManagement { private static final Logger LOGGER = LoggerFactory.getLogger(RolloutManagement.class); @@ -134,7 +136,7 @@ public class RolloutManagement { /** * Retrieves all rollouts. - * + * * @param page * the page request to sort and limit the result * @return a page of found rollouts @@ -146,7 +148,7 @@ public class RolloutManagement { /** * Retrieves all rollouts found by the given specification. - * + * * @param specification * the specification to filter rollouts * @param page @@ -163,7 +165,7 @@ public class RolloutManagement { /** * Retrieves a specific rollout by its ID. - * + * * @param rolloutId * the ID of the rollout to retrieve * @return the founded rollout or {@code null} if rollout with given ID does @@ -180,13 +182,13 @@ public class RolloutManagement { * which are effected by this rollout to create. The targets will then be * split up into groups. The size of the groups can be defined in the * {@code groupSize} parameter. - * + * * The rollout is not started. Only the preparation of the rollout is done, * persisting and creating all the necessary groups. The Rollout and the * groups are persisted in {@link RolloutStatus#READY} and * {@link RolloutGroupStatus#READY} so they can be started * {@link #startRollout(Rollout)}. - * + * * @param rollout * the rollout entity to create * @param amountGroup @@ -195,11 +197,11 @@ public class RolloutManagement { * the rolloutgroup conditions and actions which should be * applied for each {@link RolloutGroup} * @return the persisted rollout. - * + * * @throws IllegalArgumentException * in case the given groupSize is zero or lower. */ - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @Modifying @PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_WRITE) public Rollout createRollout(final Rollout rollout, final int amountGroup, @@ -215,22 +217,22 @@ public class RolloutManagement { * will be done synchronously and will be returned. The targets will then be * split up into groups. The size of the groups can be defined in the * {@code groupSize} parameter. - * + * * The creation of the rollout groups is executed asynchronously due it * might take some time to split up the targets into groups. The creation of * the {@link RolloutGroup} is published as event * {@link RolloutGroupCreatedEvent}. - * + * * The rollout is in status {@link RolloutStatus#CREATING} until all rollout * groups has been created and the targets are split up, then the rollout * will change the status to {@link RolloutStatus#READY}. - * + * * The rollout is not started. Only the preparation of the rollout is done, * persisting and creating all the necessary groups. The Rollout and the * groups are persisted in {@link RolloutStatus#READY} and * {@link RolloutGroupStatus#READY} so they can be started * {@link #startRollout(Rollout)}. - * + * * @param rollout * the rollout to be created * @param amountGroup @@ -242,7 +244,7 @@ public class RolloutManagement { * @return the created rollout entity in state * {@link RolloutStatus#CREATING} */ - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @Modifying @PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_WRITE) public Rollout createRolloutAsync(final Rollout rollout, final int amountGroup, @@ -259,13 +261,7 @@ public class RolloutManagement { entityManager.flush(); executor.execute(() -> { try { - final DefaultTransactionDefinition def = new DefaultTransactionDefinition(); - def.setName("creatingRollout"); - def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); - new TransactionTemplate(txManager, def).execute(status -> { - createRolloutGroups(amountGroup, conditions, savedRollout); - return null; - }); + createRolloutGroupsInNewTransaction(amountGroup, conditions, savedRollout); } finally { creatingRollouts.remove(savedRollout.getName()); } @@ -280,7 +276,7 @@ public class RolloutManagement { return rolloutRepository.save(rollout); } - private void verifyRolloutGroupParameter(final int amountGroup) { + private static void verifyRolloutGroupParameter(final int amountGroup) { if (amountGroup <= 0) { throw new IllegalArgumentException("the amountGroup must be greater than zero"); } else if (amountGroup > 500) { @@ -288,13 +284,22 @@ public class RolloutManagement { } } + private Rollout createRolloutGroupsInNewTransaction(final int amountOfGroups, + final RolloutGroupConditions conditions, final Rollout savedRollout) { + final DefaultTransactionDefinition def = new DefaultTransactionDefinition(); + def.setName("creatingRollout"); + def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + return new TransactionTemplate(txManager, def) + .execute(status -> createRolloutGroups(amountOfGroups, conditions, savedRollout)); + } + /** * Method for creating rollout groups and calculating group sizes. Group * sizes are calculated by dividing the total count of targets through the * amount of given groups. In same cases this will lead to less rollout * groups than given by client. - * - * @param amountGroup + * + * @param amountOfGroups * the amount of groups * @param conditions * the rollout group conditions @@ -302,17 +307,17 @@ public class RolloutManagement { * the rollout * @return the rollout with created groups */ - private Rollout createRolloutGroups(final int amountGroup, final RolloutGroupConditions conditions, + private Rollout createRolloutGroups(final int amountOfGroups, final RolloutGroupConditions conditions, final Rollout savedRollout) { int pageIndex = 0; int groupIndex = 0; final Long totalCount = savedRollout.getTotalTargets(); - final int groupSize = (int) Math.ceil((double) totalCount / (double) amountGroup); + final int groupSize = (int) Math.ceil((double) totalCount / (double) amountOfGroups); // validate if the amount of groups that will be created are the amount // of groups that the client what's to have created. - int amountGroupValidated = amountGroup; + int amountGroupValidated = amountOfGroups; final int amountGroupCreation = (int) (Math.ceil((double) totalCount / (double) groupSize)); - if (amountGroupCreation == (amountGroup - 1)) { + if (amountGroupCreation == (amountOfGroups - 1)) { amountGroupValidated--; } RolloutGroup lastSavedGroup = null; @@ -356,17 +361,19 @@ public class RolloutManagement { * for each affected target in the rollout. The actions of the first group * will be started immediately {@link RolloutGroupStatus#RUNNING} as the * other groups will be {@link RolloutGroupStatus#SCHEDULED} state. - * + * * The rollout itself will be then also in {@link RolloutStatus#RUNNING}. - * + * * @param rollout * the rollout to be started - * + * + * @return started rollout + * * @throws RolloutIllegalStateException * if given rollout is not in {@link RolloutStatus#READY}. Only * ready rollouts can be started. */ - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @Modifying @PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_WRITE + SpringEvalExpressions.HAS_AUTH_OR + SpringEvalExpressions.IS_SYSTEM_CODE) @@ -383,12 +390,14 @@ public class RolloutManagement { * actions of the first group will be started immediately * {@link RolloutGroupStatus#RUNNING} as the other groups will be * {@link RolloutGroupStatus#SCHEDULED} state. - * + * * The rollout itself will be then also in {@link RolloutStatus#RUNNING}. - * + * * @param rollout * the rollout to be started - * + * + * @return the started rollout + * * @throws RolloutIllegalStateException * if given rollout is not in {@link RolloutStatus#READY}. Only * ready rollouts can be started. @@ -456,19 +465,19 @@ public class RolloutManagement { * {@link RolloutGroupStatus#SCHEDULED} will not be started and keep in * {@link RolloutGroupStatus#SCHEDULED} state until the rollout is * {@link RolloutManagement#resumeRollout(Rollout)}. - * + * * Switching the rollout status to {@link RolloutStatus#PAUSED} is * sufficient due the {@link #checkRunningRollouts(long)} will not check * this rollout anymore. - * + * * @param rollout * the rollout to be paused. - * + * * @throws RolloutIllegalStateException * if given rollout is not in {@link RolloutStatus#RUNNING}. * Only running rollouts can be paused. */ - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @Modifying @PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_WRITE + SpringEvalExpressions.HAS_AUTH_OR + SpringEvalExpressions.IS_SYSTEM_CODE) @@ -491,14 +500,14 @@ public class RolloutManagement { * Resumes a paused rollout. The rollout switches back to * {@link RolloutStatus#RUNNING} state which is then picked up again by the * {@link #checkRunningRollouts(long)}. - * + * * @param rollout * the rollout to be resumed * @throws RolloutIllegalStateException * if given rollout is not in {@link RolloutStatus#PAUSED}. Only * paused rollouts can be resumed. */ - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @Modifying @PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_WRITE + SpringEvalExpressions.HAS_AUTH_OR + SpringEvalExpressions.IS_SYSTEM_CODE) @@ -516,7 +525,7 @@ public class RolloutManagement { * Checking running rollouts. Rollouts which are checked updating the * {@link Rollout#setLastCheck(long)} to indicate that the current instance * is handling the specific rollout. This code should run as system-code. - * + * *
      * {@code
      *  SystemSecurityContext.runAsSystem(new Callable() {
@@ -526,21 +535,21 @@ public class RolloutManagement {
      * });
      *  }
      * 
- * + * * This method is attend to be called by a scheduler. * {@link RolloutScheduler}. And must be running in an transaction so it's * splitted from the scheduler. - * + * * Rollouts which are currently running are investigated, by means the * error- and finish condition of running groups in this rollout are * evaluated. - * + * * @param delayBetweenChecks * the time in milliseconds of the delay between the further and * this check. This check is only applied if the last check is * less than (lastcheck-delay). */ - @Transactional + @Transactional(propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_UNCOMMITTED) @Modifying @PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_WRITE + SpringEvalExpressions.HAS_AUTH_OR + SpringEvalExpressions.IS_SYSTEM_CODE) @@ -723,7 +732,7 @@ public class RolloutManagement { /** * Count rollouts by specified filter text. - * + * * @param searchText * name or description * @return total count rollouts for specified filter text. @@ -745,7 +754,7 @@ public class RolloutManagement { /** * * Retrieves a specific rollout by its ID. - * + * * @param pageable * the page request to sort and limit the result * @param searchText @@ -763,7 +772,7 @@ public class RolloutManagement { /** * Retrieves a specific rollout by its name. - * + * * @param rolloutName * the name of the rollout to retrieve * @return the founded rollout or {@code null} if rollout with given name @@ -776,14 +785,14 @@ public class RolloutManagement { /** * Update rollout details. - * + * * @param rollout * rollout to be updated - * + * * @return Rollout updated rollout */ @NotNull - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @Modifying @PreAuthorize(SpringEvalExpressions.HAS_AUTH_ROLLOUT_MANAGEMENT_WRITE) public Rollout updateRollout(@NotNull final Rollout rollout) { @@ -793,7 +802,7 @@ public class RolloutManagement { /** * Get count of targets in different status in rollout. - * + * * @param page * the page request to sort and limit the result * @return a list of rollouts with details of targets count for different @@ -845,7 +854,7 @@ public class RolloutManagement { } } - private void checkIfRolloutCanStarted(final Rollout rollout, final Rollout mergedRollout) { + private static void checkIfRolloutCanStarted(final Rollout rollout, final Rollout mergedRollout) { if (!(RolloutStatus.READY.equals(mergedRollout.getStatus()))) { throw new RolloutIllegalStateException("Rollout can only be started in state ready but current state is " + rollout.getStatus().name().toLowerCase()); @@ -855,7 +864,7 @@ public class RolloutManagement { /*** * Get finished percentage details for a specified group which is in running * state. - * + * * @param rolloutId * the ID of the {@link Rollout} * @param rolloutGroup diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/RolloutRepository.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/RolloutRepository.java index 9c4318a3f..5a22f5ab5 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/RolloutRepository.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/RolloutRepository.java @@ -18,12 +18,13 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; +import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Transactional; /** * The repository interface for the {@link Rollout} model. */ -@Transactional(readOnly = true) +@Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) public interface RolloutRepository extends BaseEntityRepository, JpaSpecificationExecutor { /** @@ -40,7 +41,7 @@ public interface RolloutRepository extends BaseEntityRepository, * @return the count of the updated rows. Zero if no row has been updated */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @Query("UPDATE Rollout r SET r.lastCheck = :lastCheck WHERE r.lastCheck < (:lastCheck - :delay) AND r.status=:status") int updateLastCheck(@Param("lastCheck") final long lastCheck, @Param("delay") final long delay, @Param("status") final RolloutStatus status); diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/RolloutTargetGroupRepository.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/RolloutTargetGroupRepository.java index 6564e2c1f..14d9b8353 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/RolloutTargetGroupRepository.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/RolloutTargetGroupRepository.java @@ -12,11 +12,14 @@ import org.eclipse.hawkbit.repository.model.RolloutTargetGroup; import org.eclipse.hawkbit.repository.model.RolloutTargetGroupId; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.repository.CrudRepository; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Transactional; /** - * + * Spring data repository for {@link RolloutTargetGroup}. * */ +@Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) public interface RolloutTargetGroupRepository extends CrudRepository, JpaSpecificationExecutor { } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/SoftwareManagement.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/SoftwareManagement.java index 1f610d29c..d719667ed 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/SoftwareManagement.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/SoftwareManagement.java @@ -52,6 +52,7 @@ import org.springframework.data.jpa.domain.Specification; import org.springframework.data.jpa.repository.Modifying; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Transactional; import org.springframework.validation.annotation.Validated; @@ -59,14 +60,10 @@ import com.google.common.base.Strings; import com.google.common.collect.Sets; /** - * Business facade for managing the deployable {@link SoftwareModule}s. - * - * - * - * + * Business facade for managing {@link SoftwareModule}s. * */ -@Transactional(readOnly = true) +@Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) @Validated @Service public class SoftwareManagement { @@ -99,7 +96,7 @@ public class SoftwareManagement { private ArtifactManagement artifactManagement; /** - * Updates existing {@link SoftwareModule}. Updateable values are + * Updates existing {@link SoftwareModule}. Update-able values are * {@link SoftwareModule#getDescription()} * {@link SoftwareModule#getVendor()}. * @@ -112,24 +109,28 @@ public class SoftwareManagement { * of {@link SoftwareModule#getId()} is null */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) public SoftwareModule updateSoftwareModule(@NotNull final SoftwareModule sm) { checkNotNull(sm.getId()); final SoftwareModule module = softwareModuleRepository.findOne(sm.getId()); + boolean updated = false; if (null == sm.getDescription() || !sm.getDescription().equals(module.getDescription())) { module.setDescription(sm.getDescription()); + updated = true; } if (null == sm.getVendor() || !sm.getVendor().equals(module.getVendor())) { module.setVendor(sm.getVendor()); + updated = true; } - return softwareModuleRepository.save(module); + + return updated ? softwareModuleRepository.save(module) : module; } /** - * Updates existing {@link SoftwareModuleType}. Updatable value is + * Updates existing {@link SoftwareModuleType}. Update-able value is * {@link SoftwareModuleType#getDescription()} and * {@link SoftwareModuleType#getColour()}. * @@ -138,20 +139,23 @@ public class SoftwareManagement { * @return updated {@link Entity} */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) public SoftwareModuleType updateSoftwareModuleType(@NotNull final SoftwareModuleType sm) { checkNotNull(sm.getId()); final SoftwareModuleType type = softwareModuleTypeRepository.findOne(sm.getId()); + boolean updated = false; if (sm.getDescription() != null && !sm.getDescription().equals(type.getDescription())) { type.setDescription(sm.getDescription()); + updated = true; } if (sm.getColour() != null && !sm.getColour().equals(type.getColour())) { type.setColour(sm.getColour()); + updated = true; } - return softwareModuleTypeRepository.save(type); + return updated ? softwareModuleTypeRepository.save(type) : type; } /** @@ -256,19 +260,21 @@ public class SoftwareManagement { } /** - * retrieves {@link SoftwareModule}s by their name AND version. + * retrieves {@link SoftwareModule} by their name AND version AND type.. * * @param name * of the {@link SoftwareModule} * @param version * of the {@link SoftwareModule} - * @return the found {@link SoftwareModule}s + * @param type + * of the {@link SoftwareModule} + * @return the found {@link SoftwareModule} or null */ @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) - public List findSoftwareModuleByNameAndVersion(@NotEmpty final String name, - @NotEmpty final String version) { + public SoftwareModule findSoftwareModuleByNameAndVersion(@NotEmpty final String name, + @NotEmpty final String version, @NotNull final SoftwareModuleType type) { - return softwareModuleRepository.findByNameAndVersion(name, version); + return softwareModuleRepository.findOneByNameAndVersionAndType(name, version, type); } /** @@ -278,7 +284,7 @@ public class SoftwareManagement { * is the {@link SoftwareModule} to be deleted */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_REPOSITORY) public void deleteSoftwareModule(@NotNull final SoftwareModule bsm) { @@ -309,10 +315,10 @@ public class SoftwareManagement { * Deletes {@link SoftwareModule}s which is any if the given ids. * * @param ids - * of the Software Moduels to be deleted + * of the Software Modules to be deleted */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_REPOSITORY) public void deleteSoftwareModules(@NotNull final Iterable ids) { final List swModulesToDelete = softwareModuleRepository.findByIdIn(ids); @@ -491,21 +497,27 @@ public class SoftwareManagement { /** * Filter {@link SoftwareModule}s with given * {@link SoftwareModule#getName()} or {@link SoftwareModule#getVersion()} - * and {@link SoftwareModule#getType()} that are not marked as deleted. + * search text and {@link SoftwareModule#getType()} that are not marked as + * deleted and sort them by means of given distribution set related modules + * on top of the list. + * + * After that the modules are sorted by {@link SoftwareModule#getName()} and + * {@link SoftwareModule#getVersion()} in ascending order. * * @param pageable * page parameter * @param orderByDistributionId - * the ID of distribution set to be order by + * the ID of distribution set to be ordered on top * @param searchText - * to be filtered as "like" on {@link SoftwareModule#getName()} + * filtered as "like" on {@link SoftwareModule#getName()} * @param type - * to be filtered as "like" on {@link SoftwareModule#getType()} + * filtered as "equal" on {@link SoftwareModule#getType()} * @return the page of found {@link SoftwareModule} */ @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) - public Slice findSoftwareModuleOrderByDistribution(@NotNull final Pageable pageable, - @NotNull final Long orderByDistributionId, final String searchText, final SoftwareModuleType type) { + public Slice findSoftwareModuleOrderBySetAssignmentAndModuleNameAscModuleVersionAsc( + @NotNull final Pageable pageable, @NotNull final Long orderByDistributionId, final String searchText, + final SoftwareModuleType type) { final List resultList = new ArrayList<>(); final int pageSize = pageable.getPageSize(); @@ -522,7 +534,7 @@ public class SoftwareManagement { assignedRoot, assignedQuery, cb, cb.equal(assignedDsJoin.get(DistributionSet_.id), orderByDistributionId)); // if we have some predicates then add it to the where clause of the - // multiselect + // multi select assignedQuery.where(specPredicate); assignedQuery.orderBy(cb.asc(assignedRoot.get(SoftwareModule_.name)), cb.asc(assignedRoot.get(SoftwareModule_.version))); @@ -546,7 +558,7 @@ public class SoftwareManagement { unassignedQuery.distinct(true); final Root unassignedRoot = unassignedQuery.from(SoftwareModule.class); - Predicate[] unassignedSpec = null; + Predicate[] unassignedSpec; if (!assignedSoftwareModules.isEmpty()) { unassignedSpec = specificationsToPredicate(buildSpecificationList(searchText, type), unassignedRoot, unassignedQuery, cb, cb.not(unassignedRoot.get(SoftwareModule_.id) @@ -568,7 +580,7 @@ public class SoftwareManagement { return new SliceImpl<>(resultList); } - private List> buildSpecificationList(final String searchText, + private static List> buildSpecificationList(final String searchText, final SoftwareModuleType type) { final List> specList = new ArrayList<>(); if (!Strings.isNullOrEmpty(searchText)) { @@ -689,7 +701,7 @@ public class SoftwareManagement { * @return created {@link Entity} */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY) public SoftwareModuleType createSoftwareModuleType(@NotNull final SoftwareModuleType type) { if (type.getId() != null) { @@ -707,10 +719,10 @@ public class SoftwareManagement { * @return created {@link Entity} */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY) - public List createSoftwareModuleTypes(@NotNull final Collection types) { - return types.stream().map(type -> createSoftwareModuleType(type)).collect(Collectors.toList()); + public List createSoftwareModuleType(@NotNull final Collection types) { + return types.stream().map(this::createSoftwareModuleType).collect(Collectors.toList()); } /** @@ -720,7 +732,7 @@ public class SoftwareManagement { * to delete */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_REPOSITORY) public void deleteSoftwareModuleType(@NotNull final SoftwareModuleType type) { @@ -774,7 +786,7 @@ public class SoftwareManagement { * in case the meta data entry already exists for the specific * key */ - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @Modifying @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) public SoftwareModuleMetadata createSoftwareModuleMetadata(@NotNull final SoftwareModuleMetadata metadata) { @@ -799,7 +811,7 @@ public class SoftwareManagement { * in case one of the meta data entry already exists for the * specific key */ - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @Modifying @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) public List createSoftwareModuleMetadata( @@ -821,12 +833,12 @@ public class SoftwareManagement { * in case the meta data entry does not exists and cannot be * updated */ - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @Modifying @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) public SoftwareModuleMetadata updateSoftwareModuleMetadata(@NotNull final SoftwareModuleMetadata metadata) { // check if exists otherwise throw entity not found exception - findOne(metadata.getId()); + findSoftwareModuleMetadata(metadata.getId()); // touch it to update the lock revision because we are modifying the // software module // indirectly @@ -840,7 +852,7 @@ public class SoftwareManagement { * @param id * the ID of the software module meta data to delete */ - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @Modifying @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) public void deleteSoftwareModuleMetadata(@NotNull final SwMetadataCompositeKey id) { @@ -884,7 +896,7 @@ public class SoftwareManagement { cb) -> cb.and( cb.equal(root.get(SoftwareModuleMetadata_.softwareModule) .get(SoftwareModule_.id), softwareModuleId), - spec.toPredicate(root, query, cb)), + spec.toPredicate(root, query, cb)), pageable); } @@ -899,7 +911,7 @@ public class SoftwareManagement { * in case the meta data does not exists for the given key */ @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_REPOSITORY) - public SoftwareModuleMetadata findOne(@NotNull final SwMetadataCompositeKey id) { + public SoftwareModuleMetadata findSoftwareModuleMetadata(@NotNull final SwMetadataCompositeKey id) { final SoftwareModuleMetadata findOne = softwareModuleMetadataRepository.findOne(id); if (findOne == null) { throw new EntityNotFoundException("Metadata with key '" + id.getKey() + "' does not exist"); @@ -914,7 +926,7 @@ public class SoftwareManagement { } } - private void throwMetadataKeyAlreadyExists(final String metadataKey) { + private static void throwMetadataKeyAlreadyExists(final String metadataKey) { throw new EntityAlreadyExistsException("Metadata entry with key '" + metadataKey + "' already exists"); } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/SoftwareModuleMetadataRepository.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/SoftwareModuleMetadataRepository.java index 0d80e1932..c40a96e92 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/SoftwareModuleMetadataRepository.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/SoftwareModuleMetadataRepository.java @@ -16,15 +16,14 @@ import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.repository.PagingAndSortingRepository; +import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Transactional; /** * {@link SoftwareModuleMetadata} repository. * - * - * */ -@Transactional(readOnly = true) +@Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) public interface SoftwareModuleMetadataRepository extends PagingAndSortingRepository, JpaSpecificationExecutor { diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/SoftwareModuleRepository.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/SoftwareModuleRepository.java index ccadb028a..95b01c270 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/SoftwareModuleRepository.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/SoftwareModuleRepository.java @@ -21,15 +21,14 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; +import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Transactional; /** * {@link SoftwareModule} repository. * - * - * */ -@Transactional(readOnly = true) +@Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) public interface SoftwareModuleRepository extends BaseEntityRepository, JpaSpecificationExecutor { @@ -43,15 +42,19 @@ public interface SoftwareModuleRepository Long countByType(SoftwareModuleType type); /** - * Retrieves {@link SoftwareModule}s by filtering on name AND version. + * Retrieves {@link SoftwareModule} by filtering on name AND version AND + * type (which is unique per tenant. * * @param name * to be filtered on * @param version * to be filtered on - * @return the found {@link SoftwareModule}s with the given name AND verion + * @param type + * to be filtered on + * @return the found {@link SoftwareModule} with the given name AND version + * AND type */ - List findByNameAndVersion(String name, String version); + SoftwareModule findOneByNameAndVersionAndType(String name, String version, SoftwareModuleType type); /** * deletes the {@link SoftwareModule}s with the given IDs. @@ -65,7 +68,7 @@ public interface SoftwareModuleRepository * */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @Query("UPDATE SoftwareModule b SET b.deleted = 1, b.lastModifiedAt = :lastModifiedAt, b.lastModifiedBy = :lastModifiedBy WHERE b.id IN :ids") void deleteSoftwareModule(@Param("lastModifiedAt") Long modifiedAt, @Param("lastModifiedBy") String modifiedBy, @Param("ids") final Long... ids); @@ -81,6 +84,8 @@ public interface SoftwareModuleRepository Page findByAssignedTo(Pageable pageable, DistributionSet set); /** + * + * * @param set * to search for * @return all {@link SoftwareModule}s that are assigned to given diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/SoftwareModuleTypeRepository.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/SoftwareModuleTypeRepository.java index 44b85b06b..ac9425a08 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/SoftwareModuleTypeRepository.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/SoftwareModuleTypeRepository.java @@ -12,16 +12,14 @@ import org.eclipse.hawkbit.repository.model.SoftwareModuleType; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; +import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Transactional; /** * Repository for {@link SoftwareModuleType}. * - * - * - * */ -@Transactional(readOnly = true) +@Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) public interface SoftwareModuleTypeRepository extends BaseEntityRepository, JpaSpecificationExecutor { diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/SystemManagement.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/SystemManagement.java index 77b48a3cd..49c9183a7 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/SystemManagement.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/SystemManagement.java @@ -35,6 +35,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.data.jpa.repository.Modifying; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import org.springframework.validation.annotation.Validated; @@ -43,7 +44,7 @@ import org.springframework.validation.annotation.Validated; * Central system management operations of the SP server. * */ -@Transactional(readOnly = true) +@Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) @Validated @Service public class SystemManagement { @@ -164,6 +165,7 @@ public class SystemManagement { * @return the {@link CurrentTenantKeyGenerator} */ @Bean + @Transactional(propagation = Propagation.SUPPORTS) public CurrentTenantKeyGenerator currentTenantKeyGenerator() { return new CurrentTenantKeyGenerator(); } @@ -179,7 +181,7 @@ public class SystemManagement { * @return */ @Cacheable(value = "tenantMetadata", key = "#tenant.toUpperCase()") - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @Modifying @NotNull public TenantMetaData getTenantMetadata(@NotNull final String tenant) { @@ -206,7 +208,6 @@ public class SystemManagement { @NotNull @PreAuthorize(SpringEvalExpressions.HAS_AUTH_SYSTEM_ADMIN + SpringEvalExpressions.HAS_AUTH_OR + SpringEvalExpressions.IS_SYSTEM_CODE) - // tenant independent public List findTenants() { return tenantMetaDataRepository.findAll().stream().map(md -> md.getTenant()).collect(Collectors.toList()); } @@ -218,10 +219,9 @@ public class SystemManagement { * to delete */ @CacheEvict(value = { "tenantMetadata" }, key = "#tenant.toUpperCase()") - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @Modifying @PreAuthorize(SpringEvalExpressions.HAS_AUTH_SYSTEM_ADMIN) - // tenant independent public void deleteTenant(@NotNull final String tenant) { cacheManager.evictCaches(tenant); cacheManager.getCache("currentTenant").evict(currentTenantKeyGenerator().generate(null, null)); @@ -250,7 +250,7 @@ public class SystemManagement { * @return {@link TenantMetaData} of {@link TenantAware#getCurrentTenant()} */ @Cacheable(value = "tenantMetadata", keyGenerator = "tenantKeyGenerator") - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @Modifying @NotNull public TenantMetaData getTenantMetadata() { @@ -279,7 +279,7 @@ public class SystemManagement { // suspend the transaction here to do a read-request against the medata // table, when the current // tenant is not cached anyway already. - @Transactional(propagation = Propagation.NOT_SUPPORTED) + @Transactional(propagation = Propagation.NOT_SUPPORTED, isolation = Isolation.READ_UNCOMMITTED) public String currentTenant() { final String initialTenantCreation = createInitialTenant.get(); if (initialTenantCreation == null) { @@ -298,7 +298,7 @@ public class SystemManagement { * @return updated {@link TenantMetaData} entity */ @CachePut(value = "tenantMetadata", key = "#metaData.tenant.toUpperCase()") - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @Modifying @NotNull public TenantMetaData updateTenantMetadata(@NotNull final TenantMetaData metaData) { @@ -310,8 +310,6 @@ public class SystemManagement { } private DistributionSetType createStandardSoftwareDataSetup() { - - // Edge Controller Linux standard setup final SoftwareModuleType eclApp = softwareModuleTypeRepository.save(new SoftwareModuleType("application", "ECL Application", "Edge Controller Linux base application type", 1)); final SoftwareModuleType eclOs = softwareModuleTypeRepository @@ -327,13 +325,11 @@ public class SystemManagement { "Standard Edge Controller Linux distribution set type. OS only.").addMandatoryModuleType(eclOs) .addOptionalModuleType(eclApp)); - final DistributionSetType defaultType = distributionSetTypeRepository + return distributionSetTypeRepository .save(new DistributionSetType("ecl_os_app_jvm", "OS with optional app and jvm", "Standard Edge Controller Linux distribution set type. OS with optional application.") .addMandatoryModuleType(eclOs).addOptionalModuleType(eclApp) .addOptionalModuleType(eclJvm)); - - return defaultType; } /** @@ -343,19 +339,11 @@ public class SystemManagement { * default types we need to use the tenant the current tenant which is * currently created and not the one currently in the {@link TenantAware}. * - * - * */ private class CurrentTenantKeyGenerator implements KeyGenerator { - - /* - * (non-Javadoc) - * - * @see - * org.springframework.cache.interceptor.KeyGenerator#generate(java.lang - * .Object, java.lang.reflect.Method, java.lang.Object[]) - */ @Override + // Exception squid:S923 - override + @SuppressWarnings({ "squid:S923" }) public Object generate(final Object target, final Method method, final Object... params) { final String initialTenantCreation = createInitialTenant.get(); if (initialTenantCreation == null) { diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TagManagement.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TagManagement.java index e0ab951ac..8db9773e6 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TagManagement.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TagManagement.java @@ -38,21 +38,17 @@ import org.springframework.data.jpa.domain.Specification; import org.springframework.data.jpa.repository.Modifying; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Transactional; import org.springframework.validation.annotation.Validated; import com.google.common.eventbus.EventBus; /** - * - * Mangement service class for {@link Tag}s. - * - * - * - * + * Management service class for {@link Tag}s. * */ -@Transactional(readOnly = true) +@Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) @Validated @Service public class TagManagement { @@ -102,7 +98,7 @@ public class TagManagement { * if given object already exists */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @NotNull @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_TARGET) public TargetTag createTargetTag(@NotNull final TargetTag targetTag) { @@ -133,7 +129,7 @@ public class TagManagement { * if given object has already an ID. */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @NotNull @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_TARGET) public List createTargetTags(@NotNull final Iterable targetTags) { @@ -155,7 +151,7 @@ public class TagManagement { * tag name of the {@link TargetTag} to be deleted */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_TARGET) public void deleteTargetTag(@NotEmpty final String targetTagName) { final TargetTag tag = targetTagRepository.findByNameEquals(targetTagName); @@ -220,7 +216,7 @@ public class TagManagement { * @return the new {@link TargetTag} */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @NotNull @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_TARGET) public TargetTag updateTargetTag(@NotNull final TargetTag targetTag) { @@ -254,7 +250,7 @@ public class TagManagement { * */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY) public DistributionSetTag createDistributionSetTag(@NotNull final DistributionSetTag distributionSetTag) { if (null != distributionSetTag.getId()) { @@ -282,7 +278,7 @@ public class TagManagement { * if a given entity already exists */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_REPOSITORY) public List createDistributionSetTags( @NotNull final Iterable distributionSetTags) { @@ -306,7 +302,7 @@ public class TagManagement { * to be deleted */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_REPOSITORY) public void deleteDistributionSetTag(@NotEmpty final String tagName) { final DistributionSetTag tag = distributionSetTagRepository.findByNameEquals(tagName); @@ -335,7 +331,7 @@ public class TagManagement { * of {@link DistributionSetTag#getName()} is null */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @NotNull @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_REPOSITORY) public DistributionSetTag updateDistributionSetTag(@NotNull final DistributionSetTag distributionSetTag) { diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TargetFilterQueryManagement.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TargetFilterQueryManagement.java index c55127d0f..4f7c91da3 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TargetFilterQueryManagement.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TargetFilterQueryManagement.java @@ -26,6 +26,7 @@ import org.springframework.data.jpa.domain.Specifications; import org.springframework.data.jpa.repository.Modifying; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.Assert; import org.springframework.validation.annotation.Validated; @@ -35,10 +36,8 @@ import com.google.common.base.Strings; /** * Business service facade for managing {@link TargetFilterQuery}s. * - * - * */ -@Transactional(readOnly = true) +@Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) @Validated @Service public class TargetFilterQueryManagement { @@ -53,7 +52,7 @@ public class TargetFilterQueryManagement { * @return the created {@link TargetFilterQuery} */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @NotNull @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_TARGET) public TargetFilterQuery createTargetFilterQuery(@NotNull final TargetFilterQuery customTargetFilter) { @@ -71,7 +70,7 @@ public class TargetFilterQueryManagement { * IDs of target filter query to be deleted */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_TARGET) public void deleteTargetFilterQuery(@NotNull final Long targetFilterQueryId) { targetFilterQueryRepository.delete(targetFilterQueryId); @@ -161,7 +160,7 @@ public class TargetFilterQueryManagement { * @return the updated {@link TargetFilterQuery} */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @NotNull @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_TARGET) public TargetFilterQuery updateTargetFilterQuery(@NotNull final TargetFilterQuery targetFilterQuery) { diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TargetFilterQueryRepository.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TargetFilterQueryRepository.java index b9bfcc8b6..3604785cd 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TargetFilterQueryRepository.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TargetFilterQueryRepository.java @@ -12,13 +12,14 @@ import org.eclipse.hawkbit.repository.model.TargetFilterQuery; import org.springframework.data.domain.Page; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Modifying; +import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Transactional; /** - * + * Spring data repositories for {@link TargetFilterQuery}s. * */ -@Transactional(readOnly = true) +@Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) public interface TargetFilterQueryRepository extends BaseEntityRepository, JpaSpecificationExecutor { diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TargetInfoRepository.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TargetInfoRepository.java index 4582b7397..436f1e7b6 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TargetInfoRepository.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TargetInfoRepository.java @@ -12,7 +12,6 @@ import java.util.Collection; import java.util.List; import javax.persistence.Entity; -import javax.transaction.Transactional; import org.eclipse.hawkbit.repository.model.TargetInfo; import org.eclipse.hawkbit.repository.model.TargetUpdateStatus; @@ -20,15 +19,16 @@ import org.springframework.cache.annotation.CacheEvict; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Transactional; /** * Usually a JPA spring data repository to handle {@link TargetInfo} entity. * However, do to an eclipselink bug with spring boot now a regular interface * that is implemented by {@link EclipseLinkTargetInfoRepository}. * - * - * */ +@Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) public interface TargetInfoRepository { /** @@ -41,7 +41,7 @@ public interface TargetInfoRepository { * to set it for */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @Query("update TargetInfo ti set ti.updateStatus = :status where ti.targetId in :targets and ti.updateStatus != :status") void setTargetUpdateStatus(@Param("status") TargetUpdateStatus status, @Param("targets") List targets); @@ -63,7 +63,7 @@ public interface TargetInfoRepository { * to delete */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @CacheEvict(value = { "targetStatus", "distributionUsageInstalled", "targetsLastPoll" }, allEntries = true) void deleteByTargetIdIn(final Collection targetIDs); } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TargetManagement.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TargetManagement.java index e790d0a5e..4d6540acf 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TargetManagement.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TargetManagement.java @@ -43,7 +43,7 @@ import org.eclipse.hawkbit.repository.model.TargetIdName; import org.eclipse.hawkbit.repository.model.TargetInfo; import org.eclipse.hawkbit.repository.model.TargetInfo_; import org.eclipse.hawkbit.repository.model.TargetTag; -import org.eclipse.hawkbit.repository.model.TargetTagAssigmentResult; +import org.eclipse.hawkbit.repository.model.TargetTagAssignmentResult; import org.eclipse.hawkbit.repository.model.TargetUpdateStatus; import org.eclipse.hawkbit.repository.model.Target_; import org.eclipse.hawkbit.repository.rsql.RSQLUtility; @@ -53,7 +53,6 @@ import org.hibernate.validator.constraints.NotEmpty; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheEvict; import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Slice; import org.springframework.data.domain.SliceImpl; @@ -63,6 +62,7 @@ import org.springframework.data.jpa.domain.Specification; import org.springframework.data.jpa.repository.Modifying; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.Assert; import org.springframework.validation.annotation.Validated; @@ -74,10 +74,8 @@ import com.google.common.eventbus.EventBus; /** * Business service facade for managing {@link Target}s. * - * - * */ -@Transactional(readOnly = true) +@Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) @Validated @Service public class TargetManagement { @@ -157,7 +155,7 @@ public class TargetManagement { * @return List of found{@link Target}s */ @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) - public List findTargetsByControllerID(@NotEmpty final Collection controllerIDs) { + public List findTargetByControllerID(@NotEmpty final Collection controllerIDs) { return targetRepository.findAll(TargetSpecifications.byControllerIdWithStatusAndAssignedInJoin(controllerIDs)); } @@ -263,7 +261,7 @@ public class TargetManagement { * @return the updated {@link Target} */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @NotNull @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_TARGET + SpringEvalExpressions.HAS_AUTH_OR + SpringEvalExpressions.IS_CONTROLLER) @@ -281,7 +279,7 @@ public class TargetManagement { * @return the updated {@link Target}s */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @NotNull @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_TARGET + SpringEvalExpressions.HAS_AUTH_OR + SpringEvalExpressions.IS_CONTROLLER) @@ -297,7 +295,7 @@ public class TargetManagement { * the technical IDs of the targets to be deleted */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_DELETE_TARGET) public void deleteTargets(@NotEmpty final Long... targetIDs) { // we need to select the target IDs first to check the if the targetIDs @@ -333,10 +331,10 @@ public class TargetManagement { } /** - * retrieves {@link Target}s by the assigned {@link DistributionSet} without + * Retrieves {@link Target}s by the assigned {@link DistributionSet} without * details, i.e. NO {@link Target#getTags()} and - * {@link Target#getActiveActions()} possible including the filtering based - * on the given {@code spec}. + * {@link Target#getActiveActions()} possible including additional filtering + * based on the given {@code spec}. * * @param distributionSetID * the ID of the {@link DistributionSet} @@ -376,7 +374,8 @@ public class TargetManagement { /** * retrieves {@link Target}s by the installed {@link DistributionSet}without * details, i.e. NO {@link Target#getTags()} and - * {@link Target#getActiveActions()} possible. + * {@link Target#getActiveActions()} possible including additional filtering + * based on the given {@code spec}. * * @param distributionSetId * the ID of the {@link DistributionSet} @@ -492,7 +491,7 @@ public class TargetManagement { if (!Strings.isNullOrEmpty(searchText)) { specList.add(TargetSpecifications.likeNameOrDescriptionOrIp(searchText)); } - if (selectTargetWithNoTag || (tagNames != null && tagNames.length > 0)) { + if (selectTargetWithNoTag != null && (selectTargetWithNoTag || (tagNames != null && tagNames.length > 0))) { specList.add(TargetSpecifications.hasTags(tagNames, selectTargetWithNoTag)); } return specList; @@ -529,14 +528,14 @@ public class TargetManagement { * @param targets * to toggle for * @param tag - * to toogle - * @return TagAssigmentResult with all metadata of the assigment outcome. + * to toggle + * @return TagAssigmentResult with all metadata of the assignment outcome. */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @NotNull @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_TARGET) - public TargetTagAssigmentResult toggleTagAssignment(@NotEmpty final List targets, + public TargetTagAssignmentResult toggleTagAssignment(@NotEmpty final List targets, @NotNull final TargetTag tag) { return toggleTagAssignment( targets.stream().map(target -> target.getControllerId()).collect(Collectors.toList()), tag.getName()); @@ -555,10 +554,10 @@ public class TargetManagement { * @return TagAssigmentResult with all metadata of the assigment outcome. */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @NotNull @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_TARGET) - public TargetTagAssigmentResult toggleTagAssignment(@NotEmpty final Collection targetIds, + public TargetTagAssignmentResult toggleTagAssignment(@NotEmpty final Collection targetIds, @NotNull final String tagName) { final TargetTag tag = targetTagRepository.findByNameEquals(tagName); final List alreadyAssignedTargets = targetRepository.findByTagNameAndControllerIdIn(tagName, targetIds); @@ -568,7 +567,7 @@ public class TargetManagement { // all are already assigned -> unassign if (alreadyAssignedTargets.size() == allTargets.size()) { alreadyAssignedTargets.forEach(target -> target.getTags().remove(tag)); - final TargetTagAssigmentResult result = new TargetTagAssigmentResult(0, 0, alreadyAssignedTargets.size(), + final TargetTagAssignmentResult result = new TargetTagAssignmentResult(0, 0, alreadyAssignedTargets.size(), Collections.emptyList(), alreadyAssignedTargets, tag); afterCommit.afterCommit(() -> eventBus.post(new TargetTagAssigmentResultEvent(result))); @@ -578,7 +577,7 @@ public class TargetManagement { allTargets.removeAll(alreadyAssignedTargets); // some or none are assigned -> assign allTargets.forEach(target -> target.getTags().add(tag)); - final TargetTagAssigmentResult result = new TargetTagAssigmentResult(alreadyAssignedTargets.size(), + final TargetTagAssignmentResult result = new TargetTagAssignmentResult(alreadyAssignedTargets.size(), allTargets.size(), 0, targetRepository.save(allTargets), Collections.emptyList(), tag); afterCommit.afterCommit(() -> eventBus.post(new TargetTagAssigmentResultEvent(result))); @@ -598,7 +597,7 @@ public class TargetManagement { * @return list of assigned targets */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @NotNull @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_TARGET) public List assignTag(@NotEmpty final Collection targetIds, @NotNull final TargetTag tag) { @@ -609,7 +608,7 @@ public class TargetManagement { final List save = targetRepository.save(allTargets); afterCommit.afterCommit(() -> { - final TargetTagAssigmentResult assigmentResult = new TargetTagAssigmentResult(0, save.size(), 0, save, + final TargetTagAssignmentResult assigmentResult = new TargetTagAssignmentResult(0, save.size(), 0, save, Collections.emptyList(), tag); eventBus.post(new TargetTagAssigmentResultEvent(assigmentResult)); }); @@ -622,7 +621,7 @@ public class TargetManagement { final List save = targetRepository.save(targets); afterCommit.afterCommit(() -> { - final TargetTagAssigmentResult assigmentResult = new TargetTagAssigmentResult(0, 0, save.size(), + final TargetTagAssignmentResult assigmentResult = new TargetTagAssignmentResult(0, 0, save.size(), Collections.emptyList(), save, tag); eventBus.post(new TargetTagAssigmentResultEvent(assigmentResult)); }); @@ -637,7 +636,7 @@ public class TargetManagement { * @return list of unassigned targets */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @NotNull @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_TARGET) public List unAssignAllTargetsByTag(@NotNull final TargetTag tag) { @@ -654,7 +653,7 @@ public class TargetManagement { * @return the unassigned target or if no target is unassigned */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @PreAuthorize(SpringEvalExpressions.HAS_AUTH_UPDATE_TARGET) public Target unAssignTag(@NotNull final String controllerID, @NotNull final TargetTag targetTag) { final List allTargets = targetRepository @@ -812,14 +811,12 @@ public class TargetManagement { } /** - * finds all {@link Target#getControllerId()} for all the given parameters. + * Finds all targets for all the given parameters but returns not the full + * target but {@link TargetIdName}. * * @param pageRequest * the pageRequest to enhance the query for paging and sorting - * @param filterByDistributionId - * to find targets having the {@link DistributionSet} as - * installed or assigned. Set to null in case this - * is not required. + * * @param filterByStatus * find targets having this {@link TargetUpdateStatus}s. Set to * null in case this is not required. @@ -827,28 +824,38 @@ public class TargetManagement { * to find targets having the text anywhere in name or * description. Set null in case this is not * required. + * @param installedOrAssignedDistributionSetId + * to find targets having the {@link DistributionSet} as + * installed or assigned. Set to null in case this + * is not required. * @param filterByTagNames * to find targets which are having any one in this tag names. * Set null in case this is not required. * @param selectTargetWithNoTag * flag to select targets with no tag assigned * - * @return the found {@link Target}s + * @return the found {@link TargetIdName}s */ @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) - public List findAllTargetIdsByFilters(final PageRequest pageRequest, - final Long filterByDistributionId, final Collection filterByStatus, - final String filterBySearchText, final Boolean selectTargetWithNoTag, final String... filterByTagNames) { + public List findAllTargetIdsByFilters(@NotNull final Pageable pageRequest, + final Collection filterByStatus, final String filterBySearchText, + final Long installedOrAssignedDistributionSetId, final Boolean selectTargetWithNoTag, + final String... filterByTagNames) { final CriteriaBuilder cb = entityManager.getCriteriaBuilder(); final CriteriaQuery query = cb.createQuery(Object[].class); final Root targetRoot = query.from(Target.class); List resultList; + + String sortProperty = Target_.id.getName(); + if (pageRequest.getSort() != null && pageRequest.getSort().iterator().hasNext()) { + sortProperty = pageRequest.getSort().iterator().next().getProperty(); + } + final CriteriaQuery multiselect = query.multiselect(targetRoot.get(Target_.id), - targetRoot.get(Target_.controllerId), targetRoot.get(Target_.name), - targetRoot.get(pageRequest.getSort().iterator().next().getProperty())); + targetRoot.get(Target_.controllerId), targetRoot.get(Target_.name), targetRoot.get(sortProperty)); final Predicate[] specificationsForMultiSelect = specificationsToPredicate( - buildSpecificationList(filterByStatus, filterBySearchText, filterByDistributionId, + buildSpecificationList(filterByStatus, filterBySearchText, installedOrAssignedDistributionSetId, selectTargetWithNoTag, false, filterByTagNames), targetRoot, multiselect, cb); @@ -864,24 +871,29 @@ public class TargetManagement { } /** - * Finds all {@link Target#getControllerId()} for all the given parameter - * {@link TargetFilterQuery}. + * Finds all targets for all the given parameter {@link TargetFilterQuery} + * and returns not the full target but {@link TargetIdName}. * * @param pageRequest * the pageRequest to enhance the query for paging and sorting * @param targetFilterQuery * {@link TargetFilterQuery} - * @return the found {@link Target}s + * @return the found {@link TargetIdName}s */ @PreAuthorize(SpringEvalExpressions.HAS_AUTH_READ_TARGET) - public List findAllTargetIdsByTargetFilterQuery(final PageRequest pageRequest, + public List findAllTargetIdsByTargetFilterQuery(final Pageable pageRequest, @NotNull final TargetFilterQuery targetFilterQuery) { final CriteriaBuilder cb = entityManager.getCriteriaBuilder(); final CriteriaQuery query = cb.createQuery(Object[].class); final Root targetRoot = query.from(Target.class); + + String sortProperty = Target_.id.getName(); + if (pageRequest.getSort() != null && pageRequest.getSort().iterator().hasNext()) { + sortProperty = pageRequest.getSort().iterator().next().getProperty(); + } + final CriteriaQuery multiselect = query.multiselect(targetRoot.get(Target_.id), - targetRoot.get(Target_.controllerId), targetRoot.get(Target_.name), - targetRoot.get(pageRequest.getSort().iterator().next().getProperty())); + targetRoot.get(Target_.controllerId), targetRoot.get(Target_.name), targetRoot.get(sortProperty)); final Specification spec = RSQLUtility.parse(targetFilterQuery.getQuery(), TargetFields.class); final List> specList = new ArrayList<>(); @@ -923,7 +935,7 @@ public class TargetManagement { * @return */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @NotNull @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_TARGET + SpringEvalExpressions.HAS_AUTH_OR + SpringEvalExpressions.IS_CONTROLLER) @@ -961,7 +973,7 @@ public class TargetManagement { * */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @NotNull @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_TARGET + SpringEvalExpressions.HAS_AUTH_OR + SpringEvalExpressions.IS_CONTROLLER) @@ -985,7 +997,7 @@ public class TargetManagement { * already exist. */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @NotNull @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_TARGET) public List createTargets(@NotNull final List targets) { @@ -1017,7 +1029,7 @@ public class TargetManagement { * @return newly created target */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @NotNull @PreAuthorize(SpringEvalExpressions.HAS_AUTH_CREATE_TARGET) public List createTargets(@NotNull final Collection targets, @@ -1074,7 +1086,7 @@ public class TargetManagement { return targetRepository.count(specs); } - private List getTargetIdNameResultSet(final PageRequest pageRequest, final CriteriaBuilder cb, + private List getTargetIdNameResultSet(final Pageable pageRequest, final CriteriaBuilder cb, final Root targetRoot, final CriteriaQuery multiselect) { List resultList; if (pageRequest.getSort() != null) { diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TargetRepository.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TargetRepository.java index 35ba39660..5e37902ab 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TargetRepository.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TargetRepository.java @@ -27,15 +27,14 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; +import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Transactional; /** * {@link Target} repository. * - * - * */ -@Transactional(readOnly = true) +@Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) public interface TargetRepository extends BaseEntityRepository, JpaSpecificationExecutor { /** @@ -64,7 +63,7 @@ public interface TargetRepository extends BaseEntityRepository, Jp * to be deleted */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) // Workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=349477 @Query("DELETE FROM Target t WHERE t.id IN ?1") void deleteByIdIn(final Collection targetIDs); @@ -153,7 +152,7 @@ public interface TargetRepository extends BaseEntityRepository, Jp */ @Override @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @CacheEvict(value = { "targetStatus", "distributionUsageInstalled", "targetsLastPoll" }, allEntries = true) List save(Iterable entities); @@ -167,7 +166,7 @@ public interface TargetRepository extends BaseEntityRepository, Jp */ @Override @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @CacheEvict(value = { "targetStatus", "distributionUsageInstalled", "targetsLastPoll" }, allEntries = true) S save(S entity); @@ -276,7 +275,7 @@ public interface TargetRepository extends BaseEntityRepository, Jp * to update */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @Query("UPDATE Target t SET t.assignedDistributionSet = :set, t.lastModifiedAt = :lastModifiedAt, t.lastModifiedBy = :lastModifiedBy WHERE t.id IN :targets") void setAssignedDistributionSet(@Param("set") DistributionSet set, @Param("lastModifiedAt") Long modifiedAt, @Param("lastModifiedBy") String modifiedBy, @Param("targets") Collection targets); diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TargetTagRepository.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TargetTagRepository.java index a81ed81ab..e0f03ee78 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TargetTagRepository.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TargetTagRepository.java @@ -13,15 +13,14 @@ import java.util.List; import org.eclipse.hawkbit.repository.model.TargetTag; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Modifying; +import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Transactional; /** * {@link TargetTag} repository. * - * - * */ -@Transactional(readOnly = true) +@Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) public interface TargetTagRepository extends BaseEntityRepository, JpaSpecificationExecutor { @@ -33,7 +32,7 @@ public interface TargetTagRepository * @return 1 if tag was deleted */ @Modifying - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) Long deleteByName(final String tagName); /** diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TenantConfigurationManagement.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TenantConfigurationManagement.java index f6b6afcfc..c292b39e3 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TenantConfigurationManagement.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TenantConfigurationManagement.java @@ -24,18 +24,19 @@ import org.springframework.core.convert.support.DefaultConversionService; import org.springframework.core.env.Environment; import org.springframework.data.jpa.repository.Modifying; import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Transactional; import org.springframework.validation.annotation.Validated; /** * Central tenant configuration management operations of the SP server. */ -@Transactional(readOnly = true) +@Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) @Validated +@Service public class TenantConfigurationManagement implements EnvironmentAware { - private static final TenantConfigurationManagement INSTANCE = new TenantConfigurationManagement(); - @Autowired private TenantConfigurationRepository tenantConfigurationRepository; @@ -46,16 +47,6 @@ public class TenantConfigurationManagement implements EnvironmentAware { private Environment environment; - /** - * Get Singleton instance, needed for classes which are not managed in - * Spring context - * - * @return singleton instance of TenantConfigurationManagement - */ - public static TenantConfigurationManagement getInstance() { - return INSTANCE; - } - /** * Retrieves a configuration value from the e.g. tenant overwritten * configuration values or in case the tenant does not a have a specific @@ -150,7 +141,7 @@ public class TenantConfigurationManagement implements EnvironmentAware { * @param configurationKey * the key of the configuration * @return the converted configuration value either from the tenant specific - * configuration stored or from the fallback default values or + * configuration stored or from the fall back default values or * {@code null} in case key has not been configured and not default * value exists * @throws TenantConfigurationValidatorException @@ -160,7 +151,8 @@ public class TenantConfigurationManagement implements EnvironmentAware { * if the property cannot be converted to the given * {@code propertyType} */ - @PreAuthorize(value = SpringEvalExpressions.HAS_AUTH_TENANT_CONFIGURATION) + @PreAuthorize(value = SpringEvalExpressions.HAS_AUTH_TENANT_CONFIGURATION + SpringEvalExpressions.HAS_AUTH_OR + + SpringEvalExpressions.IS_SYSTEM_CODE) public TenantConfigurationValue getConfigurationValue(final TenantConfigurationKey configurationKey) { return getConfigurationValue(configurationKey, configurationKey.getDataType()); } @@ -185,7 +177,8 @@ public class TenantConfigurationManagement implements EnvironmentAware { * if the property cannot be converted to the given * {@code propertyType} */ - @PreAuthorize(value = SpringEvalExpressions.HAS_AUTH_TENANT_CONFIGURATION) + @PreAuthorize(value = SpringEvalExpressions.HAS_AUTH_TENANT_CONFIGURATION + SpringEvalExpressions.HAS_AUTH_OR + + SpringEvalExpressions.IS_SYSTEM_CODE) public T getGlobalConfigurationValue(final TenantConfigurationKey configurationKey, final Class propertyType) { @@ -221,7 +214,7 @@ public class TenantConfigurationManagement implements EnvironmentAware { * if the property cannot be converted to the given */ @CacheEvict(value = "tenantConfiguration", key = "#configurationKey.getKeyName()") - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @Modifying @PreAuthorize(value = SpringEvalExpressions.HAS_AUTH_TENANT_CONFIGURATION) public TenantConfigurationValue addOrUpdateConfiguration(final TenantConfigurationKey configurationKey, @@ -264,7 +257,7 @@ public class TenantConfigurationManagement implements EnvironmentAware { * the configuration key to be deleted */ @CacheEvict(value = "tenantConfiguration", key = "#configurationKey.getKeyName()") - @Transactional + @Transactional(isolation = Isolation.READ_UNCOMMITTED) @Modifying @PreAuthorize(value = SpringEvalExpressions.HAS_AUTH_TENANT_CONFIGURATION) public void deleteConfiguration(final TenantConfigurationKey configurationKey) { diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TenantConfigurationRepository.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TenantConfigurationRepository.java index d8973f275..0497ea924 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TenantConfigurationRepository.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TenantConfigurationRepository.java @@ -11,16 +11,14 @@ package org.eclipse.hawkbit.repository; import java.util.List; import org.eclipse.hawkbit.repository.model.TenantConfiguration; +import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Transactional; /** * The spring-data repository for the entity {@link TenantConfiguration}. * - * - * - * */ -@Transactional(readOnly = true) +@Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) public interface TenantConfigurationRepository extends BaseEntityRepository { /** @@ -32,11 +30,6 @@ public interface TenantConfigurationRepository extends BaseEntityRepository findAll(); diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TenantKeyGenerator.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TenantKeyGenerator.java index d0a2b4ea7..3265b622c 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TenantKeyGenerator.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TenantKeyGenerator.java @@ -18,9 +18,6 @@ import org.springframework.stereotype.Service; /** * {@link KeyGenerator} for tenant related caches. * - * - * - * */ @Service public class TenantKeyGenerator implements KeyGenerator { @@ -28,13 +25,6 @@ public class TenantKeyGenerator implements KeyGenerator { @Autowired private TenantAware tenantAware; - /* - * (non-Javadoc) - * - * @see - * org.springframework.cache.interceptor.KeyGenerator#generate(java.lang. - * Object, java.lang.reflect.Method, java.lang.Object[]) - */ @Override public Object generate(final Object target, final Method method, final Object... params) { return tenantAware.getCurrentTenant().toUpperCase(); diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TenantMetaDataRepository.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TenantMetaDataRepository.java index 08d672803..4aa4c48dc 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TenantMetaDataRepository.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/TenantMetaDataRepository.java @@ -12,16 +12,14 @@ import java.util.List; import org.eclipse.hawkbit.repository.model.TenantMetaData; import org.springframework.data.repository.PagingAndSortingRepository; +import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Transactional; /** * repository for operations on {@link TenantMetaData} entity. * - * - * - * */ -@Transactional(readOnly = true) +@Transactional(readOnly = true, isolation = Isolation.READ_UNCOMMITTED) public interface TenantMetaDataRepository extends PagingAndSortingRepository { /** diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/Action.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/Action.java index c19b947de..eedb36037 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/Action.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/Action.java @@ -50,9 +50,9 @@ import org.eclipse.persistence.annotations.CascadeOnDelete; @Index(name = "sp_idx_action_prim", columnList = "tenant,id") }) @NamedEntityGraphs({ @NamedEntityGraph(name = "Action.ds", attributeNodes = { @NamedAttributeNode("distributionSet") }), @NamedEntityGraph(name = "Action.all", attributeNodes = { @NamedAttributeNode("distributionSet"), - @NamedAttributeNode(value = "target", subgraph = "target.ds") }, subgraphs = @NamedSubgraph(name = "target.ds", attributeNodes = @NamedAttributeNode("assignedDistributionSet") ) ) }) + @NamedAttributeNode(value = "target", subgraph = "target.ds") }, subgraphs = @NamedSubgraph(name = "target.ds", attributeNodes = @NamedAttributeNode("assignedDistributionSet"))) }) @Entity -public class Action extends BaseEntity implements Comparable { +public class Action extends TenantAwareBaseEntity { private static final long serialVersionUID = 1L; /** @@ -64,11 +64,11 @@ public class Action extends BaseEntity implements Comparable { * the {@link DistributionSet} which should be installed by this action. */ @ManyToOne(fetch = FetchType.LAZY) - @JoinColumn(name = "distribution_set", foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_action_ds") ) + @JoinColumn(name = "distribution_set", foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_action_ds")) private DistributionSet distributionSet; @ManyToOne(fetch = FetchType.LAZY) - @JoinColumn(name = "target", foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_action_target") ) + @JoinColumn(name = "target", foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_action_target")) private Target target; @Column(name = "active") @@ -90,11 +90,11 @@ public class Action extends BaseEntity implements Comparable { private List actionStatus; @ManyToOne(fetch = FetchType.LAZY) - @JoinColumn(name = "rolloutgroup", foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_action_rolloutgroup") ) + @JoinColumn(name = "rolloutgroup", foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_action_rolloutgroup")) private RolloutGroup rolloutGroup; @ManyToOne(fetch = FetchType.LAZY) - @JoinColumn(name = "rollout", foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_action_rollout") ) + @JoinColumn(name = "rollout", foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_action_rollout")) private Rollout rollout; /** @@ -127,55 +127,30 @@ public class Action extends BaseEntity implements Comparable { return status == Status.CANCELING || status == Status.CANCELED; } - /** - * @param active - * the active to set - */ public void setActive(final boolean active) { this.active = active; } - /** - * @return the status - */ public Status getStatus() { return status; } - /** - * @param status - * the status to set - */ public void setStatus(final Status status) { this.status = status; } - /** - * @return the downloadProgressPercent - */ public int getDownloadProgressPercent() { return downloadProgressPercent; } - /** - * @param downloadProgressPercent - * the downloadProgressPercent to set - */ public void setDownloadProgressPercent(final int downloadProgressPercent) { this.downloadProgressPercent = downloadProgressPercent; } - /** - * @return the active - */ public boolean isActive() { return active; } - /** - * @param actionType - * the actionType to set - */ public void setActionType(final ActionType actionType) { this.actionType = actionType; } @@ -187,81 +162,42 @@ public class Action extends BaseEntity implements Comparable { return actionType; } - /** - * @return the actionStatus - */ public List getActionStatus() { return actionStatus; } - /** - * @param target - * the target to set - */ public void setTarget(final Target target) { this.target = target; } - /** - * @return the target - */ public Target getTarget() { return target; } - /** - * @return the forcedTime - */ public long getForcedTime() { return forcedTime; } - /** - * @param forcedTime - * the forcedTime to set - */ public void setForcedTime(final long forcedTime) { this.forcedTime = forcedTime; } - /** - * @return the rolloutGroup - */ public RolloutGroup getRolloutGroup() { return rolloutGroup; } - /** - * @param rolloutGroup - * the rolloutGroup to set - */ public void setRolloutGroup(final RolloutGroup rolloutGroup) { this.rolloutGroup = rolloutGroup; } - /** - * @return the rollout - */ public Rollout getRollout() { return rollout; } - /** - * @param rollout - * the rollout to set - */ public void setRollout(final Rollout rollout) { this.rollout = rollout; } - @Override - public int compareTo(final Action o) { - if (super.getId() == null || o == null || o.getId() == null) { - return 0; - } - return super.getId().compareTo(o.getId()); - } - /** * checks if the {@link #forcedTime} is hit by the given * {@code hitTimeMillis}, by means if the given milliseconds are greater @@ -305,66 +241,11 @@ public class Action extends BaseEntity implements Comparable { return actionType == ActionType.FORCED; } - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ @Override public String toString() { return "Action [distributionSet=" + distributionSet + ", getId()=" + getId() + "]"; } - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { // NOSONAR - as this is generated - final int prime = 31; - int result = super.hashCode(); - result = prime * result + ((actionType == null) ? 0 : actionType.hashCode()); - result = prime * result + (active ? 1231 : 1237); - result = prime * result + (int) (forcedTime ^ (forcedTime >>> 32)); - result = prime * result + ((status == null) ? 0 : status.hashCode()); - result = prime * result + (isHitAutoForceTime(System.currentTimeMillis()) ? 1231 : 1237); - return result; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(final Object obj) { // NOSONAR - as this is generated - - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final Action other = (Action) obj; - if (actionType != other.actionType) { - return false; - } - if (active != other.active) { - return false; - } - if (forcedTime != other.forcedTime) { - return false; - } - if (status != other.status) { - return false; - } - return true; - } - /** * Action status as reported by the controller. * @@ -424,9 +305,6 @@ public class Action extends BaseEntity implements Comparable { /** * The action type for this action relation. * - * - * - * */ public enum ActionType { FORCED, SOFT, TIMEFORCED; diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/ActionStatus.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/ActionStatus.java index 2b0effae9..c8d320abd 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/ActionStatus.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/ActionStatus.java @@ -32,27 +32,20 @@ import com.google.common.base.Splitter; /** * Entity to store the status for a specific action. - * - * - * */ @Table(name = "sp_action_status", indexes = { @Index(name = "sp_idx_action_status_01", columnList = "tenant,action"), @Index(name = "sp_idx_action_status_02", columnList = "tenant,action,status"), @Index(name = "sp_idx_action_status_prim", columnList = "tenant,id") }) @NamedEntityGraph(name = "ActionStatus.withMessages", attributeNodes = { @NamedAttributeNode("messages") }) @Entity -public class ActionStatus extends BaseEntity { - - /** - * - */ +public class ActionStatus extends TenantAwareBaseEntity { private static final long serialVersionUID = 1L; @Column(name = "target_occurred_at") private Long occurredAt; @ManyToOne(fetch = FetchType.LAZY, optional = false) - @JoinColumn(name = "action", nullable = false, foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_act_stat_action") ) + @JoinColumn(name = "action", nullable = false, foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_act_stat_action")) private Action action; @Column(name = "status") @@ -60,14 +53,14 @@ public class ActionStatus extends BaseEntity { @CascadeOnDelete @ElementCollection(fetch = FetchType.LAZY, targetClass = String.class) - @CollectionTable(name = "sp_action_status_messages", joinColumns = @JoinColumn(name = "action_status_id", foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_stat_msg_act_stat") ) , indexes = { + @CollectionTable(name = "sp_action_status_messages", joinColumns = @JoinColumn(name = "action_status_id", foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_stat_msg_act_stat")), indexes = { @Index(name = "sp_idx_action_status_msgs_01", columnList = "action_status_id") }) @Column(name = "detail_message", length = 512) private final List messages = new ArrayList<>(); /** * Creates a new {@link ActionStatus} object. - * + * * @param action * the action for this action status * @param status @@ -83,7 +76,7 @@ public class ActionStatus extends BaseEntity { /** * Creates a new {@link ActionStatus} object. - * + * * @param action * the action for this action status * @param status @@ -103,67 +96,48 @@ public class ActionStatus extends BaseEntity { } /** - * - */ + * JPA default constructor. + */ public ActionStatus() { + // JPA default constructor. } - /** - * @return the occurredAt - */ public Long getOccurredAt() { return occurredAt; } - /** - * @param occurredAt - * the occurredAt to set - */ public void setOccurredAt(final Long occurredAt) { this.occurredAt = occurredAt; } /** - * Adds message. + * Adds message including splitting in case it exceeds 512 length. * * @param message * to add */ public final void addMessage(final String message) { - Splitter.fixedLength(512).split(message).forEach(chunk -> messages.add(chunk)); + Splitter.fixedLength(512).split(message).forEach(messages::add); } public List getMessages() { return messages; } - /** - * @return the action - */ public Action getAction() { return action; } - /** - * @param action - * the action to set - */ public void setAction(final Action action) { this.action = action; } - /** - * @return the status - */ public Status getStatus() { return status; } - /** - * @param status - * the status to set - */ public void setStatus(final Status status) { this.status = status; } + } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/ActionWithStatusCount.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/ActionWithStatusCount.java index 7d01b9dd2..73eab32f9 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/ActionWithStatusCount.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/ActionWithStatusCount.java @@ -15,9 +15,6 @@ import org.eclipse.hawkbit.repository.model.Action.Status; * Custom JPA Model for querying {@link Action} include the count of the * action's {@link ActionStatus}. * - * - * - * */ public class ActionWithStatusCount { private final Long actionStatusCount; @@ -37,7 +34,7 @@ public class ActionWithStatusCount { /** * JPA constructor, the parameter are the result set columns of the custom * query. - * + * * @param actionId * the ID of the action * @param actionType @@ -70,9 +67,9 @@ public class ActionWithStatusCount { final String rolloutName) { this.actionId = actionId; this.actionType = actionType; - this.actionActive = active; - this.actionForceTime = forcedTime; - this.actionStatus = status; + actionActive = active; + actionForceTime = forcedTime; + actionStatus = status; this.actionCreatedAt = actionCreatedAt; this.actionLastModifiedAt = actionLastModifiedAt; this.dsId = dsId; @@ -81,101 +78,62 @@ public class ActionWithStatusCount { this.actionStatusCount = actionStatusCount; this.rolloutName = rolloutName; - this.action = new Action(); - this.action.setActionType(actionType); - this.action.setActive(actionActive); - this.action.setForcedTime(actionForceTime); - this.action.setStatus(actionStatus); - this.action.setId(actionId); + action = new Action(); + action.setActionType(actionType); + action.setActive(actionActive); + action.setForcedTime(actionForceTime); + action.setStatus(actionStatus); + action.setId(actionId); } - /** - * @return the action - */ public Action getAction() { return action; } - /** - * @return the actionId - */ public Long getActionId() { return actionId; } - /** - * @return the actionType - */ public ActionType getActionType() { return actionType; } - /** - * @return the actionActive - */ public boolean isActionActive() { return actionActive; } - /** - * @return the actionForceTime - */ public long getActionForceTime() { return actionForceTime; } - /** - * @return the actionStatus - */ public Status getActionStatus() { return actionStatus; } - /** - * @return the actionCreatedAt - */ public Long getActionCreatedAt() { return actionCreatedAt; } - /** - * @return the actionLastModifiedAt - */ public Long getActionLastModifiedAt() { return actionLastModifiedAt; } - /** - * @return the dsId - */ public Long getDsId() { return dsId; } - /** - * @return the dsName - */ public String getDsName() { return dsName; } - /** - * @return the dsVersion - */ public String getDsVersion() { return dsVersion; } - /** - * @return the actionStatusCount - */ public Long getActionStatusCount() { return actionStatusCount; } - /** - * @return the rolloutName - */ public String getRolloutName() { return rolloutName; } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/Artifact.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/Artifact.java index 4b868f9a2..b384a3100 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/Artifact.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/Artifact.java @@ -13,14 +13,10 @@ import javax.persistence.MappedSuperclass; /** * Tenant specific locally stored artifact representation that is used by - * {@link SoftwareModule} . - * - * - * - * + * {@link SoftwareModule}. */ @MappedSuperclass -public abstract class Artifact extends BaseEntity { +public abstract class Artifact extends TenantAwareBaseEntity { private static final long serialVersionUID = 1L; @Column(name = "sha1_hash", length = 40, nullable = true) @@ -34,49 +30,27 @@ public abstract class Artifact extends BaseEntity { public abstract SoftwareModule getSoftwareModule(); - /** - * @return the md5Hash - */ public String getMd5Hash() { return md5Hash; } - /** - * @return the sha1Hash - */ public String getSha1Hash() { return sha1Hash; } - /** - * @param md5Hash - * the md5Hash to set - */ public void setMd5Hash(final String md5Hash) { this.md5Hash = md5Hash; } - /** - * @param sha1Hash - * the sha1Hash to set - */ public void setSha1Hash(final String sha1Hash) { this.sha1Hash = sha1Hash; } - /** - * @return the size - */ public Long getSize() { return size; } - /** - * @param size - * the size to set - */ public void setSize(final Long size) { this.size = size; } - } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/AssignmentResult.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/AssignmentResult.java index 05f812b06..2dea94f33 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/AssignmentResult.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/AssignmentResult.java @@ -8,18 +8,21 @@ */ package org.eclipse.hawkbit.repository.model; +import java.util.List; + /** - * Generic assigment result bean. - * - * - * + * Generic assignment result bean. * */ -public class AssignmentResult { +public class AssignmentResult { private final int total; private final int assigned; private final int alreadyAssigned; + + private final int unassigned; + private final List assignedEntity; + private final List unassignedEntity; /** * Constructor. @@ -27,34 +30,47 @@ public class AssignmentResult { * @param assigned * is the number of newly assigned elements. * @param alreadyAssigned - * is the number of already assigned elements. + * number of already assigned/ignored elements + * @param unassigned + * number of newly assigned elements + * @param assignedEntity + * {@link List} of assigned entity. + * @param unassignedEntity + * {@link List} of unassigned entity. */ - public AssignmentResult(final int assigned, final int alreadyAssigned) { - super(); + public AssignmentResult(final int assigned, final int alreadyAssigned, final int unassigned, + final List assignedEntity, final List unassignedEntity) { this.assigned = assigned; this.alreadyAssigned = alreadyAssigned; total = assigned + alreadyAssigned; + this.unassigned = unassigned; + this.assignedEntity = assignedEntity; + this.unassignedEntity = unassignedEntity; } - - /** - * @return the assignedTargets - */ + public int getAssigned() { return assigned; } - - /** - * @return the total - */ + public int getTotal() { return total; } - - /** - * @return the alreadyAssigned - */ + public int getAlreadyAssigned() { return alreadyAssigned; } + + + public int getUnassigned() { + return unassigned; + } + + public List getAssignedEntity() { + return assignedEntity; + } + + public List getUnassignedEntity() { + return unassignedEntity; + } } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/BaseEntity.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/BaseEntity.java index 72d25be6c..65300c6c4 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/BaseEntity.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/BaseEntity.java @@ -18,17 +18,10 @@ import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.MappedSuperclass; -import javax.persistence.PrePersist; import javax.persistence.Version; import org.eclipse.hawkbit.eventbus.CacheFieldEntityListener; import org.eclipse.hawkbit.eventbus.EntityPropertyChangeListener; -import org.eclipse.hawkbit.repository.exception.TenantNotExistException; -import org.eclipse.hawkbit.repository.model.helper.SystemManagementHolder; -import org.eclipse.hawkbit.repository.model.helper.TenantAwareHolder; -import org.eclipse.persistence.annotations.Multitenant; -import org.eclipse.persistence.annotations.MultitenantType; -import org.eclipse.persistence.annotations.TenantDiscriminatorColumn; import org.springframework.data.annotation.CreatedBy; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.LastModifiedBy; @@ -37,18 +30,12 @@ import org.springframework.data.jpa.domain.support.AuditingEntityListener; import org.springframework.hateoas.Identifiable; /** - * Holder of all base attributes common to all entities. - * - * - * - * + * Holder of the base attributes common to all entities. * */ @MappedSuperclass @Access(AccessType.FIELD) @EntityListeners({ AuditingEntityListener.class, CacheFieldEntityListener.class, EntityPropertyChangeListener.class }) -@TenantDiscriminatorColumn(name = "tenant", length = 40) -@Multitenant(MultitenantType.SINGLE_TABLE) public abstract class BaseEntity implements Serializable, Identifiable { private static final long serialVersionUID = 1L; @@ -66,44 +53,11 @@ public abstract class BaseEntity implements Serializable, Identifiable { @Column(name = "optlock_revision") private long optLockRevision; - @Column(name = "tenant", nullable = false, insertable = false, updatable = false, length = 40) - private String tenant; - /** - * - */ + * Default constructor needed for JPA entities. + */ public BaseEntity() { - - } - - /** - * @param entity - * the entity to copy - */ - public BaseEntity(final BaseEntity entity) { - id = entity.id; - createdAt = entity.createdAt; - createdBy = entity.createdBy; - lastModifiedAt = entity.lastModifiedAt; - lastModifiedBy = entity.lastModifiedBy; - optLockRevision = entity.optLockRevision; - } - - /** - * PrePersist listener method for all {@link BaseEntity} entities. - */ - @PrePersist - public void prePersist() { - // before persisting the entity check the current ID of the tenant by - // using the TenantAware - // service - final String currentTenant = SystemManagementHolder.getInstance().currentTenant(); - if (currentTenant == null) { - throw new TenantNotExistException("Tenant " - + TenantAwareHolder.getInstance().getTenantAware().getCurrentTenant() - + " does not exists, cannot create entity " + this.getClass() + " with id " + id); - } - setTenant(currentTenant.toUpperCase()); + // Default constructor needed for JPA entities. } @Access(AccessType.PROPERTY) @@ -130,37 +84,21 @@ public abstract class BaseEntity implements Serializable, Identifiable { return lastModifiedBy; } - /** - * @param createdBy - * the createdBy to set - */ @CreatedBy public void setCreatedBy(final String createdBy) { this.createdBy = createdBy; } - /** - * @param lastModifiedBy - * the lastModifiedBy to set - */ @LastModifiedBy public void setLastModifiedBy(final String lastModifiedBy) { this.lastModifiedBy = lastModifiedBy; } - /** - * @param createdAt - * the createdAt to set - */ @CreatedDate public void setCreatedAt(final Long createdAt) { this.createdAt = createdAt; } - /** - * @param lastModifiedAt - * the lastModifiedAt to set - */ @LastModifiedDate public void setLastModifiedAt(final Long lastModifiedAt) { this.lastModifiedAt = lastModifiedAt; @@ -170,49 +108,29 @@ public abstract class BaseEntity implements Serializable, Identifiable { return optLockRevision; } - /** - * @return the tenant - */ - public String getTenant() { - return tenant; + // for test purposes only + void setOptLockRevision(final long optLockRevision) { + this.optLockRevision = optLockRevision; } - /** - * @param tenant - * the tenant to set - */ - public void setTenant(final String tenant) { - this.tenant = tenant; - } - - /** - * @return the id - */ @Override public Long getId() { return id; } - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ @Override public String toString() { return "BaseEntity [id=" + id + "]"; } - /** - * @param id - * the id to set - */ public void setId(final Long id) { this.id = id; } - /* - * (non-Javadoc) + /** + * Defined equals/hashcode strategy for the repository in general is that an + * entity is equal if it has the same {@link #getId()} and + * {@link #getOptLockRevision()} and class. * * @see java.lang.Object#hashCode() */ @@ -222,11 +140,14 @@ public abstract class BaseEntity implements Serializable, Identifiable { int result = 1; result = prime * result + (id == null ? 0 : id.hashCode()); result = prime * result + (int) (optLockRevision ^ optLockRevision >>> 32); + result = prime * result + this.getClass().getName().hashCode(); return result; } - /* - * (non-Javadoc) + /** + * Defined equals/hashcode strategy for the repository in general is that an + * entity is equal if it has the same {@link #getId()} and + * {@link #getOptLockRevision()} and class. * * @see java.lang.Object#equals(java.lang.Object) */ @@ -239,7 +160,7 @@ public abstract class BaseEntity implements Serializable, Identifiable { if (obj == null) { return false; } - if (getClass() != obj.getClass()) { + if (!(this.getClass().isInstance(obj))) { return false; } final BaseEntity other = (BaseEntity) obj; diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/CustomSoftwareModule.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/CustomSoftwareModule.java index 96c7cdd62..34aa8345a 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/CustomSoftwareModule.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/CustomSoftwareModule.java @@ -13,9 +13,6 @@ import java.io.Serializable; /** * Use to display software modules for the selected distribution. * - * - * - * */ public class CustomSoftwareModule implements Serializable { @@ -39,17 +36,51 @@ public class CustomSoftwareModule implements Serializable { this.assigned = assigned; } - /** - * @return the softwareModule - */ public SoftwareModule getSoftwareModule() { return softwareModule; } - /** - * @return the assigned - */ public boolean isAssigned() { return assigned; } + + @Override + public String toString() { + return "CustomSoftwareModule [softwareModule=" + softwareModule + ", assigned=" + assigned + "]"; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + (assigned ? 1231 : 1237); + result = prime * result + (softwareModule == null ? 0 : softwareModule.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (!(obj instanceof CustomSoftwareModule)) { + return false; + } + final CustomSoftwareModule other = (CustomSoftwareModule) obj; + if (assigned != other.assigned) { + return false; + } + if (softwareModule == null) { + if (other.softwareModule != null) { + return false; + } + } else if (!softwareModule.equals(other.softwareModule)) { + return false; + } + return true; + } + } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSet.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSet.java index e0444bc28..a9d390284 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSet.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSet.java @@ -46,10 +46,6 @@ import org.eclipse.persistence.annotations.CascadeOnDelete; * A {@link Target} has exactly one target {@link DistributionSet} assigned. *

* - * - * - * - * */ @Entity @Table(name = "sp_distribution_set", uniqueConstraints = { @@ -67,14 +63,14 @@ public class DistributionSet extends NamedVersionedEntity { @ManyToMany(targetEntity = SoftwareModule.class, fetch = FetchType.LAZY) @JoinTable(name = "sp_ds_module", joinColumns = { - @JoinColumn(name = "ds_id", foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_ds_module_ds") ) }, inverseJoinColumns = { - @JoinColumn(name = "module_id", foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_ds_module_module") ) }) + @JoinColumn(name = "ds_id", foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_ds_module_ds")) }, inverseJoinColumns = { + @JoinColumn(name = "module_id", foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_ds_module_module")) }) private final Set modules = new HashSet<>(); @ManyToMany(targetEntity = DistributionSetTag.class) @JoinTable(name = "sp_ds_dstag", joinColumns = { - @JoinColumn(name = "ds", foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_ds_dstag_ds") ) }, inverseJoinColumns = { - @JoinColumn(name = "TAG", foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_ds_dstag_tag") ) }) + @JoinColumn(name = "ds", foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_ds_dstag_ds")) }, inverseJoinColumns = { + @JoinColumn(name = "TAG", foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_ds_dstag_tag")) }) private Set tags = new HashSet<>(); @Column(name = "deleted") @@ -95,7 +91,7 @@ public class DistributionSet extends NamedVersionedEntity { private final List metadata = new ArrayList<>(); @ManyToOne(fetch = FetchType.LAZY) - @JoinColumn(name = "ds_id", nullable = false, foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_ds_dstype_ds") ) + @JoinColumn(name = "ds_id", nullable = false, foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_ds_dstype_ds")) private DistributionSetType type; @Column(name = "complete") @@ -130,75 +126,34 @@ public class DistributionSet extends NamedVersionedEntity { if (moduleList != null) { moduleList.forEach(this::addModule); } - complete = type.checkComplete(this); + if (this.type != null) { + complete = this.type.checkComplete(this); + } } public Set getTags() { return tags; } - /** - * @return the deleted - */ public boolean isDeleted() { return deleted; } /** - * @return the metadata + * @return immutable list of meta data elements. */ public List getMetadata() { - return metadata; + return Collections.unmodifiableList(metadata); } - /** - * @return the actions - */ public List getActions() { return actions; } - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + this.getClass().getName().hashCode(); - return result; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (!(obj instanceof DistributionSet)) { - return false; - } - - return true; - } - public boolean isRequiredMigrationStep() { return requiredMigrationStep; } - /** - * @param deleted - * the deleted to set - */ public DistributionSet setDeleted(final boolean deleted) { this.deleted = deleted; return this; @@ -209,10 +164,6 @@ public class DistributionSet extends NamedVersionedEntity { return this; } - /** - * @param tags - * the tags to set - */ public DistributionSet setTags(final Set tags) { this.tags = tags; return this; @@ -232,11 +183,6 @@ public class DistributionSet extends NamedVersionedEntity { return installedAtTargets; } - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ @Override public String toString() { return "DistributionSet [getName()=" + getName() + ", getOptLockRevision()=" + getOptLockRevision() @@ -322,7 +268,7 @@ public class DistributionSet extends NamedVersionedEntity { * Searches through modules for the given type. * * @param type - * to seach for + * to search for * @return SoftwareModule of given type or null if not in the * list. */ @@ -337,26 +283,15 @@ public class DistributionSet extends NamedVersionedEntity { return null; } - /** - * @return the type - */ public DistributionSetType getType() { return type; } - /** - * @param type - * the type to set - */ public void setType(final DistributionSetType type) { this.type = type; } - /** - * @return the complete - */ public boolean isComplete() { return complete; } - } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetIdName.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetIdName.java index a7eb8e517..f8662567a 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetIdName.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetIdName.java @@ -15,9 +15,6 @@ import java.io.Serializable; * */ public class DistributionSetIdName implements Serializable { - /** - * - */ private static final long serialVersionUID = 1L; private final Long id; @@ -39,9 +36,6 @@ public class DistributionSetIdName implements Serializable { this.version = version; } - /** - * @return the id - */ public Long getId() { return id; } @@ -50,40 +44,27 @@ public class DistributionSetIdName implements Serializable { return version; } - /** - * @return the name - */ public String getName() { return name; } - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ @Override - public int hashCode() { // NOSONAR - as this is generated + public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (id == null ? 0 : id.hashCode()); return result; } - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ @Override - public boolean equals(final Object obj) { // NOSONAR - as this is generated + public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } - if (getClass() != obj.getClass()) { + if (!(obj instanceof DistributionSetIdName)) { return false; } final DistributionSetIdName other = (DistributionSetIdName) obj; @@ -97,11 +78,6 @@ public class DistributionSetIdName implements Serializable { return true; } - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ @Override public String toString() { // only return the ID because it's used in vaadin for setting the item 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 b0627f0db..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 @@ -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; @@ -23,99 +19,62 @@ import javax.persistence.ManyToOne; import javax.persistence.Table; /** - * Metadata for {@link DistributionSet}. - * - * - * + * Meta data for {@link DistributionSet}. * */ @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") ) + @JoinColumn(name = "ds_id", foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_metadata_ds")) private DistributionSet distributionSet; public DistributionSetMetadata() { - + // default public constructor for JPA } - /** - * Parameter constructor. - * - * @param key - * @param distributionSet - * @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); + return new DsMetadataCompositeKey(distributionSet, getKey()); } - /** - * @return the key - */ - public String getKey() { - return key; - } - - /** - * @param key - * the key to set - */ - public void setKey(final String key) { - this.key = key; - } - - /** - * @param distributionSet - * the distributionSet to set - */ public void setDistributionSet(final DistributionSet distributionSet) { this.distributionSet = distributionSet; } - /** - * @return the value - */ - public String getValue() { - return value; - } - - /** - * @param value - * the value to set - */ - public void setValue(final String value) { - this.value = value; - } - - /** - * @return the distributionSet - */ public DistributionSet getDistributionSet() { return distributionSet; } + @Override + public int hashCode() { + final int prime = 31; + int result = super.hashCode(); + result = prime * result + ((distributionSet == null) ? 0 : distributionSet.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (!super.equals(obj)) { + return false; + } + final DistributionSetMetadata other = (DistributionSetMetadata) obj; + if (distributionSet == null) { + if (other.distributionSet != null) { + return false; + } + } else if (!distributionSet.equals(other.distributionSet)) { + return false; + } + return true; + } } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetTag.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetTag.java index 63a858a7d..137fde5b9 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetTag.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetTag.java @@ -21,16 +21,11 @@ import javax.persistence.UniqueConstraint; * A {@link DistributionSetTag} is used to describe DistributionSet attributes * and use them also for filtering the DistributionSet list. * - * - * - * - * - * */ @Entity @Table(name = "sp_distributionset_tag", indexes = { @Index(name = "sp_idx_distribution_set_tag_prim", columnList = "tenant,id") }, uniqueConstraints = @UniqueConstraint(columnNames = { - "name", "tenant" }, name = "uk_ds_tag") ) + "name", "tenant" }, name = "uk_ds_tag")) public class DistributionSetTag extends Tag { private static final long serialVersionUID = 1L; @@ -69,11 +64,6 @@ public class DistributionSetTag extends Tag { return assignedToDistributionSet; } - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ @Override public int hashCode() { final int prime = 31; @@ -82,16 +72,8 @@ public class DistributionSetTag extends Tag { return result; } - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ @Override public boolean equals(final Object obj) { // NOSONAR - as this is generated - if (this == obj) { - return true; - } if (!super.equals(obj)) { return false; } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetTagAssigmentResult.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetTagAssignmentResult.java similarity index 57% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetTagAssigmentResult.java rename to hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetTagAssignmentResult.java index d7ed57305..f1f3b1519 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetTagAssigmentResult.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetTagAssignmentResult.java @@ -11,14 +11,11 @@ package org.eclipse.hawkbit.repository.model; import java.util.List; /** - * Result object for {@link DistributionSetTag} assigments. + * Result object for {@link DistributionSetTag} assignments. * */ -public class DistributionSetTagAssigmentResult extends AssignmentResult { +public class DistributionSetTagAssignmentResult extends AssignmentResult { - private final int unassigned; - private final List assignedDs; - private final List unassignedDs; private final DistributionSetTag distributionSetTag; /** @@ -37,42 +34,16 @@ public class DistributionSetTagAssigmentResult extends AssignmentResult { * @param distributionSetTag * the assigned or unassigned tag */ - public DistributionSetTagAssigmentResult(final int alreadyAssigned, final int assigned, final int unassigned, + public DistributionSetTagAssignmentResult(final int alreadyAssigned, final int assigned, final int unassigned, final List assignedDs, final List unassignedDs, final DistributionSetTag distributionSetTag) { - super(assigned, alreadyAssigned); - this.unassigned = unassigned; - this.assignedDs = assignedDs; - this.unassignedDs = unassignedDs; + super(assigned, alreadyAssigned,unassigned, assignedDs, unassignedDs); this.distributionSetTag = distributionSetTag; } - /** - * @return the unassigned - */ - public int getUnassigned() { - return unassigned; - } - - /** - * @return the distributionSetTag - */ public DistributionSetTag getDistributionSetTag() { return distributionSetTag; } - /** - * @return the assignedDs - */ - public List getAssignedDs() { - return assignedDs; - } - - /** - * @return the unassignedDs - */ - public List getUnassignedDs() { - return unassignedDs; - } } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetType.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetType.java index e1c7e61ea..61d2fc58c 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetType.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetType.java @@ -27,9 +27,6 @@ import javax.persistence.UniqueConstraint; * A distribution set type defines which software module types can or have to be * {@link DistributionSet}. * - * - * - * */ @Entity @Table(name = "sp_distribution_set_type", indexes = { @@ -38,10 +35,6 @@ import javax.persistence.UniqueConstraint; @UniqueConstraint(columnNames = { "name", "tenant" }, name = "uk_dst_name"), @UniqueConstraint(columnNames = { "type_key", "tenant" }, name = "uk_dst_key") }) public class DistributionSetType extends NamedEntity { - - /** - * - */ private static final long serialVersionUID = 1L; @OneToMany(targetEntity = DistributionSetTypeElement.class, cascade = { @@ -59,7 +52,7 @@ public class DistributionSetType extends NamedEntity { private boolean deleted = false; public DistributionSetType() { - // default public constructor + // default public constructor for JPA } /** @@ -91,7 +84,7 @@ public class DistributionSetType extends NamedEntity { public DistributionSetType(final String key, final String name, final String description, final String color) { super(name, description); this.key = key; - this.colour = color; + colour = color; } /** @@ -256,17 +249,10 @@ public class DistributionSetType extends NamedEntity { return this; } - /** - * @return the key - */ public String getKey() { return key; } - /** - * @param key - * the key to set - */ public void setKey(final String key) { this.key = key; } @@ -282,19 +268,10 @@ public class DistributionSetType extends NamedEntity { .containsAll(getMandatoryModuleTypes()); } - /** - * - * @return the DistributionSet type color - */ public String getColour() { return colour; } - /** - * - * @param colour - * the col - */ public void setColour(final String colour) { this.colour = colour; } @@ -303,11 +280,6 @@ public class DistributionSetType extends NamedEntity { return elements; } - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ @Override public String toString() { return "DistributionSetType [key=" + key + ", isDeleted()=" + isDeleted() + ", getId()=" + getId() + "]"; diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetTypeElement.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetTypeElement.java index 0d892f6da..8414a6f1a 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetTypeElement.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetTypeElement.java @@ -25,17 +25,10 @@ import javax.persistence.Table; * Relation element between a {@link DistributionSetType} and its * {@link SoftwareModuleType} elements. * - * - * - * */ @Entity @Table(name = "sp_ds_type_element") public class DistributionSetTypeElement implements Serializable { - - /** - * - */ private static final long serialVersionUID = 1L; @EmbeddedId @@ -46,18 +39,16 @@ public class DistributionSetTypeElement implements Serializable { @MapsId("dsType") @ManyToOne(optional = false, fetch = FetchType.LAZY) - @JoinColumn(name = "distribution_set_type", foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_ds_type_element_dstype") ) + @JoinColumn(name = "distribution_set_type", foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_ds_type_element_dstype")) private DistributionSetType dsType; @MapsId("smType") @ManyToOne(optional = false, fetch = FetchType.LAZY) - @JoinColumn(name = "software_module_type", foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_ds_type_element_smtype") ) + @JoinColumn(name = "software_module_type", foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_ds_type_element_smtype")) private SoftwareModuleType smType; - /** - * Default constructor. - */ public DistributionSetTypeElement() { + // Default constructor for JPA } /** @@ -74,38 +65,30 @@ public class DistributionSetTypeElement implements Serializable { public DistributionSetTypeElement(final DistributionSetType dsType, final SoftwareModuleType smType, final boolean mandatory) { super(); - this.key = new DistributionSetTypeElementCompositeKey(dsType, smType); + key = new DistributionSetTypeElementCompositeKey(dsType, smType); this.dsType = dsType; this.smType = smType; this.mandatory = mandatory; } - /** - * @return the mandatory - */ public boolean isMandatory() { return mandatory; } - /** - * @return the dsType - */ public DistributionSetType getDsType() { return dsType; } - /** - * @return the smType - */ public SoftwareModuleType getSmType() { return smType; } - /** - * @return the key - */ public DistributionSetTypeElementCompositeKey getKey() { return key; } + @Override + public String toString() { + return "DistributionSetTypeElement [mandatory=" + mandatory + ", dsType=" + dsType + ", smType=" + smType + "]"; + } } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetTypeElementCompositeKey.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetTypeElementCompositeKey.java index c819d4e52..2ee1aba0d 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetTypeElementCompositeKey.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DistributionSetTypeElementCompositeKey.java @@ -15,17 +15,9 @@ import javax.persistence.Embeddable; /** * Composite key for {@link DistributionSetTypeElement}. - * - * - * - * */ @Embeddable public class DistributionSetTypeElementCompositeKey implements Serializable { - - /** - * - */ private static final long serialVersionUID = 1L; @Column(name = "distribution_set_type", nullable = false) @@ -54,34 +46,19 @@ public class DistributionSetTypeElementCompositeKey implements Serializable { this.smType = smType.getId(); } - /** - * @return the dsType - */ public Long getDsType() { return dsType; } - /** - * @param dsType - * the dsType to set - */ public void setDsType(final Long dsType) { this.dsType = dsType; } - /** - * @return the smType - */ public Long getSmType() { return smType; } - /** - * @param smType - * the smType to set - */ public void setSmType(final Long smType) { this.smType = smType; } - } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DsMetadataCompositeKey.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DsMetadataCompositeKey.java index f26a66ab9..adc37d65a 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DsMetadataCompositeKey.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/DsMetadataCompositeKey.java @@ -13,24 +13,17 @@ import java.io.Serializable; /** * The DistributionSet Metadata composite key which contains the meta data key * and the ID of the DistributionSet itself. - * - * * */ public final class DsMetadataCompositeKey implements Serializable { - /** - * - */ private static final long serialVersionUID = 1L; private String key; private Long distributionSet; - /** - * - */ public DsMetadataCompositeKey() { + // Default constructor for JPA. } /** @@ -44,55 +37,31 @@ public final class DsMetadataCompositeKey implements Serializable { this.key = key; } - /** - * @return the key - */ public String getKey() { return key; } - /** - * @param key - * the key to set - */ public void setKey(final String key) { this.key = key; } - /** - * @return the distributionSet - */ public Long getDistributionSet() { return distributionSet; } - /** - * @param distributionSet - * the distributionSet to set - */ public void setDistributionSet(final Long distributionSet) { this.distributionSet = distributionSet; } - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ @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()); + result = prime * result + (distributionSet == null ? 0 : distributionSet.hashCode()); + result = prime * result + (key == null ? 0 : key.hashCode()); return result; } - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ @Override public boolean equals(final Object obj) { // NOSONAR - as this is generated // code diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/ExternalArtifact.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/ExternalArtifact.java index 35e0c4e99..898c685a5 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/ExternalArtifact.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/ExternalArtifact.java @@ -22,12 +22,9 @@ import javax.persistence.Table; import javax.validation.constraints.NotNull; /** - * External artifact representation with all the necessray informattion to + * External artifact representation with all the necessary information to * generate an artifact {@link URL} at runtime. * - * - * - * */ @Table(name = "sp_external_artifact", indexes = { @Index(name = "sp_idx_external_artifact_prim", columnList = "id,tenant") }) @@ -36,7 +33,7 @@ public class ExternalArtifact extends Artifact { private static final long serialVersionUID = 1L; @ManyToOne - @JoinColumn(name = "provider", nullable = false, updatable = false, foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_art_to_ext_provider") ) + @JoinColumn(name = "provider", nullable = false, updatable = false, foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_art_to_ext_provider")) private ExternalArtifactProvider externalArtifactProvider; @Column(name = "url_suffix", length = 512) @@ -44,7 +41,7 @@ public class ExternalArtifact extends Artifact { // CascadeType.PERSIST as we register ourself at the BSM @ManyToOne(optional = false, cascade = { CascadeType.PERSIST }) - @JoinColumn(name = "software_module", nullable = false, updatable = false, foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_external_assigned_sm") ) + @JoinColumn(name = "software_module", nullable = false, updatable = false, foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_external_assigned_sm")) private SoftwareModule softwareModule; /** @@ -84,18 +81,11 @@ public class ExternalArtifact extends Artifact { return softwareModule; } - /** - * @param softwareModule - * the softwareModule to set - */ public final void setSoftwareModule(final SoftwareModule softwareModule) { this.softwareModule = softwareModule; this.softwareModule.addArtifact(this); } - /** - * @return the externalArtifactProvider - */ public ExternalArtifactProvider getExternalArtifactProvider() { return externalArtifactProvider; } @@ -104,17 +94,10 @@ public class ExternalArtifact extends Artifact { return new StringBuilder().append(externalArtifactProvider.getBasePath()).append(urlSuffix).toString(); } - /** - * @return the urlSuffix - */ public String getUrlSuffix() { return urlSuffix; } - /** - * @param externalArtifactProvider - * the externalArtifactProvider to set - */ public void setExternalArtifactProvider(final ExternalArtifactProvider externalArtifactProvider) { this.externalArtifactProvider = externalArtifactProvider; } @@ -127,11 +110,6 @@ public class ExternalArtifact extends Artifact { this.urlSuffix = urlSuffix; } - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ @Override public int hashCode() { // NOSONAR - as this is generated final int prime = 31; @@ -140,16 +118,8 @@ public class ExternalArtifact extends Artifact { return result; } - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ @Override public boolean equals(final Object obj) { // NOSONAR - as this is generated - if (this == obj) { - return true; - } if (!super.equals(obj)) { return false; } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/ExternalArtifactProvider.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/ExternalArtifactProvider.java index 56d92c8e1..9fa8714ac 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/ExternalArtifactProvider.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/ExternalArtifactProvider.java @@ -15,11 +15,8 @@ import javax.persistence.Table; /** * External repositories for artifact storage. The SP server provides URLs for - * the targets to download rom these external ressources but does not access - * thenm itself. - * - * - * + * the targets to download from these external resources but does not access + * them itself. * */ @Table(name = "sp_external_provider", indexes = { @@ -60,67 +57,20 @@ public class ExternalArtifactProvider extends NamedEntity { basePath = ""; } - /** - * @return the basePath - */ public String getBasePath() { return basePath; } - /** - * @return the defaultSuffix - */ public String getDefaultSuffix() { return defaultSuffix; } - /** - * @param basePath - * the basePath to set - */ public void setBasePath(final String basePath) { this.basePath = basePath; } - /** - * @param defaultSuffix - * the defaultSuffix to set - */ public void setDefaultSuffix(final String defaultSuffix) { this.defaultSuffix = defaultSuffix; } - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { // NOSONAR - as this is generated - final int prime = 31; - int result = super.hashCode(); - result = prime * result + this.getClass().getName().hashCode(); - return result; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(final Object obj) { // NOSONAR - as this is generated - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (!(obj instanceof ExternalArtifactProvider)) { - return false; - } - - return true; - } - } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/LocalArtifact.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/LocalArtifact.java index baa4ee1f0..8afcdc168 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/LocalArtifact.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/LocalArtifact.java @@ -46,7 +46,7 @@ public class LocalArtifact extends Artifact { private String filename; @ManyToOne(optional = false, cascade = { CascadeType.PERSIST }) - @JoinColumn(name = "software_module", nullable = false, updatable = false, foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_assigned_sm") ) + @JoinColumn(name = "software_module", nullable = false, updatable = false, foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_assigned_sm")) private SoftwareModule softwareModule; /** @@ -73,11 +73,6 @@ public class LocalArtifact extends Artifact { this.filename = filename; } - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ @Override public int hashCode() { // NOSONAR - as this is generated final int prime = 31; @@ -86,16 +81,8 @@ public class LocalArtifact extends Artifact { return result; } - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ @Override public boolean equals(final Object obj) { // NOSONAR - as this is generated - if (this == obj) { - return true; - } if (!super.equals(obj)) { return false; } @@ -106,33 +93,20 @@ public class LocalArtifact extends Artifact { return true; } - /** - * @return the softwareModule - */ @Override public SoftwareModule getSoftwareModule() { return softwareModule; } - /** - * @param softwareModule - * the softwareModule to set - */ public final void setSoftwareModule(final SoftwareModule softwareModule) { this.softwareModule = softwareModule; this.softwareModule.addArtifact(this); } - /** - * @return the gridFsFileName - */ public String getGridFsFileName() { return gridFsFileName; } - /** - * @return the filename - */ public String getFilename() { return filename; } 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..c41a0e8c9 --- /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 (!(this.getClass().isInstance(obj))) { + 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/NamedEntity.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/NamedEntity.java index 0cebd0362..e14d88161 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/NamedEntity.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/NamedEntity.java @@ -12,17 +12,11 @@ import javax.persistence.Column; import javax.persistence.MappedSuperclass; /** - * {@link BaseEntity} extension for all entities that are named in addition to - * their technical ID. - * - * - * - * - * - * + * {@link TenantAwareBaseEntity} extension for all entities that are named in + * addition to their technical ID. */ @MappedSuperclass -public abstract class NamedEntity extends BaseEntity { +public abstract class NamedEntity extends TenantAwareBaseEntity { private static final long serialVersionUID = 1L; @Column(name = "name", nullable = false, length = 64) @@ -40,7 +34,7 @@ public abstract class NamedEntity extends BaseEntity { /** * Parameterized constructor. - * + * * @param name * of the {@link NamedEntity} * @param description @@ -66,5 +60,4 @@ public abstract class NamedEntity extends BaseEntity { public void setName(final String name) { this.name = name; } - } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/NamedVersionedEntity.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/NamedVersionedEntity.java index 77819ed46..fa56da197 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/NamedVersionedEntity.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/NamedVersionedEntity.java @@ -14,11 +14,6 @@ import javax.persistence.MappedSuperclass; /** * Extension for {@link NamedEntity} that are versioned. * - * - * - * - * - * */ @MappedSuperclass public abstract class NamedVersionedEntity extends NamedEntity { @@ -29,7 +24,7 @@ public abstract class NamedVersionedEntity extends NamedEntity { /** * parameterized constructor. - * + * * @param name * of the entity * @param version @@ -52,5 +47,4 @@ public abstract class NamedVersionedEntity extends NamedEntity { public void setVersion(final String version) { this.version = version; } - } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/Rollout.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/Rollout.java index 83e541ed5..a7f9b10cb 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/Rollout.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/Rollout.java @@ -36,20 +36,20 @@ import org.eclipse.hawkbit.repository.model.Action.ActionType; @Entity @Table(name = "sp_rollout", indexes = { @Index(name = "sp_idx_rollout_01", columnList = "tenant,name") }, uniqueConstraints = @UniqueConstraint(columnNames = { - "name", "tenant" }, name = "uk_rollout") ) + "name", "tenant" }, name = "uk_rollout")) public class Rollout extends NamedEntity { private static final long serialVersionUID = 1L; @OneToMany(targetEntity = RolloutGroup.class) - @JoinColumn(name = "rollout", insertable = false, updatable = false, foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_rollout_rolloutgroup") ) + @JoinColumn(name = "rollout", insertable = false, updatable = false, foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_rollout_rolloutgroup")) private List rolloutGroups; @Column(name = "target_filter", length = 1024, nullable = false) private String targetFilterQuery; @ManyToOne(fetch = FetchType.LAZY) - @JoinColumn(name = "distribution_set", foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_rolltout_ds") ) + @JoinColumn(name = "distribution_set", foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_rolltout_ds")) private DistributionSet distributionSet; @Column(name = "status") @@ -79,159 +79,86 @@ public class Rollout extends NamedEntity { @Transient private transient TotalTargetCountStatus totalTargetCountStatus; - /** - * @return the distributionSet - */ public DistributionSet getDistributionSet() { return distributionSet; } - /** - * @param distributionSet - * the distributionSet to set - */ public void setDistributionSet(final DistributionSet distributionSet) { this.distributionSet = distributionSet; } - /** - * @return the rolloutGroups - */ public List getRolloutGroups() { return rolloutGroups; } - /** - * @param rolloutGroups - * the rolloutGroups to set - */ public void setRolloutGroups(final List rolloutGroups) { this.rolloutGroups = rolloutGroups; } - /** - * @return the targetFilterQuery - */ public String getTargetFilterQuery() { return targetFilterQuery; } - /** - * @param targetFilterQuery - * the targetFilterQuery to set - */ public void setTargetFilterQuery(final String targetFilterQuery) { this.targetFilterQuery = targetFilterQuery; } - /** - * @return the status - */ public RolloutStatus getStatus() { return status; } - /** - * @param status - * the status to set - */ public void setStatus(final RolloutStatus status) { this.status = status; } - /** - * @return the lastCheck - */ public long getLastCheck() { return lastCheck; } - /** - * @param lastCheck - * the lastCheck to set - */ public void setLastCheck(final long lastCheck) { this.lastCheck = lastCheck; } - /** - * @return the actionType - */ public ActionType getActionType() { return actionType; } - /** - * @param actionType - * the actionType to set - */ public void setActionType(final ActionType actionType) { this.actionType = actionType; } - /** - * @return the forcedTime - */ public long getForcedTime() { return forcedTime; } - /** - * @param forcedTime - * the forcedTime to set - */ public void setForcedTime(final long forcedTime) { this.forcedTime = forcedTime; } - /** - * @return the totalTargets - */ public long getTotalTargets() { return totalTargets; } - /** - * @param totalTargets - * the totalTargets to set - */ public void setTotalTargets(final long totalTargets) { this.totalTargets = totalTargets; } - /** - * @return the rolloutGroupsTotal - */ public int getRolloutGroupsTotal() { return rolloutGroupsTotal; } - /** - * @param rolloutGroupsTotal - * the rolloutGroupsTotal to set - */ public void setRolloutGroupsTotal(final int rolloutGroupsTotal) { this.rolloutGroupsTotal = rolloutGroupsTotal; } - /** - * @return the rolloutGroupsCreated - */ public int getRolloutGroupsCreated() { return rolloutGroupsCreated; } - /** - * @param rolloutGroupsCreated - * the rolloutGroupsCreated to set - */ public void setRolloutGroupsCreated(final int rolloutGroupsCreated) { this.rolloutGroupsCreated = rolloutGroupsCreated; } - /** - * @return the totalTargetCountStatus - */ public TotalTargetCountStatus getTotalTargetCountStatus() { if (totalTargetCountStatus == null) { totalTargetCountStatus = new TotalTargetCountStatus(totalTargets); @@ -239,10 +166,6 @@ public class Rollout extends NamedEntity { return totalTargetCountStatus; } - /** - * @param totalTargetCountStatus - * the totalTargetCountStatus to set - */ public void setTotalTargetCountStatus(final TotalTargetCountStatus totalTargetCountStatus) { this.totalTargetCountStatus = totalTargetCountStatus; } @@ -256,7 +179,7 @@ public class Rollout extends NamedEntity { /** * - * @author Michael Hirsch + * State machine for rollout. * */ public enum RolloutStatus { diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/RolloutGroup.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/RolloutGroup.java index dcb95b254..5aa30126c 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/RolloutGroup.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/RolloutGroup.java @@ -34,13 +34,13 @@ import javax.persistence.UniqueConstraint; @Entity @Table(name = "sp_rolloutgroup", indexes = { @Index(name = "sp_idx_rolloutgroup_01", columnList = "tenant,name") }, uniqueConstraints = @UniqueConstraint(columnNames = { - "name", "rollout", "tenant" }, name = "uk_rolloutgroup") ) + "name", "rollout", "tenant" }, name = "uk_rolloutgroup")) public class RolloutGroup extends NamedEntity { private static final long serialVersionUID = 1L; @ManyToOne(fetch = FetchType.LAZY) - @JoinColumn(name = "rollout", foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_rolloutgroup_rollout") ) + @JoinColumn(name = "rollout", foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_rolloutgroup_rollout")) private Rollout rollout; @Column(name = "status") @@ -210,8 +210,7 @@ public class RolloutGroup extends NamedEntity { } /** - * - * @author Michael Hirsch + * Rollout goup state machine. * */ public enum RolloutGroupStatus { @@ -477,5 +476,4 @@ public class RolloutGroup extends NamedEntity { return this; } } - } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/RolloutTargetGroup.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/RolloutTargetGroup.java index f1d4fe718..7a46b15b1 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/RolloutTargetGroup.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/RolloutTargetGroup.java @@ -24,13 +24,18 @@ import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; +import org.eclipse.persistence.annotations.ExistenceChecking; +import org.eclipse.persistence.annotations.ExistenceType; + /** - * @author Michael Hirsch - * + * Entity with JPA annotation to store the information which {@link Target} is + * in a specific {@link RolloutGroup}. + * */ @IdClass(RolloutTargetGroupId.class) @Entity @Table(name = "sp_rollouttargetgroup") +@ExistenceChecking(ExistenceType.ASSUME_NON_EXISTENCE) public class RolloutTargetGroup implements Serializable { private static final long serialVersionUID = 1L; diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/RolloutTargetGroupId.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/RolloutTargetGroupId.java index 41850424b..88226142a 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/RolloutTargetGroupId.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/RolloutTargetGroupId.java @@ -12,14 +12,9 @@ import java.io.Serializable; /** * Combined unique key of the table {@link RolloutTargetGroup}. - * - * @author Michael Hirsch * */ public class RolloutTargetGroupId implements Serializable { - /** - * - */ private static final long serialVersionUID = 1L; private Long rolloutGroup; diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/SoftwareModule.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/SoftwareModule.java index 49e73f749..327bff3db 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/SoftwareModule.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/SoftwareModule.java @@ -33,17 +33,12 @@ import org.eclipse.persistence.annotations.CascadeOnDelete; /** * Base Software Module that is supported by OS level provisioning mechanism on - * the edge controller, e.g. OS, JVM, AgentHub - * - * - * - * - * + * the edge controller, e.g. OS, JVM, AgentHub. * */ @Entity @Table(name = "sp_base_software_module", uniqueConstraints = @UniqueConstraint(columnNames = { "module_type", "name", - "version", "tenant" }, name = "uk_base_sw_mod") , indexes = { + "version", "tenant" }, name = "uk_base_sw_mod"), indexes = { @Index(name = "sp_idx_base_sw_module_01", columnList = "tenant,deleted,name,version"), @Index(name = "sp_idx_base_sw_module_02", columnList = "tenant,deleted,module_type"), @Index(name = "sp_idx_base_sw_module_prim", columnList = "tenant,id") }) @@ -52,7 +47,7 @@ public class SoftwareModule extends NamedVersionedEntity { private static final long serialVersionUID = 1L; @ManyToOne - @JoinColumn(name = "module_type", nullable = false, foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_module_type") ) + @JoinColumn(name = "module_type", nullable = false, foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_module_type")) private SoftwareModuleType type; @ManyToMany(mappedBy = "modules", targetEntity = DistributionSet.class, fetch = FetchType.LAZY) @@ -213,17 +208,10 @@ public class SoftwareModule extends NamedVersionedEntity { return type; } - /** - * @return the deleted - */ public boolean isDeleted() { return deleted; } - /** - * @param deleted - * the deleted to set - */ public void setDeleted(final boolean deleted) { this.deleted = deleted; } @@ -233,55 +221,16 @@ public class SoftwareModule extends NamedVersionedEntity { } /** - * @return the metadata + * @return immutable list of meta data elements. */ public List getMetadata() { - return metadata; + return Collections.unmodifiableList(metadata); } - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ @Override public String toString() { - return "SoftwareModule [type=" + type + ", deleted=" + deleted + ", getVersion()=" + getVersion() - + ", getOptLockRevision()=" + getOptLockRevision() + ", getId()=" + getId() + ", getType()=" - + getType().getName() + "]"; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { // NOSONAR - as this is generated - final int prime = 31; - int result = super.hashCode(); - result = prime * result + this.getClass().getName().hashCode(); - return result; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(final Object obj) { // NOSONAR - as this is generated - if (this == obj) { - return true; - } - if (!super.equals(obj)) { - return false; - } - if (!(obj instanceof SoftwareModule)) { - return false; - } - - return true; + return "SoftwareModule [deleted=" + deleted + ", name=" + getName() + ", version=" + getVersion() + + ", revision=" + getOptLockRevision() + ", Id=" + getId() + ", type=" + getType().getName() + "]"; } /** diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/SoftwareModuleIdName.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/SoftwareModuleIdName.java index 8658de3c8..c59d42c5f 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/SoftwareModuleIdName.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/SoftwareModuleIdName.java @@ -13,8 +13,6 @@ import java.io.Serializable; /** * To hold software module name and Id. * - * - * */ public class SoftwareModuleIdName implements Serializable { @@ -35,25 +33,14 @@ public class SoftwareModuleIdName implements Serializable { this.name = name; } - /** - * @return the id - */ public Long getId() { return id; } - /** - * @return the name - */ public String getName() { return name; } - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ @Override public int hashCode() {// NOSONAR - as this is generated final int prime = 31; @@ -62,11 +49,6 @@ public class SoftwareModuleIdName implements Serializable { return result; } - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ @Override public boolean equals(final Object obj) {// NOSONAR - as this is generated if (this == 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 dfc1ecfa7..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 @@ -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; @@ -24,101 +21,60 @@ import javax.persistence.Table; /** * Metadata for {@link SoftwareModule}. * - * - * - * */ @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")) private SoftwareModule softwareModule; public SoftwareModuleMetadata() { - + // default public constructor for JPA } - /** - * Standard constructor. - * - * @param key - * of the metadata element - * @param softwareModule - * @param value - * of the metadata element - */ public SoftwareModuleMetadata(final String key, final SoftwareModule softwareModule, final String value) { - this.key = key; + super(key, value); this.softwareModule = softwareModule; - this.value = value; } - /** - * @return the id - */ public SwMetadataCompositeKey getId() { - return new SwMetadataCompositeKey(softwareModule, key); + return new SwMetadataCompositeKey(softwareModule, getKey()); } - /** - * @return the value - */ - public String getValue() { - return value; - } - - /** - * @param value - * the value to set - */ - public void setValue(final String value) { - this.value = value; - } - - /** - * @return the softwareModule - */ public SoftwareModule getSoftwareModule() { return softwareModule; } - /** - * @param softwareModule - * the softwareModule to set - */ public void setSoftwareModule(final SoftwareModule softwareModule) { this.softwareModule = softwareModule; } - /** - * @return the key - */ - public String getKey() { - return key; + @Override + public int hashCode() { + final int prime = 31; + int result = super.hashCode(); + result = prime * result + ((softwareModule == null) ? 0 : softwareModule.hashCode()); + return result; } - /** - * @param key - * the key to set - */ - public void setKey(final String key) { - this.key = key; + @Override + public boolean equals(final Object obj) { + if (!super.equals(obj)) { + return false; + } + final SoftwareModuleMetadata other = (SoftwareModuleMetadata) obj; + if (softwareModule == null) { + if (other.softwareModule != null) { + return false; + } + } else if (!softwareModule.equals(other.softwareModule)) { + return false; + } + return true; } - } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/SoftwareModuleType.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/SoftwareModuleType.java index 49427b9ea..f31b74ff6 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/SoftwareModuleType.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/SoftwareModuleType.java @@ -17,9 +17,6 @@ import javax.persistence.UniqueConstraint; /** * Type of a software modules. * - * - * - * */ @Entity @Table(name = "sp_software_module_type", indexes = { @@ -28,9 +25,6 @@ import javax.persistence.UniqueConstraint; @UniqueConstraint(columnNames = { "type_key", "tenant" }, name = "uk_smt_type_key"), @UniqueConstraint(columnNames = { "name", "tenant" }, name = "uk_smt_name") }) public class SoftwareModuleType extends NamedEntity { - /** - * - */ private static final long serialVersionUID = 1L; @Column(name = "type_key", nullable = false, length = 64) @@ -92,48 +86,26 @@ public class SoftwareModuleType extends NamedEntity { super(); } - /** - * @return the key - */ public String getKey() { return key; } - /** - * @return the max - */ public int getMaxAssignments() { return maxAssignments; } - /** - * @return the deleted - */ public boolean isDeleted() { return deleted; } - /** - * @param deleted - * the deleted to set - */ public void setDeleted(final boolean deleted) { this.deleted = deleted; } - /** - * - * @return the software type color - */ public String getColour() { return colour; } - /** - * - * @param colour - * the col - */ public void setColour(final String colour) { this.colour = colour; } @@ -142,5 +114,4 @@ public class SoftwareModuleType extends NamedEntity { public String toString() { return "SoftwareModuleType [key=" + key + ", getName()=" + getName() + ", getId()=" + getId() + "]"; } - } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/SwMetadataCompositeKey.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/SwMetadataCompositeKey.java index 2518e4b1b..90b3779a1 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/SwMetadataCompositeKey.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/SwMetadataCompositeKey.java @@ -11,16 +11,10 @@ package org.eclipse.hawkbit.repository.model; import java.io.Serializable; /** - * The Software Module Metadata composite key which contains the meta data key + * The Software Module meta data composite key which contains the meta data key * and the ID of the software module itself. - * - * - * */ public final class SwMetadataCompositeKey implements Serializable { - /** - * - */ private static final long serialVersionUID = 1L; private String key; @@ -28,9 +22,10 @@ public final class SwMetadataCompositeKey implements Serializable { private Long softwareModule; /** - * - */ + * Default constructor for JPA. + */ public SwMetadataCompositeKey() { + // Default constructor for JPA. } /** @@ -74,25 +69,15 @@ public final class SwMetadataCompositeKey implements Serializable { this.softwareModule = softwareModule; } - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ @Override public int hashCode() { final int prime = 31; int result = 1; - result = prime * result + ((key == null) ? 0 : key.hashCode()); - result = prime * result + ((softwareModule == null) ? 0 : softwareModule.hashCode()); + result = prime * result + (key == null ? 0 : key.hashCode()); + result = prime * result + (softwareModule == null ? 0 : softwareModule.hashCode()); return result; } - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ @Override public boolean equals(final Object obj) { // NOSONAR - as this is generated // code diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/Tag.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/Tag.java index c03a02f3e..23489ea12 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/Tag.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/Tag.java @@ -14,14 +14,9 @@ import javax.persistence.MappedSuperclass; import org.springframework.hateoas.Identifiable; /** - * A Tag can be used as describing and organisational meta information for any + * A Tag can be used as describing and organizational meta information for any * kind of entity. * - * - * - * - * - * */ @MappedSuperclass public abstract class Tag extends NamedEntity implements Identifiable { @@ -57,14 +52,8 @@ public abstract class Tag extends NamedEntity implements Identifiable { this.colour = colour; } - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ @Override public String toString() { return "Tag [getOptLockRevision()=" + getOptLockRevision() + ", getId()=" + getId() + "]"; } - } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/Target.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/Target.java index 07a97ebcf..8947ea6c3 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/Target.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/Target.java @@ -38,6 +38,7 @@ import javax.validation.constraints.Size; import org.eclipse.hawkbit.im.authentication.SpPermission; import org.eclipse.hawkbit.repository.model.helper.SecurityChecker; import org.eclipse.hawkbit.repository.model.helper.SecurityTokenGeneratorHolder; +import org.eclipse.hawkbit.repository.model.helper.SystemSecurityContextHolder; import org.eclipse.persistence.annotations.CascadeOnDelete; import org.springframework.data.domain.Persistable; @@ -56,11 +57,6 @@ import org.springframework.data.domain.Persistable; * {@link TargetStatus#REGISTERED}, i.e. a target {@link DistributionSet} . *

* - * - * - * - * - * */ @Entity @Table(name = "sp_target", indexes = { @@ -117,7 +113,7 @@ public class Target extends NamedEntity implements Persistable { /** * Constructor. - * + * * @param controllerId * controller ID of the {@link Target} */ @@ -136,28 +132,6 @@ public class Target extends NamedEntity implements Persistable { securityToken = null; } - @Override - public boolean equals(final Object obj) {// NOSONAR - as this is generated - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final Target other = (Target) obj; - if (controllerId == null) { - if (other.controllerId != null) { - return false; - } - } else if (!controllerId.equals(other.controllerId)) { - return false; - } - return true; - } - public DistributionSet getAssignedDistributionSet() { return assignedDistributionSet; } @@ -170,37 +144,18 @@ public class Target extends NamedEntity implements Persistable { return tags; } - @Override - public int hashCode() { // NOSONAR - as this is generated - final int prime = 31; - int result = 1; - result = prime * result + (controllerId == null ? 0 : controllerId.hashCode()); - return result; - } - public void setAssignedDistributionSet(final DistributionSet assignedDistributionSet) { this.assignedDistributionSet = assignedDistributionSet; } - /** - * @param controllerId - * the controllerId to set - */ public void setControllerId(final String controllerId) { this.controllerId = controllerId; } - /** - * @param tags - * the tags to set - */ public void setTags(final Set tags) { this.tags = tags; } - /** - * @return the actions - */ public List getActions() { return actions; } @@ -209,11 +164,6 @@ public class Target extends NamedEntity implements Persistable { return new TargetIdName(getId(), getControllerId(), getName()); } - /* - * (non-Javadoc) - * - * @see org.springframework.data.domain.Persistable#isNew() - */ @Override @Transient public boolean isNew() { @@ -244,10 +194,14 @@ public class Target extends NamedEntity implements Persistable { } /** - * @return the securityToken + * @return the securityToken if the current security context contains the + * necessary permission {@link SpPermission#READ_TARGET_SEC_TOKEN} + * or the current context is executed as system code, otherwise + * {@code null}. */ public String getSecurityToken() { - if (SecurityChecker.hasPermission(SpPermission.READ_TARGET_SEC_TOKEN)) { + if (SystemSecurityContextHolder.getInstance().getSystemSecurityContext().isCurrentThreadSystemCode() + || SecurityChecker.hasPermission(SpPermission.READ_TARGET_SEC_TOKEN)) { return securityToken; } return null; @@ -261,11 +215,6 @@ public class Target extends NamedEntity implements Persistable { this.securityToken = securityToken; } - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ @Override public String toString() { return "Target [controllerId=" + controllerId + ", getId()=" + getId() + "]"; diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TargetFilterQuery.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TargetFilterQuery.java index 8d76b7ae5..021b9ca7f 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TargetFilterQuery.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TargetFilterQuery.java @@ -15,18 +15,14 @@ import javax.persistence.Table; import javax.persistence.UniqueConstraint; /** - * + * Stored target filter. * */ @Entity @Table(name = "sp_target_filter_query", indexes = { @Index(name = "sp_idx_target_filter_query_01", columnList = "tenant,name") }, uniqueConstraints = @UniqueConstraint(columnNames = { - "name", "tenant" }, name = "uk_tenant_custom_filter_name") ) -public class TargetFilterQuery extends BaseEntity { - /** - * - * - */ + "name", "tenant" }, name = "uk_tenant_custom_filter_name")) +public class TargetFilterQuery extends TenantAwareBaseEntity { private static final long serialVersionUID = 7493966984413479089L; @Column(name = "name", length = 64) @@ -36,8 +32,7 @@ public class TargetFilterQuery extends BaseEntity { private String query; public TargetFilterQuery() { - name = null; - query = null; + // Default constructor for JPA. } public TargetFilterQuery(final String name, final String query) { @@ -45,63 +40,19 @@ public class TargetFilterQuery extends BaseEntity { this.query = query; } - /** - * @return the name - */ public String getName() { return name; } - /** - * @param name - * the name to set - */ public void setName(final String name) { this.name = name; } - /** - * @return the query - */ public String getQuery() { return query; } - /** - * @param query - * the query to set - */ public void setQuery(final String query) { this.query = query; } - - @Override - public boolean equals(final Object obj) {// NOSONAR - as this is generated - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final TargetFilterQuery other = (TargetFilterQuery) obj; - if (name == null) { - if (other.name != null) { - return false; - } - } else if (!name.equals(other.name)) { - return false; - } - return true; - } - - @Override - public int hashCode() { // NOSONAR - as this is generated - final int prime = 31; - int result = 1; - result = prime * result + (name == null ? 0 : name.hashCode()); - return result; - } } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TargetIdName.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TargetIdName.java index f7a63b775..26a74e9bb 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TargetIdName.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TargetIdName.java @@ -13,19 +13,12 @@ import java.io.Serializable; /** * ID class of the {@link Target} which contains the * {@link Target#getControllerId()} and the {@link Target#getName()} in one - * object. Often it's necessary to remeber the IDs of the {@link Target} and the - * resolve for e.g. the UI the name of the target, this is very costly + * object. Often it's necessary to remember the IDs of the {@link Target} and + * the resolve for e.g. the UI the name of the target, this is very costly * operation, so it's much better if the ID and the name of the {@link Target} * is already in memory available. - * - * - * - * */ public class TargetIdName implements Serializable { - /** - * - */ private static final long serialVersionUID = 1L; private final long targetId; @@ -46,61 +39,34 @@ public class TargetIdName implements Serializable { this.name = name; } - /** - * @return the controller id - */ public String getControllerId() { return controllerId; } - /** - * @return the name - */ public String getName() { return name; } - /** - * @param id - * the id to set - */ public void setControllerId(final String id) { - this.controllerId = id; + controllerId = id; } - /** - * @param name - * the name to set - */ public void setName(final String name) { this.name = name; } - /** - * @return the targetId - */ public long getTargetId() { return targetId; } - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ @Override public int hashCode() { final int prime = 31; int result = 1; - result = prime * result + (int) (targetId ^ (targetId >>> 32)); + result = prime * result + (int) (targetId ^ targetId >>> 32); return result; } - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ @Override public boolean equals(final Object obj) { if (this == obj) { @@ -119,11 +85,6 @@ public class TargetIdName implements Serializable { return true; } - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ @Override public String toString() { // only return the ID because it's used in vaadin for setting the item diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TargetInfo.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TargetInfo.java index 09d9fed28..00a501540 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TargetInfo.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TargetInfo.java @@ -38,7 +38,8 @@ import javax.persistence.OneToOne; import javax.persistence.Table; import javax.persistence.Transient; -import org.eclipse.hawkbit.repository.TenantConfigurationManagement; +import org.eclipse.hawkbit.repository.model.helper.SystemSecurityContextHolder; +import org.eclipse.hawkbit.repository.model.helper.TenantConfigurationManagementHolder; import org.eclipse.hawkbit.tenancy.configuration.DurationHelper; import org.eclipse.hawkbit.tenancy.configuration.TenantConfigurationKey; import org.eclipse.persistence.annotations.CascadeOnDelete; @@ -54,19 +55,11 @@ import org.springframework.data.domain.Persistable; * modifying the {@link Target} itself when a controller reports it's * {@link #lastTargetQuery} for example. * - * - * - * */ @Table(name = "sp_target_info", indexes = { @Index(name = "sp_idx_target_info_02", columnList = "target_id,update_status") }) @Entity -// @DynamicUpdate public class TargetInfo implements Persistable, Serializable { - - /** - * - */ private static final long serialVersionUID = 1L; private static final Logger LOG = LoggerFactory.getLogger(TargetInfo.class); @@ -81,9 +74,6 @@ public class TargetInfo implements Persistable, Serializable { @OneToOne(cascade = { CascadeType.MERGE, CascadeType.REMOVE }, fetch = FetchType.LAZY, targetEntity = Target.class) @JoinColumn(name = "target_id", nullable = false, updatable = false, foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_targ_stat_targ")) @MapsId - // use deprecated annotation until HHH-8862 is fixed - // @SuppressWarnings( "deprecation" ) - // @org.hibernate.annotations.ForeignKey( name = "fk_targ_stat_targ" ) private Target target; @Column(name = "address", length = 512) @@ -111,9 +101,7 @@ public class TargetInfo implements Persistable, Serializable { @MapKeyColumn(name = "attribute_key", nullable = false, length = 32) @CollectionTable(name = "sp_target_attributes", joinColumns = { @JoinColumn(name = "target_id") }, foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_targ_attrib_target")) - // use deprecated annotation until HHH-8862 is fixed - // @org.hibernate.annotations.ForeignKey( name = "fk_targ_attrib_target" ) private final Map controllerAttributes = Collections.synchronizedMap(new HashMap()); // set default request controller attributes to true, because we want to @@ -124,7 +112,7 @@ public class TargetInfo implements Persistable, Serializable { /** * Constructor for {@link TargetStatus}. - * + * * @param target * related to this status. */ @@ -138,21 +126,11 @@ public class TargetInfo implements Persistable, Serializable { targetId = null; } - /* - * (non-Javadoc) - * - * @see org.springframework.data.domain.Persistable#getId() - */ @Override public Long getId() { return targetId; } - /* - * (non-Javadoc) - * - * @see org.springframework.data.domain.Persistable#isNew() - */ @Override @Transient public boolean isNew() { @@ -198,114 +176,62 @@ public class TargetInfo implements Persistable, Serializable { this.address = address; } - /** - * @return the targetId - */ public Long getTargetId() { return targetId; } - /** - * @param targetId - * the targetId to set - */ public void setTargetId(final Long targetId) { this.targetId = targetId; } - /** - * @return the target - */ public Target getTarget() { return target; } - /** - * @param target - * the target to set - */ public void setTarget(final Target target) { this.target = target; } - /** - * @return the lastTargetQuery - */ public Long getLastTargetQuery() { return lastTargetQuery; } - /** - * @param lastTargetQuery - * the lastTargetQuery to set - */ public void setLastTargetQuery(final Long lastTargetQuery) { this.lastTargetQuery = lastTargetQuery; } - /** - * @param requestControllerAttributes - * the requestControllerAttributes to set - */ public void setRequestControllerAttributes(final boolean requestControllerAttributes) { this.requestControllerAttributes = requestControllerAttributes; } - /** - * @return the controllerAttributes - */ public Map getControllerAttributes() { return controllerAttributes; } - /** - * @return the requestControllerAttributes - */ public boolean isRequestControllerAttributes() { return requestControllerAttributes; } - /** - * @return the installationDate - */ public Long getInstallationDate() { return installationDate; } - /** - * @param installationDate - * the installationDate to set - */ public void setInstallationDate(final Long installationDate) { this.installationDate = installationDate; } - /** - * @return the updateStatus - */ public TargetUpdateStatus getUpdateStatus() { return updateStatus; } - /** - * @param updateStatus - * the updateStatus to set - */ public void setUpdateStatus(final TargetUpdateStatus updateStatus) { this.updateStatus = updateStatus; } - /** - * @return the installedDistributionSet - */ public DistributionSet getInstalledDistributionSet() { return installedDistributionSet; } - /** - * @param installedDistributionSet - * the installedDistributionSet to set - */ public void setInstalledDistributionSet(final DistributionSet installedDistributionSet) { this.installedDistributionSet = installedDistributionSet; } @@ -320,26 +246,27 @@ public class TargetInfo implements Persistable, Serializable { if (lastTargetQuery == null) { return null; } - - final Duration pollTime = DurationHelper.formattedStringToDuration(TenantConfigurationManagement.getInstance() - .getConfigurationValue(TenantConfigurationKey.POLLING_TIME_INTERVAL, String.class).getValue()); - final Duration overdueTime = DurationHelper.formattedStringToDuration(TenantConfigurationManagement - .getInstance().getConfigurationValue(TenantConfigurationKey.POLLING_OVERDUE_TIME_INTERVAL, String.class) - .getValue()); - final LocalDateTime currentDate = LocalDateTime.now(); - final LocalDateTime lastPollDate = LocalDateTime.ofInstant(Instant.ofEpochMilli(lastTargetQuery), - ZoneId.systemDefault()); - final LocalDateTime nextPollDate = lastPollDate.plus(pollTime); - final LocalDateTime overdueDate = nextPollDate.plus(overdueTime); - return new PollStatus(lastPollDate, nextPollDate, overdueDate, currentDate); + return SystemSecurityContextHolder.getInstance().getSystemSecurityContext().runAsSystem(() -> { + final Duration pollTime = DurationHelper.formattedStringToDuration(TenantConfigurationManagementHolder + .getInstance().getTenantConfigurationManagement() + .getConfigurationValue(TenantConfigurationKey.POLLING_TIME_INTERVAL, String.class).getValue()); + final Duration overdueTime = DurationHelper.formattedStringToDuration( + TenantConfigurationManagementHolder.getInstance().getTenantConfigurationManagement() + .getConfigurationValue(TenantConfigurationKey.POLLING_OVERDUE_TIME_INTERVAL, String.class) + .getValue()); + final LocalDateTime currentDate = LocalDateTime.now(); + final LocalDateTime lastPollDate = LocalDateTime.ofInstant(Instant.ofEpochMilli(lastTargetQuery), + ZoneId.systemDefault()); + final LocalDateTime nextPollDate = lastPollDate.plus(pollTime); + final LocalDateTime overdueDate = nextPollDate.plus(overdueTime); + return new PollStatus(lastPollDate, nextPollDate, overdueDate, currentDate); + }); } /** * The poll time object which holds all the necessary information around the * target poll time, e.g. the last poll time, the next poll time and the * overdue poll time. - * - * * */ public static final class PollStatus { @@ -359,7 +286,7 @@ public class TargetInfo implements Persistable, Serializable { /** * calculates if the target poll time is overdue and the target has not * been polled in the configured poll time interval. - * + * * @return {@code true} if the current time is after the poll time * overdue date otherwise {@code false}. */ @@ -386,15 +313,48 @@ public class TargetInfo implements Persistable, Serializable { return currentDate; } - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ @Override public String toString() { return "PollTime [lastPollDate=" + lastPollDate + ", nextPollDate=" + nextPollDate + ", overdueDate=" + overdueDate + ", currentDate=" + currentDate + "]"; } } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((target == null) ? 0 : target.hashCode()); + result = prime * result + ((targetId == null) ? 0 : targetId.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (!(obj instanceof TargetInfo)) { + return false; + } + final TargetInfo other = (TargetInfo) obj; + if (target == null) { + if (other.target != null) { + return false; + } + } else if (!target.equals(other.target)) { + return false; + } + if (targetId == null) { + if (other.targetId != null) { + return false; + } + } else if (!targetId.equals(other.targetId)) { + return false; + } + return true; + } } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TargetTag.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TargetTag.java index 781bf9d16..5a5a310d0 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TargetTag.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TargetTag.java @@ -21,16 +21,11 @@ import javax.persistence.UniqueConstraint; * A {@link TargetTag} is used to describe Target attributes and use them also * for filtering the target list. * - * - * - * - * - * */ @Entity @Table(name = "sp_target_tag", indexes = { @Index(name = "sp_idx_target_tag_prim", columnList = "tenant,id") }, uniqueConstraints = @UniqueConstraint(columnNames = { - "name", "tenant" }, name = "uk_targ_tag") ) + "name", "tenant" }, name = "uk_targ_tag")) public class TargetTag extends Tag { private static final long serialVersionUID = 1L; @@ -65,18 +60,10 @@ public class TargetTag extends Tag { super(); } - /** - * @return the assignedToTargets - */ public List getAssignedToTargets() { return assignedToTargets; } - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ @Override public int hashCode() { final int prime = 31; @@ -85,16 +72,8 @@ public class TargetTag extends Tag { return result; } - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ @Override public boolean equals(final Object obj) { - if (this == obj) { - return true; - } if (!super.equals(obj)) { return false; } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TargetTagAssigmentResult.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TargetTagAssignmentResult.java similarity index 56% rename from hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TargetTagAssigmentResult.java rename to hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TargetTagAssignmentResult.java index b12b80d58..b454d0c18 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TargetTagAssigmentResult.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TargetTagAssignmentResult.java @@ -11,17 +11,11 @@ package org.eclipse.hawkbit.repository.model; import java.util.List; /** - * Result object for {@link TargetTag} assigments. - * - * - * + * Result object for {@link TargetTag} assignments. * */ -public class TargetTagAssigmentResult extends AssignmentResult { +public class TargetTagAssignmentResult extends AssignmentResult { - private final int unassigned; - private final List assignedTargets; - private final List unassignedTargets; private final TargetTag targetTag; /** @@ -40,36 +34,12 @@ public class TargetTagAssigmentResult extends AssignmentResult { * @param targetTag * the assigned or unassigned tag */ - public TargetTagAssigmentResult(final int alreadyAssigned, final int assigned, final int unassigned, + public TargetTagAssignmentResult(final int alreadyAssigned, final int assigned, final int unassigned, final List assignedTargets, final List unassignedTargets, final TargetTag targetTag) { - super(assigned, alreadyAssigned); - this.unassigned = unassigned; - this.assignedTargets = assignedTargets; - this.unassignedTargets = unassignedTargets; + super(assigned, alreadyAssigned, unassigned, assignedTargets, unassignedTargets); this.targetTag = targetTag; } - /** - * @return the unassigned - */ - public int getUnassigned() { - return unassigned; - } - - /** - * @return the assignedTargets - */ - public List getAssignedTargets() { - return assignedTargets; - } - - /** - * @return the unassignedTargets - */ - public List getUnassignedTargets() { - return unassignedTargets; - } - public TargetTag getTargetTag() { return targetTag; } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TargetUpdateStatus.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TargetUpdateStatus.java index cecbf8339..7721dabda 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TargetUpdateStatus.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TargetUpdateStatus.java @@ -13,11 +13,6 @@ package org.eclipse.hawkbit.repository.model; * status. A {@link Target} can have only one status. independent of the number * of {@link UpdateAction}s that have to be applied. * - * - * - * - * - * */ public enum TargetUpdateStatus { diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TargetWithActionStatus.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TargetWithActionStatus.java index a75141658..ec09da3d5 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TargetWithActionStatus.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TargetWithActionStatus.java @@ -30,32 +30,18 @@ public class TargetWithActionStatus { this.target = target; } - /** - * @return the target - */ public Target getTarget() { return target; } - /** - * @return the status - */ public Status getStatus() { return status; } - /** - * @param target - * the target to set - */ public void setTarget(final Target target) { this.target = target; } - /** - * @param status - * the status to set - */ public void setStatus(final Status status) { this.status = status; } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TenantAwareBaseEntity.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TenantAwareBaseEntity.java new file mode 100644 index 000000000..d03a4938a --- /dev/null +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TenantAwareBaseEntity.java @@ -0,0 +1,113 @@ +/** + * 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 javax.persistence.Column; +import javax.persistence.MappedSuperclass; +import javax.persistence.PrePersist; + +import org.eclipse.hawkbit.repository.exception.TenantNotExistException; +import org.eclipse.hawkbit.repository.model.helper.SystemManagementHolder; +import org.eclipse.hawkbit.repository.model.helper.TenantAwareHolder; +import org.eclipse.persistence.annotations.Multitenant; +import org.eclipse.persistence.annotations.MultitenantType; +import org.eclipse.persistence.annotations.TenantDiscriminatorColumn; + +/** + * Holder of the base attributes common to all tenant aware entities. + * + */ +@MappedSuperclass +@TenantDiscriminatorColumn(name = "tenant", length = 40) +@Multitenant(MultitenantType.SINGLE_TABLE) +public abstract class TenantAwareBaseEntity extends BaseEntity { + private static final long serialVersionUID = 1L; + + @Column(name = "tenant", nullable = false, insertable = false, updatable = false, length = 40) + private String tenant; + + /** + * Default constructor needed for JPA entities. + */ + public TenantAwareBaseEntity() { + // Default constructor needed for JPA entities. + } + + /** + * PrePersist listener method for all {@link TenantAwareBaseEntity} + * entities. + */ + @PrePersist + public void prePersist() { + // before persisting the entity check the current ID of the tenant by + // using the TenantAware + // service + final String currentTenant = SystemManagementHolder.getInstance().currentTenant(); + if (currentTenant == null) { + throw new TenantNotExistException("Tenant " + + TenantAwareHolder.getInstance().getTenantAware().getCurrentTenant() + + " does not exists, cannot create entity " + this.getClass() + " with id " + super.getId()); + } + setTenant(currentTenant.toUpperCase()); + } + + public String getTenant() { + return tenant; + } + + public void setTenant(final String tenant) { + this.tenant = tenant; + } + + @Override + public String toString() { + return "BaseEntity [id=" + super.getId() + "]"; + } + + /** + * Tenant aware entities extend the equals/hashcode strategy with the tenant + * name. That would allow for instance in a multi-schema based data + * separation setup to have the same primary key for different entities of + * different tenants. + * + * @see org.eclipse.hawkbit.repository.model.BaseEntity#hashCode() + */ + @Override + public int hashCode() { + final int prime = 31; + int result = super.hashCode(); + result = prime * result + (tenant == null ? 0 : tenant.hashCode()); + return result; + } + + /** + * Tenant aware entities extend the equals/hashcode strategy with the tenant + * name. That would allow for instance in a multi-schema based data + * separation setup to have the same primary key for different entities of + * different tenants. + * + * @see org.eclipse.hawkbit.repository.model.BaseEntity#equals(java.lang.Object) + */ + @Override + public boolean equals(final Object obj) { + if (!super.equals(obj)) { + return false; + } + final TenantAwareBaseEntity other = (TenantAwareBaseEntity) obj; + if (tenant == null) { + if (other.tenant != null) { + return false; + } + } else if (!tenant.equals(other.tenant)) { + return false; + } + return true; + } + +} diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TenantConfiguration.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TenantConfiguration.java index d571a2ea7..5a938563b 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TenantConfiguration.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TenantConfiguration.java @@ -19,18 +19,11 @@ import javax.persistence.UniqueConstraint; /** * A JPA entity which stores the tenant specific configuration. * - * - * - * */ @Entity @Table(name = "sp_tenant_configuration", uniqueConstraints = @UniqueConstraint(columnNames = { "conf_key", - "tenant" }, name = "uk_tenant_key") ) -public class TenantConfiguration extends BaseEntity implements Serializable { - - /** - * - */ + "tenant" }, name = "uk_tenant_key")) +public class TenantConfiguration extends TenantAwareBaseEntity implements Serializable { private static final long serialVersionUID = 1L; @Column(name = "conf_key", length = 128) @@ -44,7 +37,7 @@ public class TenantConfiguration extends BaseEntity implements Serializable { * JPA default constructor. */ public TenantConfiguration() { - + // JPA default constructor. } /** @@ -59,75 +52,20 @@ public class TenantConfiguration extends BaseEntity implements Serializable { } - /** - * @return the key - */ public String getKey() { return key; } - /** - * @param key - * the key to set - */ public void setKey(final String key) { this.key = key; } - /** - * @return the value - */ public String getValue() { return value; } - /** - * @param value - * the value to set - */ public void setValue(final String value) { this.value = value; } - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((key == null) ? 0 : key.hashCode()); - return result; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(final Object obj) { // NOSONAR - as this is generated - // code - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final TenantConfiguration other = (TenantConfiguration) obj; - 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/TenantConfigurationValue.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TenantConfigurationValue.java index d8483e12f..37e00e247 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TenantConfigurationValue.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TenantConfigurationValue.java @@ -89,7 +89,7 @@ public class TenantConfigurationValue { */ public static TenantConfigurationValueBuilder builder() { - return new TenantConfigurationValueBuilder(); + return new TenantConfigurationValueBuilder<>(); } /** diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TenantMetaData.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TenantMetaData.java index e86bfe8a4..a9572c21c 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TenantMetaData.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/TenantMetaData.java @@ -8,76 +8,45 @@ */ package org.eclipse.hawkbit.repository.model; -import java.io.Serializable; - -import javax.persistence.Access; -import javax.persistence.AccessType; import javax.persistence.Column; import javax.persistence.ConstraintMode; import javax.persistence.Entity; +import javax.persistence.EntityManager; import javax.persistence.FetchType; import javax.persistence.ForeignKey; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; import javax.persistence.Index; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.persistence.UniqueConstraint; -import javax.persistence.Version; - -import org.springframework.data.annotation.CreatedBy; -import org.springframework.data.annotation.CreatedDate; -import org.springframework.data.annotation.LastModifiedBy; -import org.springframework.data.annotation.LastModifiedDate; /** - * Tenant metadata that is configured globally for the entire tenant. This - * entity is - * - * + * Tenant entity with meta data that is configured globally for the entire + * tenant. This entity is not tenant aware to allow the system to access it + * through the {@link EntityManager} even before the actual tenant exists. * + * Entities owned by the tenant are based on {@link TenantAwareBaseEntity}. * */ -@Access(AccessType.FIELD) @Table(name = "sp_tenant", indexes = { @Index(name = "sp_idx_tenant_prim", columnList = "tenant,id") }, uniqueConstraints = { @UniqueConstraint(columnNames = { "tenant" }, name = "uk_tenantmd_tenant") }) @Entity -public class TenantMetaData implements Serializable { - - /** - * - */ +public class TenantMetaData extends BaseEntity { private static final long serialVersionUID = 1L; - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "id") - private Long id; - @Column(name = "tenant", nullable = false, length = 40) private String tenant; - private String createdBy; - private String lastModifiedBy; - private Long createdAt; - private Long lastModifiedAt; - - @Version - @Column(name = "optlock_revision") - private long optLockRevision; - @OneToOne(fetch = FetchType.LAZY) - @JoinColumn(name = "default_ds_type", nullable = false, foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_tenant_md_default_ds_type") ) - // use deprecated annotation until HHH-8862 is fixed - @SuppressWarnings("deprecation") - // @org.hibernate.annotations.ForeignKey( name = - // "fk_tenant_md_default_ds_type" ) + @JoinColumn(name = "default_ds_type", nullable = false, foreignKey = @ForeignKey(value = ConstraintMode.CONSTRAINT, name = "fk_tenant_md_default_ds_type")) private DistributionSetType defaultDsType; + /** + * Default constructor needed for JPA entities. + */ public TenantMetaData() { + // Default constructor needed for JPA entities. } /** @@ -93,167 +62,39 @@ public class TenantMetaData implements Serializable { this.tenant = tenant; } - /** - * @return the defaultDsType - */ public DistributionSetType getDefaultDsType() { return defaultDsType; } - /** - * Set the DistributionSet for a tenant. - * - * @param defaultDsType - * the new default DistributionSet - */ public void setDefaultDsType(final DistributionSetType defaultDsType) { this.defaultDsType = defaultDsType; } - /** - * @return the id - */ - public Long getId() { - return id; - } - - /** - * @param id - * the id to set - */ - public void setId(final Long id) { - this.id = id; - } - - @Access(AccessType.PROPERTY) - @Column(name = "created_at", insertable = true, updatable = false) - public Long getCreatedAt() { - return createdAt; - } - - @Access(AccessType.PROPERTY) - @Column(name = "created_by", insertable = true, updatable = false, length = 40) - public String getCreatedBy() { - return createdBy; - } - - @Access(AccessType.PROPERTY) - @Column(name = "last_modified_at", insertable = false, updatable = true) - public Long getLastModifiedAt() { - return lastModifiedAt; - } - - @Access(AccessType.PROPERTY) - @Column(name = "last_modified_by", insertable = false, updatable = true, length = 40) - public String getLastModifiedBy() { - return lastModifiedBy; - } - - /** - * @param createdBy - * the createdBy to set - */ - @CreatedBy - public void setCreatedBy(final String createdBy) { - this.createdBy = createdBy; - } - - /** - * @param lastModifiedBy - * the lastModifiedBy to set - */ - @LastModifiedBy - public void setLastModifiedBy(final String lastModifiedBy) { - this.lastModifiedBy = lastModifiedBy; - } - - /** - * @param createdAt - * the createdAt to set - */ - @CreatedDate - public void setCreatedAt(final Long createdAt) { - this.createdAt = createdAt; - } - - /** - * @param lastModifiedAt - * the lastModifiedAt to set - */ - @LastModifiedDate - public void setLastModifiedAt(final Long lastModifiedAt) { - this.lastModifiedAt = lastModifiedAt; - } - - /** - * @return the optLockRevision - */ - public long getOptLockRevision() { - return optLockRevision; - } - - /** - * @param optLockRevision - * the optLockRevision to set - */ - public void setOptLockRevision(final long optLockRevision) { - this.optLockRevision = optLockRevision; - } - - /** - * @return the tenant - */ public String getTenant() { return tenant; } - /** - * @param tenant - * the tenant to set - */ public void setTenant(final String tenant) { this.tenant = tenant; } - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ @Override public int hashCode() { final int prime = 31; - int result = 1; - result = prime * result + ((id == null) ? 0 : id.hashCode()); + int result = super.hashCode(); + result = prime * result + this.getClass().getName().hashCode(); return result; } - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ @Override - public boolean equals(final Object obj) { // NOSONAR - as this is generated - // code - if (this == obj) { - return true; - } - if (obj == null) { + public boolean equals(final Object obj) { + if (!super.equals(obj)) { return false; } - if (getClass() != obj.getClass()) { - return false; - } - final TenantMetaData other = (TenantMetaData) obj; - if (id == null) { - if (other.id != null) { - return false; - } - } else if (!id.equals(other.id)) { + if (!(obj instanceof TenantMetaData)) { return false; } + return true; } - } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/helper/SystemSecurityContextHolder.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/helper/SystemSecurityContextHolder.java new file mode 100644 index 000000000..7d005e9bc --- /dev/null +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/helper/SystemSecurityContextHolder.java @@ -0,0 +1,41 @@ +/** + * 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.helper; + +import org.eclipse.hawkbit.security.SystemSecurityContext; +import org.springframework.beans.factory.annotation.Autowired; + +/** + * A singleton bean which holds {@link SystemSecurityContext} service and makes + * it accessible to beans which are not managed by spring, e.g. JPA entities. + */ +public final class SystemSecurityContextHolder { + + private static final SystemSecurityContextHolder INSTANCE = new SystemSecurityContextHolder(); + + @Autowired + private SystemSecurityContext systemSecurityContext; + + private SystemSecurityContextHolder() { + } + + /** + * @return the singleton {@link SystemSecurityContextHolder} instance + */ + public static SystemSecurityContextHolder getInstance() { + return INSTANCE; + } + + /** + * @return the {@link SystemSecurityContext} service + */ + public SystemSecurityContext getSystemSecurityContext() { + return systemSecurityContext; + } +} diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/helper/TenantConfigurationManagementHolder.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/helper/TenantConfigurationManagementHolder.java new file mode 100644 index 000000000..700511db6 --- /dev/null +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/model/helper/TenantConfigurationManagementHolder.java @@ -0,0 +1,44 @@ +/** + * Copyright (c) 2015 Bosch Software Innovations GmbH and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + */ +package org.eclipse.hawkbit.repository.model.helper; + +import org.eclipse.hawkbit.repository.TenantConfigurationManagement; +import org.springframework.beans.factory.annotation.Autowired; + +/** + * A singleton bean which holds {@link TenantConfigurationManagement} service + * and makes it accessible to beans which are not managed by spring, e.g. JPA + * entities. + */ +public final class TenantConfigurationManagementHolder { + + private static final TenantConfigurationManagementHolder INSTANCE = new TenantConfigurationManagementHolder(); + + @Autowired + private TenantConfigurationManagement tenantConfiguration; + + private TenantConfigurationManagementHolder() { + } + + /** + * @return the singleton {@link TenantConfigurationManagementHolder} + * instance + */ + public static TenantConfigurationManagementHolder getInstance() { + return INSTANCE; + } + + /** + * @return the {@link TenantConfigurationManagement} service + */ + public TenantConfigurationManagement getTenantConfigurationManagement() { + return tenantConfiguration; + } + +} diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/rsql/RSQLUtility.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/rsql/RSQLUtility.java index 03f213fef..4edc46623 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/rsql/RSQLUtility.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/rsql/RSQLUtility.java @@ -66,10 +66,6 @@ import cz.jirutka.rsql.parser.ast.RSQLVisitor; *
  • name==targetId1,description==plugAndPlay,updateStatus==UNKNOWN
  • *
  • name==targetId1 or description==plugAndPlay or updateStatus==UNKNOWN
  • * - * - * - * - * */ public final class RSQLUtility { @@ -139,14 +135,6 @@ public final class RSQLUtility { this.enumType = enumType; } - /* - * (non-Javadoc) - * - * @see - * org.springframework.data.jpa.domain.Specification#toPredicate(javax. - * persistence.criteria .Root, javax.persistence.criteria.CriteriaQuery, - * javax.persistence.criteria.CriteriaBuilder) - */ @Override public Predicate toPredicate(final Root root, final CriteriaQuery query, final CriteriaBuilder cb) { @@ -287,6 +275,9 @@ public final class RSQLUtility { } @Override + // Exception squid:S2095 - see + // https://jira.sonarsource.com/browse/SONARJAVA-1478 + @SuppressWarnings({ "squid:S2095" }) public List visit(final ComparisonNode node, final String param) { A fieldName = null; try { @@ -312,6 +303,9 @@ public final class RSQLUtility { return mapToPredicate(node, fieldPath, node.getArguments(), transformedValue, fieldName); } + // Exception squid:S2095 - see + // https://jira.sonarsource.com/browse/SONARJAVA-1478 + @SuppressWarnings({ "squid:S2095" }) private List getExpectedFieldList() { final List expectedFieldList = Arrays.stream(enumType.getEnumConstants()) .filter(enumField -> enumField.getSubEntityAttributes().isEmpty()).map(enumField -> { @@ -398,7 +392,9 @@ public final class RSQLUtility { } } - @SuppressWarnings({ "rawtypes", "unchecked" }) + // Exception squid:S2095 - see + // https://jira.sonarsource.com/browse/SONARJAVA-1478 + @SuppressWarnings({ "rawtypes", "unchecked", "squid:S2095" }) private Object transformEnumValue(final ComparisonNode node, final String value, final Class javaType) { final Class tmpEnumType = (Class) javaType; diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/specifications/ActionSpecifications.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/specifications/ActionSpecifications.java new file mode 100644 index 000000000..62e7167f1 --- /dev/null +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/specifications/ActionSpecifications.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.repository.specifications; + +import javax.persistence.criteria.Join; +import javax.persistence.criteria.ListJoin; +import javax.persistence.criteria.SetJoin; + +import org.eclipse.hawkbit.repository.model.Action; +import org.eclipse.hawkbit.repository.model.Action_; +import org.eclipse.hawkbit.repository.model.DistributionSet; +import org.eclipse.hawkbit.repository.model.DistributionSet_; +import org.eclipse.hawkbit.repository.model.LocalArtifact; +import org.eclipse.hawkbit.repository.model.LocalArtifact_; +import org.eclipse.hawkbit.repository.model.SoftwareModule; +import org.eclipse.hawkbit.repository.model.SoftwareModule_; +import org.eclipse.hawkbit.repository.model.Target; +import org.springframework.data.jpa.domain.Specification; + +/** + * Utility class for {@link Action}s {@link Specification}s. The class provides + * Spring Data JPQL Specifications. + * + */ +public class ActionSpecifications { + + private ActionSpecifications() { + // utility class + } + + /** + * Specification which joins all necessary tables to retrieve the dependency + * between a target and a local file assignment through the assigen action + * of the target. All actions are included, not only active actions. + * + * @param target + * the target to verfiy if the given artifact is currently + * assigned or had been assigned + * @param localArtifact + * the local artifact to check wherever the target had ever been + * assigned + * @return a specification to use with spring JPA + */ + public static Specification hasTargetAssignedArtifact(final Target target, + final LocalArtifact localArtifact) { + return (actionRoot, query, criteriaBuilder) -> { + final Join dsJoin = actionRoot.join(Action_.distributionSet); + final SetJoin modulesJoin = dsJoin.join(DistributionSet_.modules); + final ListJoin artifactsJoin = modulesJoin.join(SoftwareModule_.artifacts); + return criteriaBuilder.and( + criteriaBuilder.equal(artifactsJoin.get(LocalArtifact_.filename), localArtifact.getFilename()), + criteriaBuilder.equal(actionRoot.get(Action_.target), target)); + }; + } +} diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/specifications/DistributionSetSpecification.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/specifications/DistributionSetSpecification.java index 4150229c6..b95f0b8e7 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/specifications/DistributionSetSpecification.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/specifications/DistributionSetSpecification.java @@ -11,13 +11,11 @@ package org.eclipse.hawkbit.repository.specifications; import java.util.Collection; import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Join; import javax.persistence.criteria.JoinType; import javax.persistence.criteria.ListJoin; import javax.persistence.criteria.Path; import javax.persistence.criteria.Predicate; -import javax.persistence.criteria.Root; import javax.persistence.criteria.SetJoin; import org.eclipse.hawkbit.repository.model.DistributionSet; @@ -33,9 +31,7 @@ import org.springframework.data.jpa.domain.Specification; /** * Specifications class for {@link DistributionSet}s. The class provides Spring - * Data JPQL Specifications - * - * + * Data JPQL Specifications. * */ public final class DistributionSetSpecification { @@ -53,16 +49,8 @@ public final class DistributionSetSpecification { * @return the {@link DistributionSet} {@link Specification} */ public static Specification isDeleted(final Boolean isDeleted) { - final Specification spec = new Specification() { - @Override - public Predicate toPredicate(final Root targetRoot, final CriteriaQuery query, - final CriteriaBuilder cb) { - final Predicate predicate = cb.equal(targetRoot. get(DistributionSet_.deleted), isDeleted); - return predicate; - } - }; + return (targetRoot, query, cb) -> cb.equal(targetRoot. get(DistributionSet_.deleted), isDeleted); - return spec; } /** @@ -75,16 +63,8 @@ public final class DistributionSetSpecification { * @return the {@link DistributionSet} {@link Specification} */ public static Specification isCompleted(final Boolean isCompleted) { - final Specification spec = new Specification() { - @Override - public Predicate toPredicate(final Root targetRoot, final CriteriaQuery query, - final CriteriaBuilder cb) { - final Predicate predicate = cb.equal(targetRoot. get(DistributionSet_.complete), isCompleted); - return predicate; - } - }; + return (targetRoot, query, cb) -> cb.equal(targetRoot. get(DistributionSet_.complete), isCompleted); - return spec; } /** @@ -96,21 +76,15 @@ public final class DistributionSetSpecification { * @return the {@link DistributionSet} {@link Specification} */ public static Specification byId(final Long distid) { - final Specification spec = new Specification() { - @Override - public Predicate toPredicate(final Root targetRoot, final CriteriaQuery query, - final CriteriaBuilder cb) { + return (targetRoot, query, cb) -> { + final Predicate predicate = cb.equal(targetRoot. get(DistributionSet_.id), distid); + targetRoot.fetch(DistributionSet_.modules, JoinType.LEFT); + targetRoot.fetch(DistributionSet_.tags, JoinType.LEFT); + targetRoot.fetch(DistributionSet_.type, JoinType.LEFT); + query.distinct(true); - final Predicate predicate = cb.equal(targetRoot. get(DistributionSet_.id), distid); - targetRoot.fetch(DistributionSet_.modules, JoinType.LEFT); - targetRoot.fetch(DistributionSet_.tags, JoinType.LEFT); - targetRoot.fetch(DistributionSet_.type, JoinType.LEFT); - query.distinct(true); - - return predicate; - } + return predicate; }; - return spec; } /** @@ -122,20 +96,14 @@ public final class DistributionSetSpecification { * @return the {@link DistributionSet} {@link Specification} */ public static Specification byIds(final Collection distids) { - final Specification spec = new Specification() { - @Override - public Predicate toPredicate(final Root targetRoot, final CriteriaQuery query, - final CriteriaBuilder cb) { - - final Predicate predicate = targetRoot. get(DistributionSet_.id).in(distids); - targetRoot.fetch(DistributionSet_.modules, JoinType.LEFT); - targetRoot.fetch(DistributionSet_.tags, JoinType.LEFT); - targetRoot.fetch(DistributionSet_.type, JoinType.LEFT); - query.distinct(true); - return predicate; - } + return (targetRoot, query, cb) -> { + final Predicate predicate = targetRoot. get(DistributionSet_.id).in(distids); + targetRoot.fetch(DistributionSet_.modules, JoinType.LEFT); + targetRoot.fetch(DistributionSet_.tags, JoinType.LEFT); + targetRoot.fetch(DistributionSet_.type, JoinType.LEFT); + query.distinct(true); + return predicate; }; - return spec; } /** @@ -147,21 +115,10 @@ public final class DistributionSetSpecification { * @return the {@link DistributionSet} {@link Specification} */ public static Specification likeNameOrDescriptionOrVersion(final String subString) { - final Specification spec = new Specification() { - @Override - public Predicate toPredicate(final Root targetRoot, final CriteriaQuery query, - final CriteriaBuilder cb) { - final Predicate predicate = cb - .or(cb.like(cb.lower(targetRoot. get(DistributionSet_.name)), subString.toLowerCase()), - cb.like(cb.lower(targetRoot. get(DistributionSet_.version)), - subString.toLowerCase()), - cb.like(cb.lower(targetRoot. get(DistributionSet_.description)), - subString.toLowerCase())); - return predicate; - } - }; - - return spec; + return (targetRoot, query, cb) -> cb.or( + cb.like(cb.lower(targetRoot. get(DistributionSet_.name)), subString.toLowerCase()), + cb.like(cb.lower(targetRoot. get(DistributionSet_.version)), subString.toLowerCase()), + cb.like(cb.lower(targetRoot. get(DistributionSet_.description)), subString.toLowerCase())); } /** @@ -176,19 +133,13 @@ public final class DistributionSetSpecification { */ public static Specification hasTags(final Collection tagNames, final Boolean selectDSWithNoTag) { - final Specification spec = new Specification() { - @Override - public Predicate toPredicate(final Root targetRoot, final CriteriaQuery query, - final CriteriaBuilder cb) { - final SetJoin tags = targetRoot.join(DistributionSet_.tags, - JoinType.LEFT); - final Predicate predicate = getPredicate(tags, tagNames, selectDSWithNoTag, cb); - query.distinct(true); - return predicate; - } + return (targetRoot, query, cb) -> { + final SetJoin tags = targetRoot.join(DistributionSet_.tags, + JoinType.LEFT); + final Predicate predicate = getPredicate(tags, tagNames, selectDSWithNoTag, cb); + query.distinct(true); + return predicate; }; - - return spec; } private static Predicate getPredicate(final SetJoin tags, @@ -218,20 +169,10 @@ public final class DistributionSetSpecification { */ public static Specification equalsNameAndVersionIgnoreCase(final String name, final String version) { - final Specification spec = new Specification() { - @Override - public Predicate toPredicate(final Root targetRoot, final CriteriaQuery query, - final CriteriaBuilder cb) { - final Predicate predicate = cb.and( - // formatter:off - cb.equal(cb.lower(targetRoot. get(DistributionSet_.name)), name.toLowerCase()), - cb.equal(cb.lower(targetRoot. get(DistributionSet_.version)), version.toLowerCase())); - // formatter:on - return predicate; - } - }; + return (targetRoot, query, cb) -> cb.and( + cb.equal(cb.lower(targetRoot. get(DistributionSet_.name)), name.toLowerCase()), + cb.equal(cb.lower(targetRoot. get(DistributionSet_.version)), version.toLowerCase())); - return spec; } /** @@ -243,16 +184,8 @@ public final class DistributionSetSpecification { * @return the {@link DistributionSet} {@link Specification} */ public static Specification byType(final DistributionSetType type) { - final Specification spec = new Specification() { - @Override - public Predicate toPredicate(final Root targetRoot, final CriteriaQuery query, - final CriteriaBuilder cb) { - final Predicate predicate = cb.equal(targetRoot. get(DistributionSet_.type), type); - return predicate; - } - }; + return (targetRoot, query, cb) -> cb.equal(targetRoot. get(DistributionSet_.type), type); - return spec; } /** @@ -263,18 +196,12 @@ public final class DistributionSetSpecification { * installed to the given targetId */ public static Specification installedTarget(final String installedTargetId) { - final Specification spec = new Specification() { - @Override - public Predicate toPredicate(final Root dsRoot, final CriteriaQuery query, - final CriteriaBuilder cb) { - final ListJoin installedTargetJoin = dsRoot - .join(DistributionSet_.installedAtTargets, JoinType.INNER); - final Join targetJoin = installedTargetJoin.join(TargetInfo_.target); - return cb.equal(targetJoin.get(Target_.controllerId), installedTargetId); - } + return (dsRoot, query, cb) -> { + final ListJoin installedTargetJoin = dsRoot + .join(DistributionSet_.installedAtTargets, JoinType.INNER); + final Join targetJoin = installedTargetJoin.join(TargetInfo_.target); + return cb.equal(targetJoin.get(Target_.controllerId), installedTargetId); }; - - return spec; } /** @@ -285,16 +212,11 @@ public final class DistributionSetSpecification { * assigned to the given targetId */ public static Specification assignedTarget(final String assignedTargetId) { - final Specification spec = new Specification() { - @Override - public Predicate toPredicate(final Root dsRoot, final CriteriaQuery query, - final CriteriaBuilder cb) { - final ListJoin assignedTargetJoin = dsRoot - .join(DistributionSet_.assignedToTargets, JoinType.INNER); - return cb.equal(assignedTargetJoin.get(Target_.controllerId), assignedTargetId); - } + return (dsRoot, query, cb) -> { + final ListJoin assignedTargetJoin = dsRoot.join(DistributionSet_.assignedToTargets, + JoinType.INNER); + return cb.equal(assignedTargetJoin.get(Target_.controllerId), assignedTargetId); }; - return spec; } } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/specifications/DistributionSetTypeSpecification.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/specifications/DistributionSetTypeSpecification.java index 1caa5ef59..13776deb0 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/specifications/DistributionSetTypeSpecification.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/specifications/DistributionSetTypeSpecification.java @@ -8,22 +8,14 @@ */ package org.eclipse.hawkbit.repository.specifications; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Predicate; -import javax.persistence.criteria.Root; - import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.DistributionSetType; import org.eclipse.hawkbit.repository.model.DistributionSetType_; import org.springframework.data.jpa.domain.Specification; /** - * - * - * - * - * + * Specifications class for {@link DistributionSetType}s. The class provides + * Spring Data JPQL Specifications. */ public final class DistributionSetTypeSpecification { private DistributionSetTypeSpecification() { @@ -40,16 +32,7 @@ public final class DistributionSetTypeSpecification { * @return the {@link DistributionSetType} {@link Specification} */ public static Specification isDeleted(final Boolean isDeleted) { - final Specification spec = new Specification() { - @Override - public Predicate toPredicate(final Root targetRoot, final CriteriaQuery query, - final CriteriaBuilder cb) { - final Predicate predicate = cb.equal(targetRoot. get(DistributionSetType_.deleted), isDeleted); - return predicate; - } - }; - - return spec; + return (targetRoot, query, cb) -> cb.equal(targetRoot. get(DistributionSetType_.deleted), isDeleted); } /** @@ -62,16 +45,7 @@ public final class DistributionSetTypeSpecification { * @return the {@link DistributionSet} {@link Specification} */ public static Specification byId(final Long distid) { - final Specification spec = new Specification() { - @Override - public Predicate toPredicate(final Root targetRoot, final CriteriaQuery query, - final CriteriaBuilder cb) { - - final Predicate predicate = cb.equal(targetRoot. get(DistributionSetType_.id), distid); - return predicate; - } - }; - return spec; + return (targetRoot, query, cb) -> cb.equal(targetRoot. get(DistributionSetType_.id), distid); } /** @@ -84,16 +58,7 @@ public final class DistributionSetTypeSpecification { * @return the {@link DistributionSet} {@link Specification} */ public static Specification byName(final String name) { - final Specification spec = new Specification() { - @Override - public Predicate toPredicate(final Root targetRoot, final CriteriaQuery query, - final CriteriaBuilder cb) { - - final Predicate predicate = cb.equal(targetRoot. get(DistributionSetType_.name), name); - return predicate; - } - }; - return spec; + return (targetRoot, query, cb) -> cb.equal(targetRoot. get(DistributionSetType_.name), name); } /** @@ -106,16 +71,7 @@ public final class DistributionSetTypeSpecification { * @return the {@link DistributionSet} {@link Specification} */ public static Specification byKey(final String key) { - final Specification spec = new Specification() { - @Override - public Predicate toPredicate(final Root targetRoot, final CriteriaQuery query, - final CriteriaBuilder cb) { - - final Predicate predicate = cb.equal(targetRoot. get(DistributionSetType_.key), key); - return predicate; - } - }; - return spec; + return (targetRoot, query, cb) -> cb.equal(targetRoot. get(DistributionSetType_.key), key); } } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/specifications/SoftwareModuleSpecification.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/specifications/SoftwareModuleSpecification.java index 2311f59f6..680f97778 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/specifications/SoftwareModuleSpecification.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/specifications/SoftwareModuleSpecification.java @@ -8,10 +8,7 @@ */ package org.eclipse.hawkbit.repository.specifications; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; -import javax.persistence.criteria.Root; import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.repository.model.SoftwareModuleType; @@ -22,8 +19,6 @@ import org.springframework.data.jpa.domain.Specification; * Specifications class for {@link SoftwareModule}s. The class provides Spring * Data JPQL Specifications * - * - * */ public final class SoftwareModuleSpecification { private SoftwareModuleSpecification() { @@ -39,38 +34,21 @@ public final class SoftwareModuleSpecification { * @return the {@link SoftwareModule} {@link Specification} */ public static Specification byId(final Long moduleId) { - final Specification spec = new Specification() { - @Override - public Predicate toPredicate(final Root targetRoot, final CriteriaQuery query, - final CriteriaBuilder cb) { - - final Predicate predicate = cb.equal(targetRoot. get(SoftwareModule_.id), moduleId); - targetRoot.fetch(SoftwareModule_.type); - return predicate; - } + return (targetRoot, query, cb) -> { + final Predicate predicate = cb.equal(targetRoot. get(SoftwareModule_.id), moduleId); + targetRoot.fetch(SoftwareModule_.type); + return predicate; }; - return spec; } /** - * {@link Specification} for retrieving {@link SoftwareModule}s by its - * DELETED attribute. + * {@link Specification} for retrieving {@link SoftwareModule}s where its + * DELETED attribute is false. * - * @param isDeleted - * TRUE/FALSE are compared to the attribute DELETED. If NULL the - * attribute is ignored * @return the {@link SoftwareModule} {@link Specification} */ public static Specification isDeletedFalse() { - final Specification spec = new Specification() { - @Override - public Predicate toPredicate(final Root swRoot, final CriteriaQuery query, - final CriteriaBuilder cb) { - final Predicate predicate = cb.equal(swRoot. get(SoftwareModule_.deleted), Boolean.FALSE); - return predicate; - } - }; - return spec; + return (swRoot, query, cb) -> cb.equal(swRoot. get(SoftwareModule_.deleted), Boolean.FALSE); } /** @@ -82,18 +60,9 @@ public final class SoftwareModuleSpecification { * @return the {@link SoftwareModule} {@link Specification} */ public static Specification likeNameOrVersion(final String subString) { - final Specification spec = new Specification() { - @Override - public Predicate toPredicate(final Root targetRoot, final CriteriaQuery query, - final CriteriaBuilder cb) { - final Predicate predicate = cb.or( - cb.like(cb.lower(targetRoot. get(SoftwareModule_.name)), subString.toLowerCase()), - cb.like(cb.lower(targetRoot. get(SoftwareModule_.version)), subString.toLowerCase())); - return predicate; - } - }; - - return spec; + return (targetRoot, query, cb) -> cb.or( + cb.like(cb.lower(targetRoot. get(SoftwareModule_.name)), subString.toLowerCase()), + cb.like(cb.lower(targetRoot. get(SoftwareModule_.version)), subString.toLowerCase())); } /** @@ -105,16 +74,7 @@ public final class SoftwareModuleSpecification { * @return the {@link SoftwareModule} {@link Specification} */ public static Specification equalType(final SoftwareModuleType type) { - final Specification spec = new Specification() { - @Override - public Predicate toPredicate(final Root targetRoot, final CriteriaQuery query, - final CriteriaBuilder cb) { - final Predicate predicate = cb.equal(targetRoot. get(SoftwareModule_.type), type); - return predicate; - } - }; - - return spec; + return (targetRoot, query, cb) -> cb.equal(targetRoot. get(SoftwareModule_.type), type); } } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/specifications/TargetFilterQuerySpecification.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/specifications/TargetFilterQuerySpecification.java index c92da7ed1..0b600c849 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/specifications/TargetFilterQuerySpecification.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/specifications/TargetFilterQuerySpecification.java @@ -8,17 +8,13 @@ */ package org.eclipse.hawkbit.repository.specifications; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Predicate; -import javax.persistence.criteria.Root; - import org.eclipse.hawkbit.repository.model.TargetFilterQuery; import org.eclipse.hawkbit.repository.model.TargetFilterQuery_; import org.springframework.data.jpa.domain.Specification; /** - * + * Specifications class for {@link TargetFilterQuery}s. The class provides + * Spring Data JPQL Specifications. * */ public class TargetFilterQuerySpecification { @@ -27,16 +23,9 @@ public class TargetFilterQuerySpecification { } public static Specification likeName(final String searchText) { - final Specification spec = new Specification() { - @Override - public Predicate toPredicate(final Root targetFilterQueryRoot, - final CriteriaQuery query, final CriteriaBuilder cb) { - final String searchTextToLower = searchText.toLowerCase(); - final Predicate predicate = cb.like(cb.lower(targetFilterQueryRoot.get(TargetFilterQuery_.name)), - searchTextToLower); - return predicate; - } + return (targetFilterQueryRoot, query, cb) -> { + final String searchTextToLower = searchText.toLowerCase(); + return cb.like(cb.lower(targetFilterQueryRoot.get(TargetFilterQuery_.name)), searchTextToLower); }; - return spec; } } diff --git a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/specifications/TargetSpecifications.java b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/specifications/TargetSpecifications.java index fb0e5740e..de894d3a3 100644 --- a/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/specifications/TargetSpecifications.java +++ b/hawkbit-repository/src/main/java/org/eclipse/hawkbit/repository/specifications/TargetSpecifications.java @@ -12,7 +12,6 @@ import java.util.Collection; import java.util.List; import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Join; import javax.persistence.criteria.JoinType; import javax.persistence.criteria.Path; @@ -36,8 +35,6 @@ import org.springframework.data.jpa.domain.Specification; * Specifications class for {@link Target}s. The class provides Spring Data JPQL * Specifications. * - * - * */ public final class TargetSpecifications { private TargetSpecifications() { @@ -54,18 +51,12 @@ public final class TargetSpecifications { * @return the {@link Target} {@link Specification} */ public static Specification byControllerIdWithStatusAndTagsInJoin(final Collection controllerIDs) { - final Specification spec = new Specification() { - @Override - public Predicate toPredicate(final Root targetRoot, final CriteriaQuery query, - final CriteriaBuilder cb) { - final Predicate predicate = targetRoot.get(Target_.controllerId).in(controllerIDs); - targetRoot.fetch(Target_.tags, JoinType.LEFT); - query.distinct(true); - return predicate; - } + return (targetRoot, query, cb) -> { + final Predicate predicate = targetRoot.get(Target_.controllerId).in(controllerIDs); + targetRoot.fetch(Target_.tags, JoinType.LEFT); + query.distinct(true); + return predicate; }; - - return spec; } /** @@ -79,18 +70,12 @@ public final class TargetSpecifications { */ public static Specification byControllerIdWithStatusAndAssignedInJoin( final Collection controllerIDs) { - final Specification spec = new Specification() { - @Override - public Predicate toPredicate(final Root targetRoot, final CriteriaQuery query, - final CriteriaBuilder cb) { + return (targetRoot, query, cb) -> { - final Predicate predicate = targetRoot.get(Target_.controllerId).in(controllerIDs); - targetRoot.fetch(Target_.assignedDistributionSet); - return predicate; - } + final Predicate predicate = targetRoot.get(Target_.controllerId).in(controllerIDs); + targetRoot.fetch(Target_.assignedDistributionSet); + return predicate; }; - - return spec; } /** @@ -106,24 +91,18 @@ public final class TargetSpecifications { */ public static Specification hasTargetUpdateStatus(final Collection updateStatus, final boolean fetch) { - final Specification spec = new Specification() { - @Override - public Predicate toPredicate(final Root targetRoot, final CriteriaQuery query, - final CriteriaBuilder cb) { - if (!query.getResultType().isAssignableFrom(Long.class)) { - if (fetch) { - targetRoot.fetch(Target_.targetInfo); - } else { - targetRoot.join(Target_.targetInfo); - } - return targetRoot.get(Target_.targetInfo).get(TargetInfo_.updateStatus).in(updateStatus); + return (targetRoot, query, cb) -> { + if (!query.getResultType().isAssignableFrom(Long.class)) { + if (fetch) { + targetRoot.fetch(Target_.targetInfo); + } else { + targetRoot.join(Target_.targetInfo); } - final Join targetInfoJoin = targetRoot.join(Target_.targetInfo); - return targetInfoJoin.get(TargetInfo_.updateStatus).in(updateStatus); + return targetRoot.get(Target_.targetInfo).get(TargetInfo_.updateStatus).in(updateStatus); } + final Join targetInfoJoin = targetRoot.join(Target_.targetInfo); + return targetInfoJoin.get(TargetInfo_.updateStatus).in(updateStatus); }; - - return spec; } /** @@ -135,18 +114,11 @@ public final class TargetSpecifications { * @return the {@link Target} {@link Specification} */ public static Specification likeNameOrDescriptionOrIp(final String searchText) { - final Specification spec = new Specification() { - @Override - public Predicate toPredicate(final Root targetRoot, final CriteriaQuery query, - final CriteriaBuilder cb) { - final String searchTextToLower = searchText.toLowerCase(); - final Predicate predicate = cb.or(cb.like(cb.lower(targetRoot.get(Target_.name)), searchTextToLower), - cb.like(cb.lower(targetRoot.get(Target_.description)), searchTextToLower)); - return predicate; - } + return (targetRoot, query, cb) -> { + final String searchTextToLower = searchText.toLowerCase(); + return cb.or(cb.like(cb.lower(targetRoot.get(Target_.name)), searchTextToLower), + cb.like(cb.lower(targetRoot.get(Target_.description)), searchTextToLower)); }; - - return spec; } /** @@ -158,21 +130,14 @@ public final class TargetSpecifications { * @return the {@link Target} {@link Specification} */ public static Specification hasInstalledOrAssignedDistributionSet(@NotNull final Long distributionId) { - final Specification spec = new Specification() { - @Override - public Predicate toPredicate(final Root targetRoot, final CriteriaQuery query, - final CriteriaBuilder cb) { - final Join targetInfoJoin = targetRoot.join(Target_.targetInfo); - final Predicate predicate = cb.or( - cb.equal(targetInfoJoin.get(TargetInfo_.installedDistributionSet).get(DistributionSet_.id), - distributionId), - cb.equal(targetRoot. get(Target_.assignedDistributionSet) - .get(DistributionSet_.id), distributionId)); - return predicate; - } + return (targetRoot, query, cb) -> { + final Join targetInfoJoin = targetRoot.join(Target_.targetInfo); + return cb.or( + cb.equal(targetInfoJoin.get(TargetInfo_.installedDistributionSet).get(DistributionSet_.id), + distributionId), + cb.equal(targetRoot. get(Target_.assignedDistributionSet).get(DistributionSet_.id), + distributionId)); }; - - return spec; } /** @@ -187,18 +152,11 @@ public final class TargetSpecifications { */ public static Specification hasControllerIdAndAssignedDistributionSetIdNot(final List tIDs, @NotNull final Long distributionId) { - final Specification spec = new Specification() { - @Override - public Predicate toPredicate(final Root targetRoot, final CriteriaQuery query, - final CriteriaBuilder cb) { - final Predicate predicate = cb.and(targetRoot.get(Target_.controllerId).in(tIDs), + return (targetRoot, query, cb) -> cb + .and(targetRoot.get(Target_.controllerId).in(tIDs), cb.or(cb.notEqual(targetRoot. get(Target_.assignedDistributionSet) .get(DistributionSet_.id), distributionId), - cb.isNull(targetRoot. get(Target_.assignedDistributionSet)))); - return predicate; - } - }; - return spec; + cb.isNull(targetRoot. get(Target_.assignedDistributionSet)))); } /** @@ -212,16 +170,11 @@ public final class TargetSpecifications { * @return the {@link Target} {@link Specification} */ public static Specification hasTags(final String[] tagNames, final Boolean selectTargetWithNoTag) { - final Specification spec = new Specification() { - @Override - public Predicate toPredicate(final Root targetRoot, final CriteriaQuery query, - final CriteriaBuilder cb) { - final Predicate predicate = getPredicate(targetRoot, cb, selectTargetWithNoTag, tagNames); - query.distinct(true); - return predicate; - } + return (targetRoot, query, cb) -> { + final Predicate predicate = getPredicate(targetRoot, cb, selectTargetWithNoTag, tagNames); + query.distinct(true); + return predicate; }; - return spec; } private static Predicate getPredicate(final Root targetRoot, final CriteriaBuilder cb, @@ -248,15 +201,9 @@ public final class TargetSpecifications { * @return the {@link Target} {@link Specification} */ public static Specification hasAssignedDistributionSet(final Long distributionSetId) { - return new Specification() { - @Override - public Predicate toPredicate(final Root targetRoot, final CriteriaQuery query, - final CriteriaBuilder cb) { - return cb.equal( - targetRoot. get(Target_.assignedDistributionSet).get(DistributionSet_.id), - distributionSetId); - } - }; + return (targetRoot, query, cb) -> cb.equal( + targetRoot. get(Target_.assignedDistributionSet).get(DistributionSet_.id), + distributionSetId); } /** @@ -268,14 +215,10 @@ public final class TargetSpecifications { * @return the {@link Target} {@link Specification} */ public static Specification hasInstalledDistributionSet(final Long distributionSetId) { - return new Specification() { - @Override - public Predicate toPredicate(final Root targetRoot, final CriteriaQuery query, - final CriteriaBuilder cb) { - final Join targetInfoJoin = targetRoot.join(Target_.targetInfo); - return cb.equal(targetInfoJoin.get(TargetInfo_.installedDistributionSet).get(DistributionSet_.id), - distributionSetId); - } + return (targetRoot, query, cb) -> { + final Join targetInfoJoin = targetRoot.join(Target_.targetInfo); + return cb.equal(targetInfoJoin.get(TargetInfo_.installedDistributionSet).get(DistributionSet_.id), + distributionSetId); }; } } diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/AbstractIntegrationTest.java b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/AbstractIntegrationTest.java index b7091edf8..2649a9060 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/AbstractIntegrationTest.java +++ b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/AbstractIntegrationTest.java @@ -48,6 +48,7 @@ import org.eclipse.hawkbit.repository.model.DistributionSetType; import org.eclipse.hawkbit.repository.model.SoftwareModuleType; import org.eclipse.hawkbit.repository.utils.RepositoryDataGenerator.DatabaseCleanupUtil; import org.eclipse.hawkbit.security.DosFilter; +import org.eclipse.hawkbit.security.SystemSecurityContext; import org.eclipse.hawkbit.tenancy.TenantAware; import org.junit.After; import org.junit.AfterClass; @@ -73,6 +74,7 @@ import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.DefaultMockMvcBuilder; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.context.WebApplicationContext; @@ -181,11 +183,10 @@ public abstract class AbstractIntegrationTest implements EnvironmentAware { @Autowired protected TenantAwareCacheManager cacheManager; - + @Autowired protected TenantConfigurationManagement tenantConfigurationManagement; - @Autowired protected RolloutManagement rolloutManagement; @@ -198,6 +199,9 @@ public abstract class AbstractIntegrationTest implements EnvironmentAware { @Autowired protected RolloutRepository rolloutRepository; + @Autowired + protected SystemSecurityContext systemSecurityContext; + protected MockMvc mvc; @Autowired @@ -223,12 +227,7 @@ public abstract class AbstractIntegrationTest implements EnvironmentAware { @Before public void before() throws Exception { - mvc = MockMvcBuilders.webAppContextSetup(context) - .addFilter(new DosFilter(100, 10, "127\\.0\\.0\\.1|\\[0:0:0:0:0:0:0:1\\]", "(^192\\.168\\.)", - "X-Forwarded-For")) - .addFilter(new ExcludePathAwareShallowETagFilter( - "/rest/v1/softwaremodules/{smId}/artifacts/{artId}/download", "/*/controller/artifacts/**")) - .build(); + mvc = createMvcWebAppContext().build(); standardDsType = securityRule.runAsPrivileged(() -> systemManagement.getTenantMetadata().getDefaultDsType()); @@ -245,6 +244,14 @@ public abstract class AbstractIntegrationTest implements EnvironmentAware { runtimeType = securityRule.runAsPrivileged(() -> softwareManagement.updateSoftwareModuleType(runtimeType)); } + protected DefaultMockMvcBuilder createMvcWebAppContext() { + return MockMvcBuilders.webAppContextSetup(context) + .addFilter(new DosFilter(100, 10, "127\\.0\\.0\\.1|\\[0:0:0:0:0:0:0:1\\]", "(^192\\.168\\.)", + "X-Forwarded-For")) + .addFilter(new ExcludePathAwareShallowETagFilter( + "/rest/v1/softwaremodules/{smId}/artifacts/{artId}/download", "/*/controller/artifacts/**")); + } + @BeforeClass public static void beforeClass() { createTestdatabaseAndStart(); diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/TestConfiguration.java b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/TestConfiguration.java index 70372fac2..d96856557 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/TestConfiguration.java +++ b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/TestConfiguration.java @@ -79,7 +79,7 @@ public class TestConfiguration implements AsyncConfigurer { } /** - * Bean for the downlod id cache. + * Bean for the download id cache. * * @return the cache */ diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/TestDataUtil.java b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/TestDataUtil.java index befcd6a8a..7ce8283dc 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/TestDataUtil.java +++ b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/TestDataUtil.java @@ -8,6 +8,8 @@ */ package org.eclipse.hawkbit; +import static org.fest.assertions.api.Assertions.assertThat; + import java.io.InputStream; import java.util.ArrayList; import java.util.Collection; @@ -16,10 +18,15 @@ import java.util.Random; import java.util.UUID; import org.apache.commons.io.IOUtils; +import org.eclipse.hawkbit.repository.ActionRepository; import org.eclipse.hawkbit.repository.ArtifactManagement; +import org.eclipse.hawkbit.repository.ControllerManagement; import org.eclipse.hawkbit.repository.DistributionSetManagement; import org.eclipse.hawkbit.repository.SoftwareManagement; import org.eclipse.hawkbit.repository.TargetManagement; +import org.eclipse.hawkbit.repository.model.Action; +import org.eclipse.hawkbit.repository.model.Action.Status; +import org.eclipse.hawkbit.repository.model.ActionStatus; import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.DistributionSetTag; import org.eclipse.hawkbit.repository.model.DistributionSetType; @@ -27,6 +34,8 @@ import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.repository.model.SoftwareModuleType; import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.repository.model.TargetTag; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; import com.google.common.base.Strings; import com.google.common.collect.Lists; @@ -42,6 +51,56 @@ import net._01001111.text.LoremIpsum; public class TestDataUtil { private static final LoremIpsum LOREM = new LoremIpsum(); + public static DistributionSet createTestDistributionSet(final SoftwareManagement softwareManagement, + final DistributionSetManagement distributionSetManagement) { + final Pageable pageReq = new PageRequest(0, 400); + DistributionSet set = TestDataUtil.generateDistributionSet("one", softwareManagement, + distributionSetManagement); + set.setVersion("anotherVersion"); + set = distributionSetManagement.updateDistributionSet(set); + + set.getModules().forEach(module -> { + module.setDescription("updated description"); + softwareManagement.updateSoftwareModule(module); + }); + + // load also lazy stuff + set = distributionSetManagement.findDistributionSetByIdWithDetails(set.getId()); + + assertThat(distributionSetManagement.findDistributionSetsAll(pageReq, false, true)).hasSize(1); + return set; + } + + public static List sendUpdateActionStatusToTargets(final ControllerManagement controllerManagament, + final TargetManagement targetManagement, final ActionRepository actionRepository, final DistributionSet dsA, + final Iterable targs, final Status status, final String... msgs) { + final List result = new ArrayList(); + for (final Target t : targs) { + final List findByTarget = actionRepository.findByTarget(t); + for (final Action action : findByTarget) { + result.add(sendUpdateActionStatusToTarget(controllerManagament, targetManagement, status, action, t, + msgs)); + } + } + return result; + } + + private static Target sendUpdateActionStatusToTarget(final ControllerManagement controllerManagament, + final TargetManagement targetManagement, final Status status, final Action updActA, final Target t, + final String... msgs) { + updActA.setStatus(status); + + final ActionStatus statusMessages = new ActionStatus(); + statusMessages.setAction(updActA); + statusMessages.setOccurredAt(System.currentTimeMillis()); + statusMessages.setStatus(status); + for (final String msg : msgs) { + statusMessages.addMessage(msg); + } + controllerManagament.addUpdateActionStatus(statusMessages, updActA); + return targetManagement.findTargetByControllerID(t.getControllerId()); + } + public static List generateDistributionSets(final String suffix, final int number, final SoftwareManagement softwareManagement, final DistributionSetManagement distributionSetManagement) { @@ -95,7 +154,7 @@ public class TestDataUtil { return distributionSetManagement.createDistributionSet( buildDistributionSet(suffix != null && suffix.length() > 0 ? suffix : "DS", version, findOrCreateDistributionSetType(distributionSetManagement, "ecl_os_app_jvm", - "OC mandatory App/JVM optional", mand, opt), + "OS mandatory App/JVM optional", mand, opt), os, jvm, ah).setRequiredMigrationStep(isRequiredMigrationStep)); } @@ -143,7 +202,7 @@ public class TestDataUtil { } public static List generateDistributionSetTags(final int number) { - final List result = new ArrayList(); + final List result = new ArrayList<>(); for (int i = 0; i < number; i++) { result.add(new DistributionSetTag("tag" + i, "tagdesc" + i, "" + i)); diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/WithSpringAuthorityRule.java b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/WithSpringAuthorityRule.java index 15fda51b4..40f6a64c2 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/WithSpringAuthorityRule.java +++ b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/WithSpringAuthorityRule.java @@ -160,19 +160,23 @@ public class WithSpringAuthorityRule implements TestRule { } public static WithUser withUser(final String principal, final String... authorities) { - return withUserAndTenant(principal, "default", true, authorities); + return withUserAndTenant(principal, "default", true, true, authorities); + } + + public static WithUser withUser(final String principal, final boolean allSpPermision, final String... authorities) { + return withUserAndTenant(principal, "default", true, allSpPermision, authorities); } public static WithUser withUser(final boolean autoCreateTenant) { - return withUserAndTenant("bumlux", "default", autoCreateTenant, new String[] {}); + return withUserAndTenant("bumlux", "default", autoCreateTenant, true, new String[] {}); } public static WithUser withUserAndTenant(final String principal, final String tenant, final String... authorities) { - return withUserAndTenant(principal, tenant, true, new String[] {}); + return withUserAndTenant(principal, tenant, true, true, new String[] {}); } public static WithUser withUserAndTenant(final String principal, final String tenant, - final boolean autoCreateTenant, final String... authorities) { + final boolean autoCreateTenant, final boolean allSpPermission, final String... authorities) { return new WithUser() { @Override @@ -197,7 +201,7 @@ public class WithSpringAuthorityRule implements TestRule { @Override public boolean allSpPermissions() { - return true; + return allSpPermission; } @Override diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/ActionTest.java b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/ActionTest.java index 9bd532b5e..937a544a7 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/ActionTest.java +++ b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/ActionTest.java @@ -33,12 +33,10 @@ public class ActionTest { final Action timeforcedAction = new Action(); timeforcedAction.setActionType(ActionType.TIMEFORCED); timeforcedAction.setForcedTime(timeForceTimeAt); - final int knownHashCode = timeforcedAction.hashCode(); assertThat(timeforcedAction.isForce()).isFalse(); // wait until timeforce time is hit Thread.sleep(sleepTime + 100); assertThat(timeforcedAction.isForce()).isTrue(); - assertThat(timeforcedAction.hashCode()).isNotEqualTo(knownHashCode); } } diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/ArtifactManagementNoMongoDbTest.java b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/ArtifactManagementNoMongoDbTest.java index dd1e171ca..30f4093c2 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/ArtifactManagementNoMongoDbTest.java +++ b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/ArtifactManagementNoMongoDbTest.java @@ -8,6 +8,8 @@ */ package org.eclipse.hawkbit.repository; +import static org.junit.Assert.fail; + import java.io.ByteArrayInputStream; import java.io.IOException; @@ -37,7 +39,7 @@ public class ArtifactManagementNoMongoDbTest extends AbstractIntegrationTest { System.setProperty("spring.data.mongodb.port", "1020"); } - @Test(expected = ArtifactUploadFailedException.class) + @Test @Description("Checks if the expected ArtifactUploadFailedException is thrown in case of MongoDB down") public void createLocalArtifactWithMongoDbDown() throws IOException { SoftwareModule sm = new SoftwareModule(softwareManagement.findSoftwareModuleTypeByKey("os"), "name 1", @@ -46,7 +48,12 @@ public class ArtifactManagementNoMongoDbTest extends AbstractIntegrationTest { final byte random[] = RandomStringUtils.random(5 * 1024).getBytes(); - artifactManagement.createLocalArtifact(new ByteArrayInputStream(random), sm.getId(), "file1", false); + try { + artifactManagement.createLocalArtifact(new ByteArrayInputStream(random), sm.getId(), "file1", false); + fail("Should not have worked with MongoDb down."); + } catch (final ArtifactUploadFailedException e) { + + } } } diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/ArtifactManagementTest.java b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/ArtifactManagementTest.java index 2929110dd..7c801a571 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/ArtifactManagementTest.java +++ b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/ArtifactManagementTest.java @@ -352,11 +352,16 @@ public class ArtifactManagementTest extends AbstractIntegrationTestWithMongoDB { artifactManagement.loadLocalArtifactBinary(result).getFileInputStream())); } - @Test(expected = InsufficientPermissionException.class) + @Test @WithUser(allSpPermissions = true, removeFromAllPermission = { SpPermission.DOWNLOAD_REPOSITORY_ARTIFACT }) @Description("Trys and fails to load an artifact without required permission. Checks if expected InsufficientPermissionException is thrown.") public void loadLocalArtifactBinaryWithoutDownloadArtifactThrowsPermissionDenied() { - artifactManagement.loadLocalArtifactBinary(new LocalArtifact()); + try { + artifactManagement.loadLocalArtifactBinary(new LocalArtifact()); + fail("Should not have worked with missing permission."); + } catch (final InsufficientPermissionException e) { + + } } @Test diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/ControllerManagementTest.java b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/ControllerManagementTest.java index a3913da2b..279932ef7 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/ControllerManagementTest.java +++ b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/ControllerManagementTest.java @@ -43,12 +43,12 @@ public class ControllerManagementTest extends AbstractIntegrationTest { distributionSetManagement); Target savedTarget = targetManagement.createTarget(target); - final List toAssign = new ArrayList(); + final List toAssign = new ArrayList<>(); toAssign.add(savedTarget); assertThat(savedTarget.getTargetInfo().getUpdateStatus()).isEqualTo(TargetUpdateStatus.UNKNOWN); - savedTarget = deploymentManagement.assignDistributionSet(ds, toAssign).getAssignedTargets().iterator().next(); + savedTarget = deploymentManagement.assignDistributionSet(ds, toAssign).getAssignedEntity().iterator().next(); final Action savedAction = deploymentManagement.findActiveActionsByTarget(savedTarget).get(0); assertThat(targetManagement.findTargetByControllerID(savedTarget.getControllerId()).getTargetInfo() @@ -75,7 +75,7 @@ public class ControllerManagementTest extends AbstractIntegrationTest { } @Test - @Description("Register a controller which not exist") + @Description("Register a controller which does not exist") public void testfindOrRegisterTargetIfItDoesNotexist() { final Target target = controllerManagament.findOrRegisterTargetIfItDoesNotexist("AA", null); assertThat(target).as("target should not be null").isNotNull(); @@ -84,11 +84,12 @@ public class ControllerManagementTest extends AbstractIntegrationTest { assertThat(target).as("Target should be the equals").isEqualTo(sameTarget); assertThat(targetRepository.count()).as("Only 1 target should be registred").isEqualTo(1L); + // throws exception try { controllerManagament.findOrRegisterTargetIfItDoesNotexist("", null); - fail("target with empty controller id should not be registred"); + fail("should fail as target does not exist"); } catch (final ConstraintViolationException e) { - // ok + } } @@ -101,9 +102,9 @@ public class ControllerManagementTest extends AbstractIntegrationTest { final DistributionSet ds = TestDataUtil.generateDistributionSet("", softwareManagement, distributionSetManagement); Target savedTarget = targetManagement.createTarget(target); - final List toAssign = new ArrayList(); + final List toAssign = new ArrayList<>(); toAssign.add(savedTarget); - savedTarget = deploymentManagement.assignDistributionSet(ds, toAssign).getAssignedTargets().iterator().next(); + savedTarget = deploymentManagement.assignDistributionSet(ds, toAssign).getAssignedEntity().iterator().next(); Action savedAction = deploymentManagement.findActiveActionsByTarget(savedTarget).get(0); // test and verify @@ -124,7 +125,7 @@ public class ControllerManagementTest extends AbstractIntegrationTest { final ActionStatus actionStatusMessage3 = new ActionStatus(savedAction, Action.Status.FINISHED, System.currentTimeMillis()); actionStatusMessage3.addMessage("finish"); - savedAction = controllerManagament.addUpdateActionStatus(actionStatusMessage3, savedAction); + controllerManagament.addUpdateActionStatus(actionStatusMessage3, savedAction); targetManagement.findTargetByControllerID("Rabbit").getTargetInfo().getUpdateStatus(); diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/DeploymentManagementTest.java b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/DeploymentManagementTest.java index ecf079c29..a17054a3d 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/DeploymentManagementTest.java +++ b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/DeploymentManagementTest.java @@ -18,6 +18,7 @@ import java.util.LinkedList; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; import org.eclipse.hawkbit.AbstractIntegrationTest; import org.eclipse.hawkbit.Constants; @@ -154,8 +155,8 @@ public class DeploymentManagementTest extends AbstractIntegrationTest { List targets = targetManagement .createTargets(TestDataUtil.generateTargets(Constants.MAX_ENTRIES_IN_STATEMENT + 10)); - targets = deploymentManagement.assignDistributionSet(cancelDs, targets).getAssignedTargets(); - targets = deploymentManagement.assignDistributionSet(cancelDs2, targets).getAssignedTargets(); + targets = deploymentManagement.assignDistributionSet(cancelDs, targets).getAssignedEntity(); + targets = deploymentManagement.assignDistributionSet(cancelDs2, targets).getAssignedEntity(); targetManagement.findAllTargetIds().forEach(targetIdName -> { assertThat(deploymentManagement.findActiveActionsByTarget( @@ -386,7 +387,7 @@ public class DeploymentManagementTest extends AbstractIntegrationTest { .createTargets(TestDataUtil.buildTargetFixtures(10, myCtrlIDPref, "first description")); final String myDeployedCtrlIDPref = "myDeployedCtrlID"; - final List savedDeployedTargets = targetManagement + List savedDeployedTargets = targetManagement .createTargets(TestDataUtil.buildTargetFixtures(20, myDeployedCtrlIDPref, "first description")); final DistributionSet ds = TestDataUtil.generateDistributionSet("", softwareManagement, @@ -399,6 +400,10 @@ public class DeploymentManagementTest extends AbstractIntegrationTest { final Iterable allFoundTargets = targetManagement.findTargetsAll(pageReq).getContent(); + // get final updated version of targets + savedDeployedTargets = targetManagement.findTargetByControllerID( + savedDeployedTargets.stream().map(target -> target.getControllerId()).collect(Collectors.toList())); + assertThat(allFoundTargets).as("founded targets are wrong").containsAll(savedDeployedTargets) .containsAll(savedNakedTargets); assertThat(savedDeployedTargets).as("saved target are wrong") @@ -599,11 +604,15 @@ public class DeploymentManagementTest extends AbstractIntegrationTest { // activeActions, add a corresponding cancelAction and another // UpdateAction for dsA final Iterable deployed2DS = deploymentManagement - .assignDistributionSet(dsA, deployResWithDsB.getDeployedTargets()).getAssignedTargets(); + .assignDistributionSet(dsA, deployResWithDsB.getDeployedTargets()).getAssignedEntity(); actionRepository.findByDistributionSet(pageRequest, dsA).getContent().get(1); - assertThat(deployed2DS).as("deployed ds is wrong").containsAll(deployResWithDsB.getDeployedTargets()); - assertThat(deployed2DS).as("deployed ds is wrong").hasSameSizeAs(deployResWithDsB.getDeployedTargets()); + // get final updated version of targets + final List deployResWithDsBTargets = targetManagement.findTargetByControllerID(deployResWithDsB + .getDeployedTargets().stream().map(target -> target.getControllerId()).collect(Collectors.toList())); + + assertThat(deployed2DS).as("deployed ds is wrong").containsAll(deployResWithDsBTargets); + assertThat(deployed2DS).as("deployed ds is wrong").hasSameSizeAs(deployResWithDsBTargets); for (final Target t_ : deployed2DS) { final Target t = targetManagement.findTargetByControllerID(t_.getControllerId()); @@ -752,7 +761,7 @@ public class DeploymentManagementTest extends AbstractIntegrationTest { targs.add(targ); // doing the assignment - targs = deploymentManagement.assignDistributionSet(dsA, targs).getAssignedTargets(); + targs = deploymentManagement.assignDistributionSet(dsA, targs).getAssignedEntity(); targ = targetManagement.findTargetByControllerID(targs.iterator().next().getControllerId()); // checking the revisions of the created entities @@ -790,7 +799,7 @@ public class DeploymentManagementTest extends AbstractIntegrationTest { assertEquals("wrong installed ds", dsA, targ.getTargetInfo().getInstalledDistributionSet()); targs = deploymentManagement.assignDistributionSet(dsB.getId(), new String[] { "target-id-A" }) - .getAssignedTargets(); + .getAssignedEntity(); targ = targs.iterator().next(); @@ -821,7 +830,7 @@ public class DeploymentManagementTest extends AbstractIntegrationTest { final List targs = new ArrayList(); targs.add(targ); - final Iterable savedTargs = deploymentManagement.assignDistributionSet(dsA, targs).getAssignedTargets(); + final Iterable savedTargs = deploymentManagement.assignDistributionSet(dsA, targs).getAssignedEntity(); targ = savedTargs.iterator().next(); assertThat(dsA.getOptLockRevision()).as("lock revision is wrong").isEqualTo( @@ -917,7 +926,7 @@ public class DeploymentManagementTest extends AbstractIntegrationTest { // assigning all DistributionSet to the Target in the list // deployedTargets for (final DistributionSet ds : dsList) { - deployedTargets = deploymentManagement.assignDistributionSet(ds, deployedTargets).getAssignedTargets(); + deployedTargets = deploymentManagement.assignDistributionSet(ds, deployedTargets).getAssignedEntity(); } final DeploymentResult deploymentResult = new DeploymentResult(deployedTargets, nakedTargets, dsList, @@ -1021,8 +1030,7 @@ public class DeploymentManagementTest extends AbstractIntegrationTest { } private static class EventHandlerMock { - private final List events = Collections - .synchronizedList(new LinkedList()); + private final List events = Collections.synchronizedList(new LinkedList<>()); private final CountDownLatch latch; private final int expectedNumberOfEvents; @@ -1050,8 +1058,7 @@ public class DeploymentManagementTest extends AbstractIntegrationTest { } private static class CancelEventHandlerMock { - private final List events = Collections - .synchronizedList(new LinkedList()); + private final List events = Collections.synchronizedList(new LinkedList<>()); private final CountDownLatch latch; private final int expectedNumberOfEvents; diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/SoftwareManagementForDSTest.java b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/DistributionSetManagementTest.java similarity index 91% rename from hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/SoftwareManagementForDSTest.java rename to hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/DistributionSetManagementTest.java index 30f4a8cb0..db9618425 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/SoftwareManagementForDSTest.java +++ b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/DistributionSetManagementTest.java @@ -33,6 +33,7 @@ import org.eclipse.hawkbit.repository.model.DistributionSetTag; import org.eclipse.hawkbit.repository.model.DistributionSetType; import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.repository.model.Target; +import org.fest.assertions.core.Condition; import org.junit.Test; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; @@ -44,15 +45,12 @@ import ru.yandex.qatools.allure.annotations.Features; import ru.yandex.qatools.allure.annotations.Stories; /** - * {@link SoftwareManagement} test focused on {@link DistributionSet} and - * {@link DistributionSetType} related stuff. - * - * + * {@link DistributionSetManagement} tests. * */ @Features("Component Tests - Repository") -@Stories("Software Management") -public class SoftwareManagementForDSTest extends AbstractIntegrationTest { +@Stories("DistributionSet Management") +public class DistributionSetManagementTest extends AbstractIntegrationTest { @Test @Description("Tests the successfull module update of unused distribution set type which is in fact allowed.") @@ -102,7 +100,7 @@ public class SoftwareManagementForDSTest extends AbstractIntegrationTest { .isEqualTo("test123"); } - @Test(expected = EntityReadOnlyException.class) + @Test @Description("Tests the unsuccessfull update of used distribution set type (module addition).") public void addModuleToAssignedDistributionSetTypeFails() { final DistributionSetType nonUpdatableType = distributionSetManagement @@ -113,10 +111,17 @@ public class SoftwareManagementForDSTest extends AbstractIntegrationTest { .createDistributionSet(new DistributionSet("newtypesoft", "1", "", nonUpdatableType, null)); nonUpdatableType.addMandatoryModuleType(osType); - distributionSetManagement.updateDistributionSetType(nonUpdatableType); + + try { + distributionSetManagement.updateDistributionSetType(nonUpdatableType); + fail("Should not have worked as DS is in use."); + } catch (final EntityReadOnlyException e) { + + } + } - @Test(expected = EntityReadOnlyException.class) + @Test @Description("Tests the unsuccessfull update of used distribution set type (module removal).") public void removeModuleToAssignedDistributionSetTypeFails() { DistributionSetType nonUpdatableType = distributionSetManagement @@ -130,7 +135,12 @@ public class SoftwareManagementForDSTest extends AbstractIntegrationTest { .createDistributionSet(new DistributionSet("newtypesoft", "1", "", nonUpdatableType, null)); nonUpdatableType.removeModuleType(osType.getId()); - nonUpdatableType = distributionSetManagement.updateDistributionSetType(nonUpdatableType); + try { + distributionSetManagement.updateDistributionSetType(nonUpdatableType); + fail("Should not have worked as DS is in use."); + } catch (final EntityReadOnlyException e) { + + } } @Test @@ -152,22 +162,68 @@ public class SoftwareManagementForDSTest extends AbstractIntegrationTest { .createDistributionSetType(new DistributionSetType("softdeleted", "to be deletd", "")); assertThat(distributionSetTypeRepository.findAll()).contains(softDelete); - final DistributionSet dsNewType = distributionSetManagement - .createDistributionSet(new DistributionSet("newtypesoft", "1", "", softDelete, null)); + distributionSetManagement.createDistributionSet(new DistributionSet("newtypesoft", "1", "", softDelete, null)); distributionSetManagement.deleteDistributionSetType(softDelete); assertThat(distributionSetManagement.findDistributionSetTypeByKey("softdeleted").isDeleted()).isEqualTo(true); } - // TODO: kzimmerm: test N+1 - - @Test(expected = EntityAlreadyExistsException.class) + @Test @Description("Ensures that it is not possible to create a DS that already exists (unique constraint is on name,version for DS).") public void createDuplicateDistributionSetsFailsWithException() { TestDataUtil.generateDistributionSet("a", softwareManagement, distributionSetManagement); - TestDataUtil.generateDistributionSet("a", softwareManagement, distributionSetManagement); + try { + TestDataUtil.generateDistributionSet("a", softwareManagement, distributionSetManagement); + fail("Should not have worked as DS with same UK already exists."); + } catch (final EntityAlreadyExistsException e) { + } + } + + @Test + @Description("Verfies that a DS is of default type if not specified explicitly at creation time.") + public void createDistributionSetWithImplicitType() { + final DistributionSet set = distributionSetManagement + .createDistributionSet(new DistributionSet("newtypesoft", "1", "", null, null)); + + assertThat(set.getType()).as("Type should be equal to default type of tenant") + .isEqualTo(systemManagement.getTenantMetadata().getDefaultDsType()); + + } + + @Test + @Description("Verfies that multiple DS are of default type if not specified explicitly at creation time.") + public void createMultipleDistributionSetsWithImplicitType() { + + List sets = new ArrayList<>(); + for (int i = 0; i < 10; i++) { + sets.add(new DistributionSet("another DS" + i, "X" + i, "", null, null)); + } + + sets = distributionSetManagement.createDistributionSets(sets); + + assertThat(sets).as("Type should be equal to default type of tenant").are(new Condition() { + @Override + public boolean matches(final DistributionSet value) { + return value.getType().equals(systemManagement.getTenantMetadata().getDefaultDsType()); + } + }); + + } + + @Test + @Description("Verfies that a DS entity cannot be used for creation.") + public void createDistributionSetFailsOnExistingEntity() { + final DistributionSet set = distributionSetManagement + .createDistributionSet(new DistributionSet("newtypesoft", "1", "", null, null)); + + try { + distributionSetManagement.createDistributionSet(set); + fail("Should not have worked to create based on a persisted entity."); + } catch (final EntityAlreadyExistsException e) { + + } } @Test @@ -244,17 +300,22 @@ public class SoftwareManagementForDSTest extends AbstractIntegrationTest { } } - @Test(expected = DistributionSetTypeUndefinedException.class) + @Test @Description("Ensures that it is not possible to add a software module to a set that has no type defined.") public void updateDistributionSetModuleWithUndefinedTypeFails() { final DistributionSet testSet = new DistributionSet(); final SoftwareModule module = new SoftwareModule(appType, "agent-hub2", "1.0.5", null, ""); // update data - testSet.addModule(module); + try { + testSet.addModule(module); + fail("Should not have worked as DS type is undefined."); + } catch (final DistributionSetTypeUndefinedException e) { + + } } - @Test(expected = UnsupportedSoftwareModuleForThisDistributionSetException.class) + @Test @Description("Ensures that it is not possible to add a software module that is not defined of the DS's type.") public void updateDistributionSetUnsupportedModuleFails() { final DistributionSet set = new DistributionSet("agent-hub2", "1.0.5", "desc", @@ -262,7 +323,12 @@ public class SoftwareManagementForDSTest extends AbstractIntegrationTest { final SoftwareModule module = new SoftwareModule(appType, "agent-hub2", "1.0.5", null, ""); // update data - set.addModule(module); + try { + set.addModule(module); + fail("Should not have worked as module type is not in DS type."); + } catch (final UnsupportedSoftwareModuleForThisDistributionSetException e) { + + } } @Test @@ -429,11 +495,11 @@ public class SoftwareManagementForDSTest extends AbstractIntegrationTest { distributionSetManagement.deleteDistributionSet(dsDeleted); dsDeleted = distributionSetManagement.findDistributionSetById(dsDeleted.getId()); - ds100Group1 = distributionSetManagement.toggleTagAssignment(ds100Group1, dsTagA).getAssignedDs(); + ds100Group1 = distributionSetManagement.toggleTagAssignment(ds100Group1, dsTagA).getAssignedEntity(); dsTagA = distributionSetTagRepository.findByNameEquals(dsTagA.getName()); - ds100Group1 = distributionSetManagement.toggleTagAssignment(ds100Group1, dsTagB).getAssignedDs(); + ds100Group1 = distributionSetManagement.toggleTagAssignment(ds100Group1, dsTagB).getAssignedEntity(); dsTagA = distributionSetTagRepository.findByNameEquals(dsTagA.getName()); - ds100Group2 = distributionSetManagement.toggleTagAssignment(ds100Group2, dsTagA).getAssignedDs(); + ds100Group2 = distributionSetManagement.toggleTagAssignment(ds100Group2, dsTagA).getAssignedEntity(); dsTagA = distributionSetTagRepository.findByNameEquals(dsTagA.getName()); // check setup @@ -561,7 +627,7 @@ public class SoftwareManagementForDSTest extends AbstractIntegrationTest { .findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()).getContent()).hasSize(0); // combine deleted and complete and type - expected = new ArrayList(); + expected = new ArrayList<>(); expected.addAll(ds100Group1); expected.addAll(ds100Group2); distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsDeleted(Boolean.FALSE) @@ -570,7 +636,7 @@ public class SoftwareManagementForDSTest extends AbstractIntegrationTest { .findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()).getContent()).hasSize(200) .containsOnly(expected.toArray(new DistributionSet[0])); - expected = new ArrayList(); + expected = new ArrayList<>(); expected.add(dsDeleted); distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(Boolean.TRUE) .setType(standardDsType).setIsDeleted(Boolean.TRUE); @@ -583,7 +649,7 @@ public class SoftwareManagementForDSTest extends AbstractIntegrationTest { assertThat(distributionSetManagement .findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()).getContent()).hasSize(0); - expected = new ArrayList(); + expected = new ArrayList<>(); expected.add(dsNewType); distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(Boolean.TRUE).setType(newType); assertThat(distributionSetManagement @@ -591,7 +657,7 @@ public class SoftwareManagementForDSTest extends AbstractIntegrationTest { .containsOnly(expected.toArray(new DistributionSet[0])); // combine deleted and complete and type and text - expected = new ArrayList(); + expected = new ArrayList<>(); expected.addAll(ds100Group2); distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(Boolean.TRUE) .setType(standardDsType).setSearchText("%test2"); @@ -615,7 +681,7 @@ public class SoftwareManagementForDSTest extends AbstractIntegrationTest { .findDistributionSetsByFilters(pageReq, distributionSetFilterBuilder.build()).getContent()).hasSize(0); // combine deleted and complete and type and text and tag - expected = new ArrayList(); + expected = new ArrayList<>(); expected.addAll(ds100Group2); distributionSetFilterBuilder = getDistributionSetFilterBuilder().setIsComplete(true).setType(standardDsType) .setSearchText("%test2").setTagNames(Lists.newArrayList(dsTagA.getName())); @@ -637,7 +703,7 @@ public class SoftwareManagementForDSTest extends AbstractIntegrationTest { private List sendUpdateActionStatusToTargets(final DistributionSet dsA, final Iterable targs, final Status status, final String... msgs) { - final List result = new ArrayList(); + final List result = new ArrayList<>(); for (final Target t : targs) { final List findByTarget = actionRepository.findByTarget(t); for (final Action action : findByTarget) { @@ -730,7 +796,7 @@ public class SoftwareManagementForDSTest extends AbstractIntegrationTest { dsAssigned.getVersion()); final Target target = new Target("4712"); final Target savedTarget = targetManagement.createTarget(target); - final List toAssign = new ArrayList(); + final List toAssign = new ArrayList<>(); toAssign.add(savedTarget); deploymentManagement.assignDistributionSet(dsAssigned, toAssign); @@ -744,38 +810,6 @@ public class SoftwareManagementForDSTest extends AbstractIntegrationTest { .getTotalElements()).isEqualTo(2); } - /** - * helper method which re-orders a list as expected. Re-orders the given - * distribution set in the order as given and returns a new list with the - * new order. - * - * @param dsThree - * @param buildDistributionSets - * @return - */ - private List reOrderDSList(final Iterable buildDistributionSets, - final DistributionSet... ds) { - final List reOrderedList = new ArrayList<>(); - - final Iterator iterator = buildDistributionSets.iterator(); - while (iterator.hasNext()) { - final DistributionSet next = iterator.next(); - int reorder = -1; - for (int index = 0; index < ds.length; index++) { - if (next.equals(ds[index])) { - reorder = index; - } - } - if (reorder >= 0) { - reOrderedList.add(reorder, next); - } else { - reOrderedList.add(next); - } - } - - return reOrderedList; - } - private Target sendUpdateActionStatusToTarget(final Status status, final Action updActA, final Target t, final String... msgs) { updActA.setStatus(status); diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/SoftwareManagementTest.java b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/SoftwareManagementTest.java index 49776e392..849cf8e30 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/SoftwareManagementTest.java +++ b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/SoftwareManagementTest.java @@ -10,11 +10,11 @@ package org.eclipse.hawkbit.repository; import static org.fest.assertions.api.Assertions.assertThat; import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.ArrayList; -import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; @@ -24,14 +24,18 @@ import org.eclipse.hawkbit.AbstractIntegrationTestWithMongoDB; import org.eclipse.hawkbit.RandomGeneratedInputStream; import org.eclipse.hawkbit.TestDataUtil; import org.eclipse.hawkbit.WithUser; +import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException; +import org.eclipse.hawkbit.repository.exception.EntityNotFoundException; import org.eclipse.hawkbit.repository.model.Action; import org.eclipse.hawkbit.repository.model.Artifact; +import org.eclipse.hawkbit.repository.model.CustomSoftwareModule; import org.eclipse.hawkbit.repository.model.DistributionSet; -import org.eclipse.hawkbit.repository.model.DistributionSetTag; +import org.eclipse.hawkbit.repository.model.DistributionSetType; import org.eclipse.hawkbit.repository.model.LocalArtifact; import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.repository.model.SoftwareModuleMetadata; import org.eclipse.hawkbit.repository.model.SoftwareModuleType; +import org.eclipse.hawkbit.repository.model.SwMetadataCompositeKey; import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.repository.model.TargetUpdateStatus; import org.junit.Test; @@ -51,6 +55,165 @@ import ru.yandex.qatools.allure.annotations.Stories; @Stories("Software Management") public class SoftwareManagementTest extends AbstractIntegrationTestWithMongoDB { + @Test + @Description("Try to update non updatable fields results in repository doing nothing.") + public void updateTypeNonUpdateableFieldsFails() { + final SoftwareModuleType created = softwareManagement + .createSoftwareModuleType(new SoftwareModuleType("test-key", "test-name", "test-desc", 1)); + + created.setName("a new name"); + final SoftwareModuleType updated = softwareManagement.updateSoftwareModuleType(created); + + assertThat(updated.getOptLockRevision()) + .as("Expected version number of updated entitity to be equal to created version") + .isEqualTo(created.getOptLockRevision()); + } + + @Test + @Description("Calling update without changing fields results in no recorded change in the repository including unchanged audit fields.") + public void updateNothingResultsInUnchangedRepositoryForType() { + final SoftwareModuleType created = softwareManagement + .createSoftwareModuleType(new SoftwareModuleType("test-key", "test-name", "test-desc", 1)); + + final SoftwareModuleType updated = softwareManagement.updateSoftwareModuleType(created); + + assertThat(updated.getOptLockRevision()) + .as("Expected version number of updated entitity to be equal to created version") + .isEqualTo(created.getOptLockRevision()); + } + + @Test + @Description("Calling update for changed fields results in change in the repository.") + public void updateSoftareModuleTypeFieldsToNewValue() { + final SoftwareModuleType created = softwareManagement + .createSoftwareModuleType(new SoftwareModuleType("test-key", "test-name", "test-desc", 1)); + + created.setDescription("changed"); + created.setColour("changed"); + + final SoftwareModuleType updated = softwareManagement.updateSoftwareModuleType(created); + + assertThat(updated.getOptLockRevision()).as("Expected version number of updated entitity is") + .isEqualTo(created.getOptLockRevision() + 1); + assertThat(updated.getDescription()).as("Updated description is").isEqualTo("changed"); + assertThat(updated.getColour()).as("Updated vendor is").isEqualTo("changed"); + } + + @Test + @Description("Try to update non updatable fields results in repository doing nothing.") + public void updateNonUpdateableFieldsFails() { + final SoftwareModule ah = softwareManagement + .createSoftwareModule(new SoftwareModule(appType, "agent-hub", "1.0.1", null, "")); + + ah.setName("a new name"); + final SoftwareModule updated = softwareManagement.updateSoftwareModule(ah); + + assertThat(updated.getOptLockRevision()) + .as("Expected version number of updated entitity to be equal to created version") + .isEqualTo(ah.getOptLockRevision()); + } + + @Test + @Description("Calling update without changing fields results in no recorded change in the repository including unchanged audit fields.") + public void updateNothingResultsInUnchangedRepository() { + final SoftwareModule ah = softwareManagement + .createSoftwareModule(new SoftwareModule(appType, "agent-hub", "1.0.1", null, "")); + + final SoftwareModule updated = softwareManagement.updateSoftwareModule(ah); + + assertThat(updated.getOptLockRevision()) + .as("Expected version number of updated entitity to be equal to created version") + .isEqualTo(ah.getOptLockRevision()); + } + + @Test + @Description("Calling update for changed fields results in change in the repository.") + public void updateSoftareModuleFieldsToNewValue() { + final SoftwareModule ah = softwareManagement + .createSoftwareModule(new SoftwareModule(appType, "agent-hub", "1.0.1", "test desc", "test vendor")); + + ah.setDescription("changed"); + ah.setVendor("changed"); + final SoftwareModule updated = softwareManagement.updateSoftwareModule(ah); + + assertThat(updated.getOptLockRevision()).as("Expected version number of updated entitity is") + .isEqualTo(ah.getOptLockRevision() + 1); + assertThat(updated.getDescription()).as("Updated description is").isEqualTo("changed"); + assertThat(updated.getVendor()).as("Updated vendor is").isEqualTo("changed"); + } + + @Test + @Description("Create Software Module call fails when called for existing entity.") + public void createModuleCallFailsForExistingModule() { + final SoftwareModule ah = softwareManagement + .createSoftwareModule(new SoftwareModule(appType, "agent-hub", "1.0.1", "test desc", "test vendor")); + try { + softwareManagement.createSoftwareModule(ah); + fail("Should not have worked as module already exists."); + } catch (final EntityAlreadyExistsException e) { + + } + } + + @Test + @Description("Create Software Modules call fails when called for existing entities.") + public void createModulesCallFailsForExistingModule() { + final List modules = softwareManagement.createSoftwareModule( + Lists.newArrayList(new SoftwareModule(appType, "agent-hub", "1.0.1", "test desc", "test vendor"), + new SoftwareModule(appType, "agent-hub", "1.0.2", "test desc", "test vendor"))); + try { + softwareManagement.createSoftwareModule(modules); + fail("Should not have worked as module already exists."); + } catch (final EntityAlreadyExistsException e) { + + } + } + + @Test + @Description("Create Software Module Type call fails when called for existing entity.") + public void createModuleTypeCallFailsForExistingType() { + final SoftwareModuleType created = softwareManagement + .createSoftwareModuleType(new SoftwareModuleType("test-key", "test-name", "test-desc", 1)); + + try { + softwareManagement.createSoftwareModuleType(created); + fail("Should not have worked as module already exists."); + } catch (final EntityAlreadyExistsException e) { + + } + } + + @Test + @Description("Create Software Module Types call fails when called for existing entities.") + public void createModuleTypesCallFailsForExistingTypes() { + final List created = softwareManagement.createSoftwareModuleType( + Lists.newArrayList(new SoftwareModuleType("test-key-bumlux", "test-name", "test-desc", 1), + new SoftwareModuleType("test-key-bumlux2", "test-name2", "test-desc", 1))); + + try { + softwareManagement.createSoftwareModuleType(created); + fail("Should not have worked as module already exists."); + } catch (final EntityAlreadyExistsException e) { + + } + } + + @Test + @Description("Calling update for changing fields to null results in change in the repository.") + public void eraseSoftareModuleFields() { + final SoftwareModule ah = softwareManagement + .createSoftwareModule(new SoftwareModule(appType, "agent-hub", "1.0.1", "test desc", "test vendor")); + + ah.setDescription(null); + ah.setVendor(null); + final SoftwareModule updated = softwareManagement.updateSoftwareModule(ah); + + assertThat(updated.getOptLockRevision()).as("Expected version number of updated entitity is") + .isEqualTo(ah.getOptLockRevision() + 1); + assertThat(updated.getDescription()).as("Updated description is").isNull(); + assertThat(updated.getVendor()).as("Updated vendor is").isNull(); + } + @Test @Description("searched for software modules based on the various filter options, e.g. name,desc,type, version.") public void findSoftwareModuleByFilters() { @@ -105,7 +268,7 @@ public class SoftwareManagementTest extends AbstractIntegrationTestWithMongoDB { @Test @Description("Searches for software modules based on a list of IDs.") - public void findSoftwareModulesByIdAndType() { + public void findSoftwareModulesById() { final List modules = new ArrayList(); @@ -118,6 +281,54 @@ public class SoftwareManagementTest extends AbstractIntegrationTestWithMongoDB { assertThat(softwareManagement.findSoftwareModulesById(modules)).hasSize(2); } + @Test + @Description("Searches for software modules by type.") + public void findSoftwareModulesByType() { + // found in test + final SoftwareModule one = softwareManagement + .createSoftwareModule(new SoftwareModule(osType, "one", "one", null, "")); + final SoftwareModule two = softwareManagement + .createSoftwareModule(new SoftwareModule(osType, "two", "two", null, "")); + // ignored + softwareManagement.deleteSoftwareModule( + softwareManagement.createSoftwareModule(new SoftwareModule(osType, "deleted", "deleted", null, ""))); + softwareManagement.createSoftwareModule(new SoftwareModule(appType, "three", "3.0.2", null, "")); + + assertThat(softwareManagement.findSoftwareModulesByType(pageReq, osType).getContent()) + .as("Expected to find the following number of modules:").hasSize(2).as("with the following elements") + .contains(two, one); + } + + @Test + @Description("Counts all software modules in the repsitory that are not marked as deleted.") + public void countSoftwareModulesAll() { + // found in test + softwareManagement.createSoftwareModule(new SoftwareModule(osType, "one", "one", null, "")); + softwareManagement.createSoftwareModule(new SoftwareModule(appType, "two", "two", null, "")); + // ignored + softwareManagement.deleteSoftwareModule( + softwareManagement.createSoftwareModule(new SoftwareModule(osType, "deleted", "deleted", null, ""))); + + assertThat(softwareManagement.countSoftwareModulesAll()).as("Expected to find the following number of modules:") + .isEqualTo(2); + } + + @Test + @Description("Counts for software modules by type.") + public void countSoftwareModulesByType() { + // found in test + softwareManagement.createSoftwareModule(new SoftwareModule(osType, "one", "one", null, "")); + softwareManagement.createSoftwareModule(new SoftwareModule(osType, "two", "two", null, "")); + + // ignored + softwareManagement.deleteSoftwareModule( + softwareManagement.createSoftwareModule(new SoftwareModule(osType, "deleted", "deleted", null, ""))); + softwareManagement.createSoftwareModule(new SoftwareModule(appType, "three", "3.0.2", null, "")); + + assertThat(softwareManagement.countSoftwareModulesByType(osType)) + .as("Expected to find the following number of modules:").isEqualTo(2); + } + @Test @Description("Tests the successfull deletion of software module types. Both unused (hard delete) and used ones (soft delete).") public void deleteAssignedAndUnassignedSoftwareModuleTypes() { @@ -419,32 +630,194 @@ public class SoftwareManagementTest extends AbstractIntegrationTestWithMongoDB { } } - /** - * - * @param findAll - * @return - */ - @SuppressWarnings("rawtypes") - private Collection iterable2Collection(final Iterable iterable) { - final Collection col = new ArrayList(); - for (final Object o : iterable) { - col.add(o); - } - return col; + @Test + @Description("Test verfies that results are returned based on given filter parameters and in the specified order.") + public void findSoftwareModuleOrderByDistributionModuleNameAscModuleVersionAsc() { + // test meta data + final SoftwareModuleType testType = softwareManagement + .createSoftwareModuleType(new SoftwareModuleType("thetype", "thename", "desc", 100)); + final DistributionSetType testDsType = distributionSetManagement + .createDistributionSetType(new DistributionSetType("key", "name", "desc").addMandatoryModuleType(osType) + .addOptionalModuleType(testType)); + + // found in test + final SoftwareModule unassigned = softwareManagement + .createSoftwareModule(new SoftwareModule(testType, "asis", "found", null, "")); + final SoftwareModule one = softwareManagement + .createSoftwareModule(new SoftwareModule(testType, "found", "b", null, "")); + final SoftwareModule two = softwareManagement + .createSoftwareModule(new SoftwareModule(testType, "found", "c", null, "")); + final SoftwareModule differentName = softwareManagement + .createSoftwareModule(new SoftwareModule(testType, "differentname", "d", null, "")); + + // ignored + final SoftwareModule deleted = softwareManagement + .createSoftwareModule(new SoftwareModule(testType, "deleted", "deleted", null, "")); + final SoftwareModule four = softwareManagement + .createSoftwareModule(new SoftwareModule(osType, "sdfjhsdj", "e", null, "")); + + final DistributionSet set = distributionSetManagement.createDistributionSet(new DistributionSet("set", "1", + "desc", testDsType, Lists.newArrayList(one, two, deleted, four, differentName))); + softwareManagement.deleteSoftwareModule(deleted); + + // with filter on name, version and module type + assertThat(softwareManagement.findSoftwareModuleOrderBySetAssignmentAndModuleNameAscModuleVersionAsc(pageReq, + set.getId(), "found", testType).getContent()) + .as("Found modules with given name, given module type and the assigned ones first") + .containsExactly(new CustomSoftwareModule(one, true), new CustomSoftwareModule(two, true), + new CustomSoftwareModule(unassigned, false)); + + // with filter on module type only + assertThat(softwareManagement.findSoftwareModuleOrderBySetAssignmentAndModuleNameAscModuleVersionAsc(pageReq, + set.getId(), null, testType).getContent()) + .as("Found modules with given module type and the assigned ones first").containsExactly( + new CustomSoftwareModule(differentName, true), new CustomSoftwareModule(one, true), + new CustomSoftwareModule(two, true), new CustomSoftwareModule(unassigned, false)); + + // without any filter + assertThat(softwareManagement.findSoftwareModuleOrderBySetAssignmentAndModuleNameAscModuleVersionAsc(pageReq, + set.getId(), null, null).getContent()).as("Found modules with the assigned ones first").containsExactly( + new CustomSoftwareModule(differentName, true), new CustomSoftwareModule(one, true), + new CustomSoftwareModule(two, true), new CustomSoftwareModule(four, true), + new CustomSoftwareModule(unassigned, false)); } - /** - * - */ - private void printDSTags() { - System.out.println("=============================================================================="); - for (final DistributionSet d : distributionSetRepository.findAll()) { - System.out.printf("%s\t[", d.getName()); - for (final DistributionSetTag t : d.getTags()) { - System.out.printf("%s ", t.getName()); - } - System.out.println("]"); + @Test + @Description("Checks that number of modules is returned as expected based on given filters.") + public void countSoftwareModuleByFilters() { + + // test meta data + final SoftwareModuleType testType = softwareManagement + .createSoftwareModuleType(new SoftwareModuleType("thetype", "thename", "desc", 100)); + final DistributionSetType testDsType = distributionSetManagement + .createDistributionSetType(new DistributionSetType("key", "name", "desc").addMandatoryModuleType(osType) + .addOptionalModuleType(testType)); + + // test modules + softwareManagement.createSoftwareModule(new SoftwareModule(testType, "asis", "found", null, "")); + final SoftwareModule one = softwareManagement + .createSoftwareModule(new SoftwareModule(testType, "found", "b", null, "")); + final SoftwareModule two = softwareManagement + .createSoftwareModule(new SoftwareModule(testType, "found", "c", null, "")); + final SoftwareModule differentName = softwareManagement + .createSoftwareModule(new SoftwareModule(testType, "differentname", "d", null, "")); + final SoftwareModule four = softwareManagement + .createSoftwareModule(new SoftwareModule(osType, "found", "3.0.2", null, "")); + + // one soft deleted + final SoftwareModule deleted = softwareManagement + .createSoftwareModule(new SoftwareModule(testType, "deleted", "deleted", null, "")); + distributionSetManagement.createDistributionSet(new DistributionSet("set", "1", "desc", testDsType, + Lists.newArrayList(one, two, deleted, four, differentName))); + softwareManagement.deleteSoftwareModule(deleted); + + // test + assertThat(softwareManagement.countSoftwareModuleByFilters("found", testType)) + .as("Number of modules with given name or version and type").isEqualTo(3); + assertThat(softwareManagement.countSoftwareModuleByFilters(null, testType)) + .as("Number of modules with given type").isEqualTo(4); + assertThat(softwareManagement.countSoftwareModuleByFilters(null, null)).as("Number of modules overall") + .isEqualTo(5); + } + + @Test + @Description("Verfies that all undeleted software modules are found in the repository.") + public void countSoftwareModuleTypesAll() { + final SoftwareModuleType testType = softwareManagement + .createSoftwareModuleType(new SoftwareModuleType("thetype", "thename", "desc", 100)); + final DistributionSetType testDsType = distributionSetManagement + .createDistributionSetType(new DistributionSetType("key", "name", "desc").addMandatoryModuleType(osType) + .addOptionalModuleType(testType)); + final SoftwareModule four = softwareManagement + .createSoftwareModule(new SoftwareModule(osType, "found", "3.0.2", null, "")); + + // one soft deleted + final SoftwareModule deleted = softwareManagement + .createSoftwareModule(new SoftwareModule(testType, "deleted", "deleted", null, "")); + distributionSetManagement.createDistributionSet( + new DistributionSet("set", "1", "desc", testDsType, Lists.newArrayList(deleted, four))); + softwareManagement.deleteSoftwareModule(deleted); + + assertThat(softwareManagement.countSoftwareModulesAll()).as("Number of undeleted modules").isEqualTo(1); + assertThat(softwareModuleRepository.count()).as("Number of all modules").isEqualTo(2); + } + + @Test + @Description("Checks that software module typeis found based on given name.") + public void findSoftwareModuleTypeByName() { + final SoftwareModuleType found = softwareManagement + .createSoftwareModuleType(new SoftwareModuleType("thetype", "thename", "desc", 100)); + softwareManagement.createSoftwareModuleType(new SoftwareModuleType("thetype2", "anothername", "desc", 100)); + + assertThat(softwareManagement.findSoftwareModuleTypeByName("thename")).as("Type with given name") + .isEqualTo(found); + } + + @Test + @Description("Verfies that it is not possible to create a type that alrady exists.") + public void createSoftwareModuleTypeFailsWithExistingEntity() { + final SoftwareModuleType created = softwareManagement + .createSoftwareModuleType(new SoftwareModuleType("thetype", "thename", "desc", 100)); + try { + softwareManagement.createSoftwareModuleType(created); + fail("should not have worked as module type already exists"); + } catch (final EntityAlreadyExistsException e) { + } + + } + + @Test + @Description("Verfies that it is not possible to create a list of types where one already exists.") + public void createSoftwareModuleTypesFailsWithExistingEntity() { + final SoftwareModuleType created = softwareManagement + .createSoftwareModuleType(new SoftwareModuleType("thetype", "thename", "desc", 100)); + try { + softwareManagement.createSoftwareModuleType( + Lists.newArrayList(created, new SoftwareModuleType("anothertype", "anothername", "desc", 100))); + fail("should not have worked as module type already exists"); + } catch (final EntityAlreadyExistsException e) { + + } + } + + @Test + @Description("Verfies that multiple types are created as requested.") + public void createMultipleoftwareModuleTypes() { + final List created = softwareManagement + .createSoftwareModuleType(Lists.newArrayList(new SoftwareModuleType("thetype", "thename", "desc", 100), + new SoftwareModuleType("thetype2", "thename2", "desc2", 100))); + + assertThat(created.size()).as("Number of created types").isEqualTo(2); + assertThat(softwareManagement.countSoftwareModuleTypesAll()).as("Number of types in repository").isEqualTo(5); + } + + @Test + @Description("Verfies that sofwtare modules are resturned that are assigned to given DS.") + public void findSoftwareModuleByAssignedTo() { + // test meta data + final SoftwareModuleType testType = softwareManagement + .createSoftwareModuleType(new SoftwareModuleType("thetype", "thename", "desc", 100)); + final DistributionSetType testDsType = distributionSetManagement + .createDistributionSetType(new DistributionSetType("key", "name", "desc").addMandatoryModuleType(osType) + .addOptionalModuleType(testType)); + + // test modules + softwareManagement.createSoftwareModule(new SoftwareModule(testType, "asis", "found", null, "")); + final SoftwareModule one = softwareManagement + .createSoftwareModule(new SoftwareModule(testType, "found", "b", null, "")); + final SoftwareModule two = softwareManagement + .createSoftwareModule(new SoftwareModule(testType, "found", "c", null, "")); + + // one soft deleted + final SoftwareModule deleted = softwareManagement + .createSoftwareModule(new SoftwareModule(testType, "deleted", "deleted", null, "")); + final DistributionSet set = distributionSetManagement.createDistributionSet( + new DistributionSet("set", "1", "desc", testDsType, Lists.newArrayList(one, deleted))); + softwareManagement.deleteSoftwareModule(deleted); + + assertThat(softwareManagement.findSoftwareModuleByAssignedTo(pageReq, set).getContent()) + .as("Found this number of modules").hasSize(2); } @Test @@ -479,6 +852,27 @@ public class SoftwareManagementTest extends AbstractIntegrationTestWithMongoDB { assertThat(softwareModuleMetadata.get(0).getSoftwareModule().getId()).isEqualTo(ah.getId()); } + @Test + @Description("Checks that metadata for a software module cannot be created for an existing key.") + public void createSoftwareModuleMetadataFailsIfKeyExists() { + + final String knownKey1 = "myKnownKey1"; + final String knownValue1 = "myKnownValue1"; + final String knownValue2 = "myKnownValue2"; + + final SoftwareModule ah = softwareManagement + .createSoftwareModule(new SoftwareModule(appType, "agent-hub", "1.0.1", null, "")); + + softwareManagement.createSoftwareModuleMetadata(new SoftwareModuleMetadata(knownKey1, ah, knownValue1)); + + try { + softwareManagement.createSoftwareModuleMetadata(new SoftwareModuleMetadata(knownKey1, ah, knownValue2)); + fail("should not have worked as module metadata already exists"); + } catch (final EntityAlreadyExistsException e) { + + } + } + @Test @WithUser(allSpPermissions = true) @Description("Checks that metadata for a software module can be updated.") @@ -525,6 +919,47 @@ public class SoftwareManagementTest extends AbstractIntegrationTestWithMongoDB { assertThat(updated.getSoftwareModule().getId()).isEqualTo(ah.getId()); } + @Test + @Description("Verfies that existing metadata can be deleted.") + public void deleteSoftwareModuleMetadata() { + final String knownKey1 = "myKnownKey1"; + final String knownValue1 = "myKnownValue1"; + + SoftwareModule ah = softwareManagement + .createSoftwareModule(new SoftwareModule(appType, "agent-hub", "1.0.1", null, "")); + + ah = softwareManagement.createSoftwareModuleMetadata(new SoftwareModuleMetadata(knownKey1, ah, knownValue1)) + .getSoftwareModule(); + + assertThat(softwareManagement.findSoftwareModuleById(ah.getId()).getMetadata()) + .as("Contains the created metadata element") + .containsExactly(new SoftwareModuleMetadata(knownKey1, ah, knownValue1)); + + softwareManagement.deleteSoftwareModuleMetadata(new SwMetadataCompositeKey(ah, knownKey1)); + assertThat(softwareManagement.findSoftwareModuleById(ah.getId()).getMetadata()).as("Metadata elemenets are") + .isEmpty(); + } + + @Test + @Description("Verfies that non existing metadata find results in exception.") + public void findSoftwareModuleMetadataFailsIfEntryDoesNotExist() { + final String knownKey1 = "myKnownKey1"; + final String knownValue1 = "myKnownValue1"; + + SoftwareModule ah = softwareManagement + .createSoftwareModule(new SoftwareModule(appType, "agent-hub", "1.0.1", null, "")); + + ah = softwareManagement.createSoftwareModuleMetadata(new SoftwareModuleMetadata(knownKey1, ah, knownValue1)) + .getSoftwareModule(); + + try { + softwareManagement.findSoftwareModuleMetadata(new SwMetadataCompositeKey(ah, "doesnotexist")); + fail("should not have worked as module metadata with that key does not exist"); + } catch (final EntityNotFoundException e) { + + } + } + @Test @Description("Queries and loads the metadata related to a given software module.") public void findAllSoftwareModuleMetadataBySwId() { diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/TagManagementTest.java b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/TagManagementTest.java index eb263b242..4c6af0d83 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/TagManagementTest.java +++ b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/TagManagementTest.java @@ -12,7 +12,10 @@ import static org.fest.assertions.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; +import java.util.ArrayList; +import java.util.Arrays; import java.util.List; +import java.util.stream.Collectors; import org.eclipse.hawkbit.AbstractIntegrationTest; import org.eclipse.hawkbit.TestDataUtil; @@ -20,9 +23,11 @@ import org.eclipse.hawkbit.repository.DistributionSetFilter.DistributionSetFilte import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException; import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.DistributionSetTag; +import org.eclipse.hawkbit.repository.model.DistributionSetTagAssignmentResult; import org.eclipse.hawkbit.repository.model.Tag; import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.repository.model.TargetTag; +import org.eclipse.hawkbit.repository.model.TargetTagAssignmentResult; import org.junit.Before; import org.junit.Test; import org.slf4j.LoggerFactory; @@ -158,6 +163,98 @@ public class TagManagementTest extends AbstractIntegrationTest { return new DistributionSetFilterBuilder(); } + @Test + @Description("Verifies the toogle mechanism by means on assigning tag if at least on DS in the list does not have" + + "the tag yet. Unassign if all of them have the tag already.") + public void assignAndUnassignDistributionSetTags() { + final List groupA = TestDataUtil.generateDistributionSets(20, softwareManagement, + distributionSetManagement); + final List groupB = TestDataUtil.generateDistributionSets("unassigned", 20, softwareManagement, + distributionSetManagement); + + final DistributionSetTag tag = tagManagement + .createDistributionSetTag(new DistributionSetTag("tag1", "tagdesc1", "")); + + // toggle A only -> A is now assigned + DistributionSetTagAssignmentResult result = distributionSetManagement.toggleTagAssignment(groupA, tag); + assertThat(result.getAlreadyAssigned()).isEqualTo(0); + assertThat(result.getAssigned()).isEqualTo(20); + assertThat(result.getAssignedEntity()).containsAll(distributionSetManagement.findDistributionSetListWithDetails( + groupA.stream().map(set -> set.getId()).collect(Collectors.toList()))); + assertThat(result.getUnassigned()).isEqualTo(0); + assertThat(result.getUnassignedEntity()).isEmpty(); + assertThat(result.getDistributionSetTag()).isEqualTo(tag); + + // toggle A+B -> A is still assigned and B is assigned as well + result = distributionSetManagement.toggleTagAssignment(concat(groupA, groupB), tag); + assertThat(result.getAlreadyAssigned()).isEqualTo(20); + assertThat(result.getAssigned()).isEqualTo(20); + assertThat(result.getAssignedEntity()).containsAll(distributionSetManagement.findDistributionSetListWithDetails( + groupB.stream().map(set -> set.getId()).collect(Collectors.toList()))); + assertThat(result.getUnassigned()).isEqualTo(0); + assertThat(result.getUnassignedEntity()).isEmpty(); + assertThat(result.getDistributionSetTag()).isEqualTo(tag); + + // toggle A+B -> both unassigned + result = distributionSetManagement.toggleTagAssignment(concat(groupA, groupB), tag); + assertThat(result.getAlreadyAssigned()).isEqualTo(0); + assertThat(result.getAssigned()).isEqualTo(0); + assertThat(result.getAssignedEntity()).isEmpty(); + assertThat(result.getUnassigned()).isEqualTo(40); + assertThat(result.getUnassignedEntity()).containsAll(distributionSetManagement.findDistributionSetListWithDetails( + concat(groupB, groupA).stream().map(set -> set.getId()).collect(Collectors.toList()))); + assertThat(result.getDistributionSetTag()).isEqualTo(tag); + + } + + @Test + @Description("Verifies the toogle mechanism by means on assigning tag if at least on target in the list does not have" + + "the tag yet. Unassign if all of them have the tag already.") + public void assignAndUnassignTargetTags() { + final List groupA = targetManagement.createTargets(TestDataUtil.generateTargets(20, "")); + final List groupB = targetManagement.createTargets(TestDataUtil.generateTargets(20, "groupb")); + + final TargetTag tag = tagManagement.createTargetTag(new TargetTag("tag1", "tagdesc1", "")); + + // toggle A only -> A is now assigned + TargetTagAssignmentResult result = targetManagement.toggleTagAssignment(groupA, tag); + assertThat(result.getAlreadyAssigned()).isEqualTo(0); + assertThat(result.getAssigned()).isEqualTo(20); + assertThat(result.getAssignedEntity()).containsAll(targetManagement.findTargetsByControllerIDsWithTags( + groupA.stream().map(target -> target.getControllerId()).collect(Collectors.toList()))); + assertThat(result.getUnassigned()).isEqualTo(0); + assertThat(result.getUnassignedEntity()).isEmpty(); + assertThat(result.getTargetTag()).isEqualTo(tag); + + // toggle A+B -> A is still assigned and B is assigned as well + result = targetManagement.toggleTagAssignment(concat(groupA, groupB), tag); + assertThat(result.getAlreadyAssigned()).isEqualTo(20); + assertThat(result.getAssigned()).isEqualTo(20); + assertThat(result.getAssignedEntity()).containsAll(targetManagement.findTargetsByControllerIDsWithTags( + groupB.stream().map(target -> target.getControllerId()).collect(Collectors.toList()))); + assertThat(result.getUnassigned()).isEqualTo(0); + assertThat(result.getUnassignedEntity()).isEmpty(); + assertThat(result.getTargetTag()).isEqualTo(tag); + + // toggle A+B -> both unassigned + result = targetManagement.toggleTagAssignment(concat(groupA, groupB), tag); + assertThat(result.getAlreadyAssigned()).isEqualTo(0); + assertThat(result.getAssigned()).isEqualTo(0); + assertThat(result.getAssignedEntity()).isEmpty(); + assertThat(result.getUnassigned()).isEqualTo(40); + assertThat(result.getUnassignedEntity()).containsAll(targetManagement.findTargetsByControllerIDsWithTags( + concat(groupB, groupA).stream().map(target -> target.getControllerId()).collect(Collectors.toList()))); + assertThat(result.getTargetTag()).isEqualTo(tag); + + } + + @SafeVarargs + private final List concat(final List... targets) { + final List result = new ArrayList<>(); + Arrays.asList(targets).forEach(result::addAll); + return result; + } + @Test @Description("Ensures that all tags are retrieved through repository.") public void findAllTargetTags() { @@ -266,47 +363,58 @@ public class TagManagementTest extends AbstractIntegrationTest { } } + @Test @Description("Ensures that a tag cannot be created if one exists already with that name (ecpects EntityAlreadyExistsException).") public void failedDuplicateTargetTagNameException() { tagManagement.createTargetTag(new TargetTag("A")); + try { tagManagement.createTargetTag(new TargetTag("A")); - fail("Expected EntityAlreadyExistsException"); + fail("should not have worked as tag already exists"); } catch (final EntityAlreadyExistsException e) { + } } + @Test @Description("Ensures that a tag cannot be updated to a name that already exists on another tag (ecpects EntityAlreadyExistsException).") public void failedDuplicateTargetTagNameExceptionAfterUpdate() { tagManagement.createTargetTag(new TargetTag("A")); final TargetTag tag = tagManagement.createTargetTag(new TargetTag("B")); tag.setName("A"); + try { tagManagement.updateTargetTag(tag); - fail("Expected EntityAlreadyExistsException"); + fail("should not have worked as tag already exists"); } catch (final EntityAlreadyExistsException e) { + } } + @Test @Description("Ensures that a tag cannot be created if one exists already with that name (ecpects EntityAlreadyExistsException).") public void failedDuplicateDsTagNameException() { tagManagement.createDistributionSetTag(new DistributionSetTag("A")); try { tagManagement.createDistributionSetTag(new DistributionSetTag("A")); - fail("Expected EntityAlreadyExistsException"); + fail("should not have worked as tag already exists"); } catch (final EntityAlreadyExistsException e) { + } } + @Test @Description("Ensures that a tag cannot be updated to a name that already exists on another tag (ecpects EntityAlreadyExistsException).") public void failedDuplicateDsTagNameExceptionAfterUpdate() { tagManagement.createDistributionSetTag(new DistributionSetTag("A")); final DistributionSetTag tag = tagManagement.createDistributionSetTag(new DistributionSetTag("B")); tag.setName("A"); + try { tagManagement.updateDistributionSetTag(tag); - fail("Expected EntityAlreadyExistsException"); + fail("should not have worked as tag already exists"); } catch (final EntityAlreadyExistsException e) { + } } diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/TargetFilterQueryManagenmentTest.java b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/TargetFilterQueryManagenmentTest.java index 73528ca5b..99e08f331 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/TargetFilterQueryManagenmentTest.java +++ b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/TargetFilterQueryManagenmentTest.java @@ -9,6 +9,7 @@ package org.eclipse.hawkbit.repository; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; import org.eclipse.hawkbit.AbstractIntegrationTest; import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException; @@ -22,10 +23,7 @@ import ru.yandex.qatools.allure.annotations.Stories; /** * Test class for {@link TargetFilterQueryManagement}. * - * - * */ - @Features("Component Tests - Repository") @Stories("Target Filter Query Management") public class TargetFilterQueryManagenmentTest extends AbstractIntegrationTest { @@ -40,15 +38,20 @@ public class TargetFilterQueryManagenmentTest extends AbstractIntegrationTest { targetFilterQueryManagement.findTargetFilterQueryByName(filterName)); } - @Test(expected = EntityAlreadyExistsException.class) + @Test @Description("Checks if the EntityAlreadyExistsException is thrown if a targetfilterquery with the same name are created more than once.") public void createDuplicateTargetFilterQuery() { final String filterName = "new target filter duplicate"; targetFilterQueryManagement .createTargetFilterQuery(new TargetFilterQuery(filterName, "name==PendingTargets001")); - targetFilterQueryManagement - .createTargetFilterQuery(new TargetFilterQuery(filterName, "name==PendingTargets001")); + try { + targetFilterQueryManagement + .createTargetFilterQuery(new TargetFilterQuery(filterName, "name==PendingTargets001")); + fail("should not have worked as query already exists"); + } catch (final EntityAlreadyExistsException e) { + + } } @Test diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/TargetManagementSearchTest.java b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/TargetManagementSearchTest.java index 34aa223c3..73d549eb7 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/TargetManagementSearchTest.java +++ b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/TargetManagementSearchTest.java @@ -11,28 +11,34 @@ package org.eclipse.hawkbit.repository; import static org.fest.assertions.api.Assertions.assertThat; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; +import java.util.stream.Collectors; import org.eclipse.hawkbit.AbstractIntegrationTest; import org.eclipse.hawkbit.TestDataUtil; import org.eclipse.hawkbit.repository.model.Action; import org.eclipse.hawkbit.repository.model.Action.Status; import org.eclipse.hawkbit.repository.model.ActionStatus; -import org.eclipse.hawkbit.repository.model.BaseEntity; import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.Target; +import org.eclipse.hawkbit.repository.model.TargetFilterQuery; +import org.eclipse.hawkbit.repository.model.TargetIdName; import org.eclipse.hawkbit.repository.model.TargetTag; import org.eclipse.hawkbit.repository.model.TargetUpdateStatus; +import org.eclipse.hawkbit.repository.model.TenantAwareBaseEntity; +import org.eclipse.hawkbit.repository.specifications.TargetSpecifications; import org.junit.Test; -import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Slice; +import com.google.common.collect.Lists; import com.google.common.primitives.Ints; import ru.yandex.qatools.allure.annotations.Description; import ru.yandex.qatools.allure.annotations.Features; +import ru.yandex.qatools.allure.annotations.Step; import ru.yandex.qatools.allure.annotations.Stories; @Features("Component Tests - Repository") @@ -40,152 +46,634 @@ import ru.yandex.qatools.allure.annotations.Stories; public class TargetManagementSearchTest extends AbstractIntegrationTest { @Test - @Description("Tests different parameter combinations for target search operations. That includes both the test itself as a count operation with the same filters.") + @Description("Tests different parameter combinations for target search operations. " + + "That includes both the test itself, as a count operation with the same filters " + + "and query definitions by RSQL (named and un-named).") public void targetSearchWithVariousFilterCombinations() { - final TargetTag targTagA = tagManagement.createTargetTag(new TargetTag("TargTag-A")); - final TargetTag targTagB = tagManagement.createTargetTag(new TargetTag("TargTag-B")); - final TargetTag targTagC = tagManagement.createTargetTag(new TargetTag("TargTag-C")); - final TargetTag targTagD = tagManagement.createTargetTag(new TargetTag("TargTag-D")); - - // TODO kaizimmerm: test also installedDS (not only assignedDS) + final TargetTag targTagX = tagManagement.createTargetTag(new TargetTag("TargTag-X")); + final TargetTag targTagY = tagManagement.createTargetTag(new TargetTag("TargTag-Y")); + final TargetTag targTagZ = tagManagement.createTargetTag(new TargetTag("TargTag-Z")); + final TargetTag targTagW = tagManagement.createTargetTag(new TargetTag("TargTag-W")); final DistributionSet setA = TestDataUtil.generateDistributionSet("", softwareManagement, distributionSetManagement); + final DistributionSet installedSet = TestDataUtil.generateDistributionSet("another", softwareManagement, + distributionSetManagement); + final String targetDsAIdPref = "targ-A"; List targAs = targetManagement.createTargets( TestDataUtil.buildTargetFixtures(100, targetDsAIdPref, targetDsAIdPref.concat(" description"))); - targAs = targetManagement.toggleTagAssignment(targAs, targTagA).getAssignedTargets(); + targAs = targetManagement.toggleTagAssignment(targAs, targTagX).getAssignedEntity(); final String targetDsBIdPref = "targ-B"; List targBs = targetManagement.createTargets( TestDataUtil.buildTargetFixtures(100, targetDsBIdPref, targetDsBIdPref.concat(" description"))); - targBs = targetManagement.toggleTagAssignment(targBs, targTagB).getAssignedTargets(); - targBs = targetManagement.toggleTagAssignment(targBs, targTagD).getAssignedTargets(); + targBs = targetManagement.toggleTagAssignment(targBs, targTagY).getAssignedEntity(); + targBs = targetManagement.toggleTagAssignment(targBs, targTagW).getAssignedEntity(); final String targetDsCIdPref = "targ-C"; List targCs = targetManagement.createTargets( TestDataUtil.buildTargetFixtures(100, targetDsCIdPref, targetDsCIdPref.concat(" description"))); - targCs = targetManagement.toggleTagAssignment(targCs, targTagC).getAssignedTargets(); - targCs = targetManagement.toggleTagAssignment(targCs, targTagD).getAssignedTargets(); + targCs = targetManagement.toggleTagAssignment(targCs, targTagZ).getAssignedEntity(); + targCs = targetManagement.toggleTagAssignment(targCs, targTagW).getAssignedEntity(); final String targetDsDIdPref = "targ-D"; - final Iterable targDs = targetManagement.createTargets( + final List targDs = targetManagement.createTargets( TestDataUtil.buildTargetFixtures(100, targetDsDIdPref, targetDsDIdPref.concat(" description"))); - deploymentManagement.assignDistributionSet(setA.getId(), targCs.iterator().next().getControllerId()); - deploymentManagement.assignDistributionSet(setA.getId(), targAs.iterator().next().getControllerId()); - deploymentManagement.assignDistributionSet(setA.getId(), targBs.iterator().next().getControllerId()); + final String assignedC = targCs.iterator().next().getControllerId(); + deploymentManagement.assignDistributionSet(setA.getId(), assignedC); + final String assignedA = targAs.iterator().next().getControllerId(); + deploymentManagement.assignDistributionSet(setA.getId(), assignedA); + final String assignedB = targBs.iterator().next().getControllerId(); + deploymentManagement.assignDistributionSet(setA.getId(), assignedB); + final String installedC = targCs.iterator().next().getControllerId(); + final Long actionId = deploymentManagement.assignDistributionSet(installedSet.getId(), assignedC).getActions() + .get(0); - final List unknown = new ArrayList(); + // set one installed DS also + final Action action = deploymentManagement.findActionWithDetails(actionId); + action.setStatus(Status.FINISHED); + controllerManagament.addUpdateActionStatus( + new ActionStatus(action, Status.FINISHED, System.currentTimeMillis(), "message"), action); + deploymentManagement.assignDistributionSet(setA.getId(), installedC); + + final List unknown = new ArrayList<>(); unknown.add(TargetUpdateStatus.UNKNOWN); - final List pending = new ArrayList(); + final List pending = new ArrayList<>(); pending.add(TargetUpdateStatus.PENDING); - final List both = new ArrayList(); + final List both = new ArrayList<>(); both.add(TargetUpdateStatus.UNKNOWN); both.add(TargetUpdateStatus.PENDING); - final PageRequest pageReq = new PageRequest(0, 500); + // get final updated version of targets + targAs = targetManagement.findTargetByControllerID( + targAs.stream().map(target -> target.getControllerId()).collect(Collectors.toList())); + targBs = targetManagement.findTargetByControllerID( + targBs.stream().map(target -> target.getControllerId()).collect(Collectors.toList())); + targCs = targetManagement.findTargetByControllerID( + targCs.stream().map(target -> target.getControllerId()).collect(Collectors.toList())); + // try to find several targets with different filter settings + verifyThatRepositoryContains400Targets(); + verifyThat200TargetsHaveTagD(targTagW, concat(targBs, targCs)); + verifyThat100TargetsContainsGivenTextAndHaveTagAssigned(targTagY, targTagW, targBs); + verifyThat1TargetHasTagHasDescOrNameAndDs(targTagW, setA, targetManagement.findTargetByControllerID(assignedC)); + verifyThat0TargetsWithTagAndDescOrNameHasDS(targTagW, setA); + verifyThat0TargetsWithNameOrdescAndDSHaveTag(targTagX, setA); + verifyThat3TargetsHaveDSAssigned(setA, + targetManagement.findTargetByControllerID(Lists.newArrayList(assignedA, assignedB, assignedC))); + verifyThat1TargetWithDescOrNameHasDS(setA, targetManagement.findTargetByControllerID(assignedA)); + List expected = concat(targAs, targBs, targCs, targDs); + expected.removeAll( + targetManagement.findTargetByControllerID(Lists.newArrayList(assignedA, assignedB, assignedC))); + verifyThat397TargetsAreInStatusUnknown(unknown, expected); + expected = concat(targBs, targCs); + expected.removeAll(targetManagement.findTargetByControllerID(Lists.newArrayList(assignedB, assignedC))); + verifyThat198TargetsAreInStatusUnknownAndHaveGivenTags(targTagY, targTagW, unknown, expected); + verfyThat0TargetsAreInStatusUnknownAndHaveDSAssigned(setA, unknown); + expected = concat(targAs); + expected.remove(targetManagement.findTargetByControllerID(assignedA)); + verifyThat99TargetsWithNameOrDescriptionAreInGivenStatus(unknown, expected); + expected = concat(targBs); + expected.remove(targetManagement.findTargetByControllerID(assignedB)); + verifyThat99TargetsWithGivenNameOrDescAndTagAreInStatusUnknown(targTagW, unknown, expected); + verifyThat3TargetsAreInStatusPending(pending, + targetManagement.findTargetByControllerID(Lists.newArrayList(assignedA, assignedB, assignedC))); + verifyThat3TargetsWithGivenDSAreInPending(setA, pending, + targetManagement.findTargetByControllerID(Lists.newArrayList(assignedA, assignedB, assignedC))); + verifyThat1TargetWithGivenNameOrDescAndDSIsInPending(setA, pending, + targetManagement.findTargetByControllerID(assignedA)); + verifyThat1TargetWithGivenNameOrDescAndTagAndDSIsInPending(targTagW, setA, pending, + targetManagement.findTargetByControllerID(assignedB)); + verifyThat2TargetsWithGivenTagAndDSIsInPending(targTagW, setA, pending, + targetManagement.findTargetByControllerID(Lists.newArrayList(assignedB, assignedC))); + verifyThat2TargetsWithGivenTagAreInPending(targTagW, pending, + targetManagement.findTargetByControllerID(Lists.newArrayList(assignedB, assignedC))); + verifyThat200targetsWithGivenTagAreInStatusPendingorUnknown(targTagW, both, concat(targBs, targCs)); + verfiyThat1TargetAIsInStatusPendingAndHasDSInstalled(installedSet, pending, + targetManagement.findTargetByControllerID(installedC)); + } - // TODO kaizimmerm: comment and check also the content itself, not only - // the numbers - // (containsOnly) - assertThat(targetManagement.countTargetsAll()).isEqualTo(400); + @Step + private void verfiyThat1TargetAIsInStatusPendingAndHasDSInstalled(final DistributionSet installedSet, + final List pending, final Target expected) { + final TargetIdName expectedIdName = convertToIdName(expected); + final String query = "updatestatus==pending and installedds.name==" + installedSet.getName(); - assertThat(targetManagement.findTargetByFilters(pageReq, null, null, null, Boolean.FALSE, targTagD.getName()) - .getNumberOfElements()).isEqualTo(200).isEqualTo(Ints.saturatedCast( - targetManagement.countTargetByFilters(null, null, null, Boolean.FALSE, targTagD.getName()))); + assertThat(targetManagement + .findTargetByFilters(pageReq, pending, null, installedSet.getId(), Boolean.FALSE, new String[0]) + .getContent()).as("has number of elements").hasSize(1) + .as("that number is also returned by count query") + .hasSize(Ints.saturatedCast(targetManagement.countTargetByFilters(pending, null, + installedSet.getId(), Boolean.FALSE, new String[0]))) + .as("and contains the following elements").containsExactly(expected) + .as("and filter query returns the same result") + .containsAll(targetManagement.findTargetsAll(query, pageReq).getContent()) + .as("and NAMED filter query returns the same result").containsAll(targetManagement + .findTargetsAll(new TargetFilterQuery("test", query), pageReq).getContent()); - Slice x = targetManagement.findTargetByFilters(pageReq, null, "%targ-B%", null, Boolean.FALSE, - targTagB.getName(), targTagD.getName()); - assertThat(x.getNumberOfElements()).isEqualTo(100).isEqualTo(Ints.saturatedCast(targetManagement - .countTargetByFilters(null, "%targ-B%", null, Boolean.FALSE, targTagB.getName(), targTagD.getName()))); - - x = targetManagement.findTargetByFilters(pageReq, null, "%targ-C%", setA.getId(), Boolean.FALSE, - targTagD.getName()); - assertThat(x.getNumberOfElements()).isEqualTo(1).isEqualTo(Ints.saturatedCast(targetManagement - .countTargetByFilters(null, "%targ-C%", setA.getId(), Boolean.FALSE, targTagD.getName()))); - - x = targetManagement.findTargetByFilters(pageReq, null, "%targ-A%", setA.getId(), Boolean.FALSE, - targTagD.getName()); - assertThat(x.getNumberOfElements()).isEqualTo(0).isEqualTo(Ints.saturatedCast(targetManagement - .countTargetByFilters(null, "%targ-A%", setA.getId(), Boolean.FALSE, targTagD.getName()))); - - x = targetManagement.findTargetByFilters(pageReq, null, "%targ-C%", setA.getId(), Boolean.FALSE, - targTagA.getName()); - assertThat(x.getNumberOfElements()).isEqualTo(0).isEqualTo(Ints.saturatedCast(targetManagement - .countTargetByFilters(null, "%targ-C%", setA.getId(), Boolean.FALSE, targTagA.getName()))); - - x = targetManagement.findTargetByFilters(pageReq, null, null, setA.getId(), Boolean.FALSE, null); - assertThat(x.getNumberOfElements()).isEqualTo(3).isEqualTo(Ints - .saturatedCast(targetManagement.countTargetByFilters(null, null, setA.getId(), Boolean.FALSE, null))); - - x = targetManagement.findTargetByFilters(pageReq, null, "%targ-A%", setA.getId(), Boolean.FALSE, null); - assertThat(x.getNumberOfElements()).isEqualTo(1).isEqualTo(Ints.saturatedCast( - targetManagement.countTargetByFilters(null, "%targ-A%", setA.getId(), Boolean.FALSE, null))); - - x = targetManagement.findTargetByFilters(pageReq, unknown, null, null, Boolean.FALSE, null); - assertThat(x.getNumberOfElements()).isEqualTo(397).isEqualTo( - Ints.saturatedCast(targetManagement.countTargetByFilters(unknown, null, null, Boolean.FALSE, null))); - - x = targetManagement.findTargetByFilters(pageReq, unknown, null, null, Boolean.FALSE, targTagB.getName(), - targTagD.getName()); - assertThat(x.getNumberOfElements()).isEqualTo(198).isEqualTo(Ints.saturatedCast(targetManagement - .countTargetByFilters(unknown, null, null, Boolean.FALSE, targTagB.getName(), targTagD.getName()))); - - x = targetManagement.findTargetByFilters(pageReq, unknown, null, setA.getId(), Boolean.FALSE, null); - assertThat(x.getNumberOfElements()).isEqualTo(0).isEqualTo(Ints.saturatedCast( - targetManagement.countTargetByFilters(unknown, null, setA.getId(), Boolean.FALSE, null))); - - x = targetManagement.findTargetByFilters(pageReq, unknown, "%targ-A%", null, Boolean.FALSE, null); - assertThat(x.getNumberOfElements()).isEqualTo(99).isEqualTo(Ints - .saturatedCast(targetManagement.countTargetByFilters(unknown, "%targ-A%", null, Boolean.FALSE, null))); - - x = targetManagement.findTargetByFilters(pageReq, unknown, "%targ-B%", null, Boolean.FALSE, targTagD.getName()); - assertThat(x.getNumberOfElements()).isEqualTo(99).isEqualTo(Ints.saturatedCast( - targetManagement.countTargetByFilters(unknown, "%targ-B%", null, Boolean.FALSE, targTagD.getName()))); - - x = targetManagement.findTargetByFilters(pageReq, unknown, null, null, Boolean.FALSE, targTagD.getName()); - assertThat(x.getNumberOfElements()).isEqualTo(198).isEqualTo(Ints.saturatedCast( - targetManagement.countTargetByFilters(unknown, null, null, Boolean.FALSE, targTagD.getName()))); - - x = targetManagement.findTargetByFilters(pageReq, pending, null, null, Boolean.FALSE, null); - assertThat(x.getNumberOfElements()).isEqualTo(3).isEqualTo( - Ints.saturatedCast(targetManagement.countTargetByFilters(pending, null, null, Boolean.FALSE, null))); - - x = targetManagement.findTargetByFilters(pageReq, pending, null, setA.getId(), Boolean.FALSE, null); - assertThat(x.getNumberOfElements()).isEqualTo(3).isEqualTo(Ints.saturatedCast( - targetManagement.countTargetByFilters(pending, null, setA.getId(), Boolean.FALSE, null))); - - x = targetManagement.findTargetByFilters(pageReq, pending, "%targ-A%", setA.getId(), Boolean.FALSE, null); - assertThat(x.getNumberOfElements()).isEqualTo(1).isEqualTo(Ints.saturatedCast( - targetManagement.countTargetByFilters(pending, "%targ-A%", setA.getId(), Boolean.FALSE, null))); - - x = targetManagement.findTargetByFilters(pageReq, pending, "%targ-B%", setA.getId(), Boolean.FALSE, - targTagD.getName()); - assertThat(x.getNumberOfElements()).isEqualTo(1).isEqualTo(Ints.saturatedCast(targetManagement - .countTargetByFilters(pending, "%targ-B%", setA.getId(), Boolean.FALSE, targTagD.getName()))); - - x = targetManagement.findTargetByFilters(pageReq, pending, null, setA.getId(), Boolean.FALSE, - targTagD.getName()); - assertThat(x.getNumberOfElements()).isEqualTo(2).isEqualTo(Ints.saturatedCast( - targetManagement.countTargetByFilters(pending, null, setA.getId(), Boolean.FALSE, targTagD.getName()))); - - x = targetManagement.findTargetByFilters(pageReq, pending, null, null, Boolean.FALSE, targTagD.getName()); - assertThat(x.getNumberOfElements()).isEqualTo(2).isEqualTo(Ints.saturatedCast( - targetManagement.countTargetByFilters(pending, null, null, Boolean.FALSE, targTagD.getName()))); - - // Both status: 2 pending and 198 unknown - assertThat(targetManagement.findTargetByFilters(pageReq, both, null, null, Boolean.FALSE, targTagD.getName()) - .getNumberOfElements()).isEqualTo(200).isEqualTo(Ints.saturatedCast( - targetManagement.countTargetByFilters(both, null, null, Boolean.FALSE, targTagD.getName()))); + assertThat(targetManagement.findAllTargetIdsByFilters(pageReq, pending, null, installedSet.getId(), + Boolean.FALSE, new String[0])).as("has number of elements").hasSize(1) + .as("and contains the following elements").containsExactly(expectedIdName) + .as("and NAMED filter query returns the same result").containsAll(targetManagement + .findAllTargetIdsByTargetFilterQuery(pageReq, new TargetFilterQuery("test", query))); + + } + + @Step + private void verifyThat200targetsWithGivenTagAreInStatusPendingorUnknown(final TargetTag targTagW, + final List both, final List expected) { + final List expectedIdNames = convertToIdNames(expected); + + final String query = "(updatestatus==pending or updatestatus==unknown) and tag==" + targTagW.getName(); + + assertThat(targetManagement.findTargetByFilters(pageReq, both, null, null, Boolean.FALSE, targTagW.getName()) + .getContent()).as("has number of elements").hasSize(200) + .as("that number is also returned by count query") + .hasSize(Ints.saturatedCast(targetManagement.countTargetByFilters(both, null, null, + Boolean.FALSE, targTagW.getName()))) + .as("and contains the following elements").containsAll(expected) + .as("and filter query returns the same result") + .containsAll(targetManagement.findTargetsAll(query, pageReq).getContent()) + .as("and NAMED filter query returns the same result").containsAll(targetManagement + .findTargetsAll(new TargetFilterQuery("test", query), pageReq).getContent()); + + assertThat(targetManagement.findAllTargetIdsByFilters(pageReq, both, null, null, Boolean.FALSE, + targTagW.getName())).as("has number of elements").hasSize(200).as("and contains the following elements") + .containsAll(expectedIdNames).as("and NAMED filter query returns the same result") + .containsAll(targetManagement.findAllTargetIdsByTargetFilterQuery(pageReq, + new TargetFilterQuery("test", query))); + } + + private static List convertToIdNames(final List expected) { + return expected.stream() + .map(target -> new TargetIdName(target.getId(), target.getControllerId(), target.getName())) + .collect(Collectors.toList()); + } + + private static TargetIdName convertToIdName(final Target target) { + return new TargetIdName(target.getId(), target.getControllerId(), target.getName()); + } + + @Step + private void verifyThat2TargetsWithGivenTagAreInPending(final TargetTag targTagW, + final List pending, final List expected) { + final List expectedIdNames = convertToIdNames(expected); + final String query = "updatestatus==pending and tag==" + targTagW.getName(); + + assertThat(targetManagement.findTargetByFilters(pageReq, pending, null, null, Boolean.FALSE, targTagW.getName()) + .getContent()).as("has number of elements").hasSize(2) + .as("that number is also returned by count query") + .hasSize(Ints.saturatedCast(targetManagement.countTargetByFilters(pending, null, null, + Boolean.FALSE, targTagW.getName()))) + .as("and contains the following elements").containsAll(expected) + .as("and filter query returns the same result") + .containsAll(targetManagement.findTargetsAll(query, pageReq).getContent()) + .as("and NAMED filter query returns the same result").containsAll(targetManagement + .findTargetsAll(new TargetFilterQuery("test", query), pageReq).getContent()); + + assertThat(targetManagement.findAllTargetIdsByFilters(pageReq, pending, null, null, Boolean.FALSE, + targTagW.getName())).as("has number of elements").hasSize(2).as("and contains the following elements") + .containsAll(expectedIdNames).as("and NAMED filter query returns the same result") + .containsAll(targetManagement.findAllTargetIdsByTargetFilterQuery(pageReq, + new TargetFilterQuery("test", query))); + } + + @Step + private void verifyThat2TargetsWithGivenTagAndDSIsInPending(final TargetTag targTagW, final DistributionSet setA, + final List pending, final List expected) { + final List expectedIdNames = convertToIdNames(expected); + final String query = "updatestatus==pending and (assignedds.name==" + setA.getName() + " or installedds.name==" + + setA.getName() + ") and tag==" + targTagW.getName(); + + assertThat(targetManagement + .findTargetByFilters(pageReq, pending, null, setA.getId(), Boolean.FALSE, targTagW.getName()) + .getContent()).as("has number of elements").hasSize(2) + .as("that number is also returned by count query") + .hasSize(Ints.saturatedCast(targetManagement.countTargetByFilters(pending, null, setA.getId(), + Boolean.FALSE, targTagW.getName()))) + .as("and contains the following elements").containsAll(expected) + .as("and filter query returns the same result") + .containsAll(targetManagement.findTargetsAll(query, pageReq).getContent()) + .as("and NAMED filter query returns the same result").containsAll(targetManagement + .findTargetsAll(new TargetFilterQuery("test", query), pageReq).getContent()); + + assertThat(targetManagement.findAllTargetIdsByFilters(pageReq, pending, null, null, Boolean.FALSE, + targTagW.getName())).as("has number of elements").hasSize(2).as("and contains the following elements") + .containsAll(expectedIdNames).as("and NAMED filter query returns the same result") + .containsAll(targetManagement.findAllTargetIdsByTargetFilterQuery(pageReq, + new TargetFilterQuery("test", query))); + } + + @Step + private void verifyThat1TargetWithGivenNameOrDescAndTagAndDSIsInPending(final TargetTag targTagW, + final DistributionSet setA, final List pending, final Target expected) { + final TargetIdName expectedIdName = convertToIdName(expected); + final String query = "updatestatus==pending and (assignedds.name==" + setA.getName() + " or installedds.name==" + + setA.getName() + ") and (name==*targ-B* or description==*targ-B*) and tag==" + targTagW.getName(); + + assertThat(targetManagement + .findTargetByFilters(pageReq, pending, "%targ-B%", setA.getId(), Boolean.FALSE, targTagW.getName()) + .getContent()).as("has number of elements").hasSize(1) + .as("that number is also returned by count query") + .hasSize(Ints.saturatedCast(targetManagement.countTargetByFilters(pending, "%targ-B%", + setA.getId(), Boolean.FALSE, targTagW.getName()))) + .as("and contains the following elements").containsExactly(expected) + .as("and filter query returns the same result") + .containsAll(targetManagement.findTargetsAll(query, pageReq).getContent()) + .as("and NAMED filter query returns the same result").containsAll(targetManagement + .findTargetsAll(new TargetFilterQuery("test", query), pageReq).getContent()); + + assertThat(targetManagement.findAllTargetIdsByFilters(pageReq, pending, "%targ-B%", setA.getId(), Boolean.FALSE, + targTagW.getName())).as("has number of elements").hasSize(1).as("and contains the following elements") + .containsExactly(expectedIdName).as("and NAMED filter query returns the same result") + .containsAll(targetManagement.findAllTargetIdsByTargetFilterQuery(pageReq, + new TargetFilterQuery("test", query))); + } + + @Step + private void verifyThat1TargetWithGivenNameOrDescAndDSIsInPending(final DistributionSet setA, + final List pending, final Target expected) { + final TargetIdName expectedIdName = convertToIdName(expected); + final String query = "updatestatus==pending and (assignedds.name==" + setA.getName() + " or installedds.name==" + + setA.getName() + ") and (name==*targ-A* or description==*targ-A*)"; + + assertThat(targetManagement + .findTargetByFilters(pageReq, pending, "%targ-A%", setA.getId(), Boolean.FALSE, new String[0]) + .getContent()).as("has number of elements").hasSize(1) + .as("that number is also returned by count query") + .hasSize(Ints.saturatedCast(targetManagement.countTargetByFilters(pending, "%targ-A%", + setA.getId(), Boolean.FALSE, new String[0]))) + .as("and contains the following elements").containsExactly(expected) + .as("and filter query returns the same result") + .containsAll(targetManagement.findTargetsAll(query, pageReq).getContent()) + .as("and NAMED filter query returns the same result").containsAll(targetManagement + .findTargetsAll(new TargetFilterQuery("test", query), pageReq).getContent()); + + assertThat(targetManagement.findAllTargetIdsByFilters(pageReq, pending, "%targ-A%", setA.getId(), Boolean.FALSE, + new String[0])).as("has number of elements").hasSize(1).as("and contains the following elements") + .containsExactly(expectedIdName).as("and NAMED filter query returns the same result") + .containsAll(targetManagement.findAllTargetIdsByTargetFilterQuery(pageReq, + new TargetFilterQuery("test", query))); + } + + @Step + private void verifyThat3TargetsWithGivenDSAreInPending(final DistributionSet setA, + final List pending, final List expected) { + final List expectedIdNames = convertToIdNames(expected); + final String query = "updatestatus==pending and (assignedds.name==" + setA.getName() + " or installedds.name==" + + setA.getName() + ")"; + + assertThat(targetManagement + .findTargetByFilters(pageReq, pending, null, setA.getId(), Boolean.FALSE, new String[0]).getContent()) + .as("has number of elements").hasSize(3).as("that number is also returned by count query") + .hasSize(Ints.saturatedCast(targetManagement.countTargetByFilters(pending, null, setA.getId(), + Boolean.FALSE, new String[0]))) + .as("and contains the following elements").containsAll(expected) + .as("and filter query returns the same result") + .containsAll(targetManagement.findTargetsAll(query, pageReq).getContent()) + .as("and NAMED filter query returns the same result").containsAll(targetManagement + .findTargetsAll(new TargetFilterQuery("test", query), pageReq).getContent()); + + assertThat(targetManagement.findAllTargetIdsByFilters(pageReq, pending, null, setA.getId(), Boolean.FALSE, + new String[0])).as("has number of elements").hasSize(3).as("and contains the following elements") + .containsAll(expectedIdNames).as("and NAMED filter query returns the same result") + .containsAll(targetManagement.findAllTargetIdsByTargetFilterQuery(pageReq, + new TargetFilterQuery("test", query))); + } + + @Step + private void verifyThat3TargetsAreInStatusPending(final List pending, + final List expected) { + final List expectedIdNames = convertToIdNames(expected); + final String query = "updatestatus==pending"; + + assertThat(targetManagement.findTargetByFilters(pageReq, pending, null, null, Boolean.FALSE, new String[0]) + .getContent()).as("has number of elements").hasSize(3) + .as("that number is also returned by count query") + .hasSize(Ints.saturatedCast(targetManagement.countTargetByFilters(pending, null, null, + Boolean.FALSE, new String[0]))) + .as("and contains the following elements").containsAll(expected) + .as("and filter query returns the same result") + .containsAll(targetManagement.findTargetsAll(query, pageReq).getContent()) + .as("and NAMED filter query returns the same result").containsAll(targetManagement + .findTargetsAll(new TargetFilterQuery("test", query), pageReq).getContent()); + + assertThat( + targetManagement.findAllTargetIdsByFilters(pageReq, pending, null, null, Boolean.FALSE, new String[0])) + .as("has number of elements").hasSize(3).as("and contains the following elements") + .containsAll(expectedIdNames).as("and NAMED filter query returns the same result") + .containsAll(targetManagement.findAllTargetIdsByTargetFilterQuery(pageReq, + new TargetFilterQuery("test", query))); + } + + @Step + private void verifyThat99TargetsWithGivenNameOrDescAndTagAreInStatusUnknown(final TargetTag targTagW, + final List unknown, final List expected) { + final List expectedIdNames = convertToIdNames(expected); + final String query = "updatestatus==unknown and (name==*targ-B* or description==*targ-B*) and tag==" + + targTagW.getName(); + + assertThat(targetManagement + .findTargetByFilters(pageReq, unknown, "%targ-B%", null, Boolean.FALSE, targTagW.getName()) + .getContent()).as("has number of elements").hasSize(99) + .as("that number is also returned by count query") + .hasSize(Ints.saturatedCast(targetManagement.countTargetByFilters(unknown, "%targ-B%", null, + Boolean.FALSE, targTagW.getName()))) + .as("and contains the following elements").containsAll(expected) + .as("and filter query returns the same result") + .containsAll(targetManagement.findTargetsAll(query, pageReq).getContent()) + .as("and NAMED filter query returns the same result").containsAll(targetManagement + .findTargetsAll(new TargetFilterQuery("test", query), pageReq).getContent()); + + assertThat(targetManagement.findAllTargetIdsByFilters(pageReq, unknown, "%targ-B%", null, Boolean.FALSE, + targTagW.getName())).as("has number of elements").hasSize(99).as("and contains the following elements") + .containsAll(expectedIdNames).as("and NAMED filter query returns the same result") + .containsAll(targetManagement.findAllTargetIdsByTargetFilterQuery(pageReq, + new TargetFilterQuery("test", query))); + } + + @Step + private void verifyThat99TargetsWithNameOrDescriptionAreInGivenStatus(final List unknown, + final List expected) { + final List expectedIdNames = convertToIdNames(expected); + final String query = "updatestatus==unknown and (name==*targ-A* or description==*targ-A*)"; + + assertThat(targetManagement + .findTargetByFilters(pageReq, unknown, "%targ-A%", null, Boolean.FALSE, new String[0]).getContent()) + .as("has number of elements").hasSize(99).as("that number is also returned by count query") + .hasSize(Ints.saturatedCast(targetManagement.countTargetByFilters(unknown, "%targ-A%", null, + Boolean.FALSE, new String[0]))) + .as("and contains the following elements").containsAll(expected) + .as("and filter query returns the same result") + .containsAll(targetManagement.findTargetsAll(query, pageReq).getContent()) + .as("and NAMED filter query returns the same result").containsAll(targetManagement + .findTargetsAll(new TargetFilterQuery("test", query), pageReq).getContent()); + + assertThat(targetManagement.findAllTargetIdsByFilters(pageReq, unknown, "%targ-A%", null, Boolean.FALSE, + new String[0])).as("has number of elements").hasSize(99).as("and contains the following elements") + .containsAll(expectedIdNames).as("and NAMED filter query returns the same result") + .containsAll(targetManagement.findAllTargetIdsByTargetFilterQuery(pageReq, + new TargetFilterQuery("test", query))); + } + + @Step + private void verfyThat0TargetsAreInStatusUnknownAndHaveDSAssigned(final DistributionSet setA, + final List unknown) { + final String query = "updatestatus==unknown and (assignedds.name==" + setA.getName() + " or installedds.name==" + + setA.getName() + ")"; + + assertThat(targetManagement + .findTargetByFilters(pageReq, unknown, null, setA.getId(), Boolean.FALSE, new String[0]).getContent()) + .as("has number of elements").hasSize(0).as("that number is also returned by count query") + .hasSize(Ints.saturatedCast(targetManagement.countTargetByFilters(unknown, null, setA.getId(), + Boolean.FALSE, new String[0]))) + .as("and filter query returns the same result") + .hasSize(targetManagement.findTargetsAll(query, pageReq).getContent().size()) + .as("and NAMED filter query returns the same result").hasSize(targetManagement + .findTargetsAll(new TargetFilterQuery("test", query), pageReq).getContent().size()); + + assertThat(targetManagement.findAllTargetIdsByFilters(pageReq, unknown, null, setA.getId(), Boolean.FALSE, + new String[0])).as("has number of elements").hasSize(0) + .as("and NAMED filter query returns the same result").containsAll(targetManagement + .findAllTargetIdsByTargetFilterQuery(pageReq, new TargetFilterQuery("test", query))); + } + + @Step + private void verifyThat198TargetsAreInStatusUnknownAndHaveGivenTags(final TargetTag targTagY, + final TargetTag targTagW, final List unknown, final List expected) { + final List expectedIdNames = convertToIdNames(expected); + final String query = "updatestatus==unknown and (tag==" + targTagY.getName() + " or tag==" + targTagW.getName() + + ")"; + + assertThat(targetManagement.findTargetByFilters(pageReq, unknown, null, null, Boolean.FALSE, targTagY.getName(), + targTagW.getName()).getContent()).as("has number of elements").hasSize(198) + .as("that number is also returned by count query") + .hasSize(Ints.saturatedCast(targetManagement.countTargetByFilters(unknown, null, null, + Boolean.FALSE, targTagY.getName(), targTagW.getName()))) + .as("and contains the following elements").containsAll(expected) + .as("and filter query returns the same result") + .containsAll(targetManagement.findTargetsAll(query, pageReq).getContent()) + .as("and NAMED filter query returns the same result").containsAll(targetManagement + .findTargetsAll(new TargetFilterQuery("test", query), pageReq).getContent()); + + assertThat(targetManagement.findAllTargetIdsByFilters(pageReq, unknown, null, null, Boolean.FALSE, + targTagY.getName(), targTagW.getName())).as("has number of elements").hasSize(198) + .as("and contains the following elements").containsAll(expectedIdNames) + .as("and NAMED filter query returns the same result").containsAll(targetManagement + .findAllTargetIdsByTargetFilterQuery(pageReq, new TargetFilterQuery("test", query))); + } + + @Step + private void verifyThat397TargetsAreInStatusUnknown(final List unknown, + final List expected) { + final List expectedIdNames = convertToIdNames(expected); + final String query = "updatestatus==unknown"; + + assertThat(targetManagement.findTargetByFilters(pageReq, unknown, null, null, Boolean.FALSE, new String[0]) + .getContent()).as("has number of elements").hasSize(397) + .as("that number is also returned by count query") + .hasSize(Ints.saturatedCast(targetManagement.countTargetByFilters(unknown, null, null, + Boolean.FALSE, new String[0]))) + .as("and contains the following elements").containsAll(expected) + .as("and filter query returns the same result") + .containsAll(targetManagement.findTargetsAll(query, pageReq).getContent()) + .as("and NAMED filter query returns the same result").containsAll(targetManagement + .findTargetsAll(new TargetFilterQuery("test", query), pageReq).getContent()); + + assertThat( + targetManagement.findAllTargetIdsByFilters(pageReq, unknown, null, null, Boolean.FALSE, new String[0])) + .as("has number of elements").hasSize(397).as("and contains the following elements") + .containsAll(expectedIdNames).as("and NAMED filter query returns the same result") + .containsAll(targetManagement.findAllTargetIdsByTargetFilterQuery(pageReq, + new TargetFilterQuery("test", query))); + } + + @Step + private void verifyThat1TargetWithDescOrNameHasDS(final DistributionSet setA, final Target expected) { + final TargetIdName expectedIdName = convertToIdName(expected); + final String query = "(name==*targ-A* or description==*targ-A*) and (assignedds.name==" + setA.getName() + + " or installedds.name==" + setA.getName() + ")"; + + assertThat(targetManagement + .findTargetByFilters(pageReq, null, "%targ-A%", setA.getId(), Boolean.FALSE, new String[0]) + .getContent()).as("has number of elements").hasSize(1) + .as("that number is also returned by count query") + .hasSize(Ints.saturatedCast(targetManagement.countTargetByFilters(null, "%targ-A%", + setA.getId(), Boolean.FALSE, new String[0]))) + .as("and contains the following elements").containsExactly(expected) + .as("and filter query returns the same result") + .containsAll(targetManagement.findTargetsAll(query, pageReq).getContent()) + .as("and NAMED filter query returns the same result").containsAll(targetManagement + .findTargetsAll(new TargetFilterQuery("test", query), pageReq).getContent()); + + assertThat(targetManagement.findAllTargetIdsByFilters(pageReq, null, "%targ-A%", setA.getId(), Boolean.FALSE, + new String[0])).as("has number of elements").hasSize(1).as("and contains the following elements") + .containsExactly(expectedIdName).as("and NAMED filter query returns the same result") + .containsAll(targetManagement.findAllTargetIdsByTargetFilterQuery(pageReq, + new TargetFilterQuery("test", query))); + } + + @Step + private void verifyThat3TargetsHaveDSAssigned(final DistributionSet setA, final List expected) { + final List expectedIdNames = convertToIdNames(expected); + final String query = "assignedds.name==" + setA.getName() + " or installedds.name==" + setA.getName(); + + assertThat(targetManagement.findTargetByFilters(pageReq, null, null, setA.getId(), Boolean.FALSE, new String[0]) + .getContent()).as("has number of elements").hasSize(3) + .as("that number is also returned by count query") + .hasSize(Ints.saturatedCast(targetManagement.countTargetByFilters(null, null, setA.getId(), + Boolean.FALSE, new String[0]))) + .as("and contains the following elements").containsAll(expected) + .as("and filter query returns the same result") + .containsAll(targetManagement.findTargetsAll(query, pageReq).getContent()) + .as("and NAMED filter query returns the same result").containsAll(targetManagement + .findTargetsAll(new TargetFilterQuery("test", query), pageReq).getContent()); + + assertThat(targetManagement.findAllTargetIdsByFilters(pageReq, null, null, setA.getId(), Boolean.FALSE, + new String[0])).as("has number of elements").hasSize(3).as("and contains the following elements") + .containsAll(expectedIdNames).as("and NAMED filter query returns the same result") + .containsAll(targetManagement.findAllTargetIdsByTargetFilterQuery(pageReq, + new TargetFilterQuery("test", query))); + } + + @Step + private void verifyThat0TargetsWithNameOrdescAndDSHaveTag(final TargetTag targTagX, final DistributionSet setA) { + final String query = "(name==*targ-C* or description==*targ-C*) and tag==" + targTagX.getName() + + " and (assignedds.name==" + setA.getName() + " or installedds.name==" + setA.getName() + ")"; + assertThat(targetManagement + .findTargetByFilters(pageReq, null, "%targ-C%", setA.getId(), Boolean.FALSE, targTagX.getName()) + .getContent()).as("has number of elements").hasSize(0) + .as("that number is also returned by count query") + .hasSize(Ints.saturatedCast(targetManagement.countTargetByFilters(null, "%targ-C%", + setA.getId(), Boolean.FALSE, targTagX.getName()))) + .as("and filter query returns the same result") + .hasSize(targetManagement.findTargetsAll(query, pageReq).getContent().size()) + .as("and NAMED filter query returns the same result").hasSize(targetManagement + .findTargetsAll(new TargetFilterQuery("test", query), pageReq).getContent().size()); + + assertThat(targetManagement.findAllTargetIdsByFilters(pageReq, null, "%targ-C%", setA.getId(), Boolean.FALSE, + targTagX.getName())).as("has number of elements").hasSize(0) + .as("and NAMED filter query returns the same result").containsAll(targetManagement + .findAllTargetIdsByTargetFilterQuery(pageReq, new TargetFilterQuery("test", query))); + } + + @Step + private void verifyThat0TargetsWithTagAndDescOrNameHasDS(final TargetTag targTagW, final DistributionSet setA) { + final String query = "(name==*targ-A* or description==*targ-A*) and tag==" + targTagW.getName() + + " and (assignedds.name==" + setA.getName() + " or installedds.name==" + setA.getName() + ")"; + assertThat(targetManagement + .findTargetByFilters(pageReq, null, "%targ-A%", setA.getId(), Boolean.FALSE, targTagW.getName()) + .getContent()).as("has number of elements").hasSize(0) + .as("that number is also returned by count query") + .hasSize(Ints.saturatedCast(targetManagement.countTargetByFilters(null, "%targ-A%", + setA.getId(), Boolean.FALSE, targTagW.getName()))) + .as("and filter query returns the same result") + .hasSize(targetManagement.findTargetsAll(query, pageReq).getContent().size()) + .as("and NAMED filter query returns the same result").hasSize(targetManagement + .findTargetsAll(new TargetFilterQuery("test", query), pageReq).getContent().size()); + + assertThat(targetManagement.findAllTargetIdsByFilters(pageReq, null, "%targ-A%", setA.getId(), Boolean.FALSE, + targTagW.getName())).as("has number of elements").hasSize(0) + .as("and NAMED filter query returns the same result").containsAll(targetManagement + .findAllTargetIdsByTargetFilterQuery(pageReq, new TargetFilterQuery("test", query))); + } + + @Step + private void verifyThat1TargetHasTagHasDescOrNameAndDs(final TargetTag targTagW, final DistributionSet setA, + final Target expected) { + final TargetIdName expectedIdName = convertToIdName(expected); + final String query = "(name==*targ-c* or description==*targ-C*) and tag==" + targTagW.getName() + + " and (assignedds.name==" + setA.getName() + " or installedds.name==" + setA.getName() + ")"; + assertThat(targetManagement + .findTargetByFilters(pageReq, null, "%targ-C%", setA.getId(), Boolean.FALSE, targTagW.getName()) + .getContent()).as("has number of elements").hasSize(1) + .as("that number is also returned by count query") + .hasSize(Ints.saturatedCast(targetManagement.countTargetByFilters(null, "%targ-C%", + setA.getId(), Boolean.FALSE, targTagW.getName()))) + .as("and contains the following elements").containsExactly(expected) + .as("and filter query returns the same result") + .containsAll(targetManagement.findTargetsAll(query, pageReq).getContent()) + .as("and NAMED filter query returns the same result").containsAll(targetManagement + .findTargetsAll(new TargetFilterQuery("test", query), pageReq).getContent()); + + assertThat(targetManagement.findAllTargetIdsByFilters(pageReq, null, "%targ-C%", setA.getId(), Boolean.FALSE, + targTagW.getName())).as("has number of elements").hasSize(1).as("and contains the following elements") + .containsExactly(expectedIdName).as("and NAMED filter query returns the same result") + .containsAll(targetManagement.findAllTargetIdsByTargetFilterQuery(pageReq, + new TargetFilterQuery("test", query))); + } + + @Step + private void verifyThat100TargetsContainsGivenTextAndHaveTagAssigned(final TargetTag targTagY, + final TargetTag targTagW, final List expected) { + final List expectedIdNames = convertToIdNames(expected); + final String query = "(name==*targ-B* or description==*targ-B*) and (tag==" + targTagY.getName() + " or tag==" + + targTagW.getName() + ")"; + assertThat(targetManagement.findTargetByFilters(pageReq, null, "%targ-B%", null, Boolean.FALSE, + targTagY.getName(), targTagW.getName()).getContent()).as("has number of elements").hasSize(100) + .as("that number is also returned by count query") + .hasSize(Ints.saturatedCast(targetManagement.countTargetByFilters(null, "%targ-B%", null, + Boolean.FALSE, targTagY.getName(), targTagW.getName()))) + .as("and contains the following elements").containsAll(expected) + .as("and filter query returns the same result") + .containsAll(targetManagement.findTargetsAll(query, pageReq).getContent()) + .as("and NAMED filter query returns the same result").containsAll(targetManagement + .findTargetsAll(new TargetFilterQuery("test", query), pageReq).getContent()); + + assertThat(targetManagement.findAllTargetIdsByFilters(pageReq, null, "%targ-B%", null, Boolean.FALSE, + targTagY.getName(), targTagW.getName())).as("has number of elements").hasSize(100) + .as("and contains the following elements").containsAll(expectedIdNames) + .as("and NAMED filter query returns the same result").containsAll(targetManagement + .findAllTargetIdsByTargetFilterQuery(pageReq, new TargetFilterQuery("test", query))); + + } + + @SafeVarargs + private final List concat(final List... targets) { + final List result = new ArrayList<>(); + Arrays.asList(targets).forEach(result::addAll); + return result; + } + + @Step + private void verifyThat200TargetsHaveTagD(final TargetTag targTagD, final List expected) { + final List expectedIdNames = convertToIdNames(expected); + final String query = "tag==" + targTagD.getName(); + assertThat(targetManagement.findTargetByFilters(pageReq, null, null, null, Boolean.FALSE, targTagD.getName()) + .getContent()).as("Expected number of results is").hasSize(200) + .as("and is expected number of results is equal to ") + .hasSize(Ints.saturatedCast(targetManagement.countTargetByFilters(null, null, null, + Boolean.FALSE, targTagD.getName()))) + .as("and contains the following elements").containsAll(expected) + .as("and filter query returns the same result") + .containsAll(targetManagement.findTargetsAll(query, pageReq).getContent()) + .as("and NAMED filter query returns the same result").containsAll(targetManagement + .findTargetsAll(new TargetFilterQuery("test", query), pageReq).getContent()); + + assertThat(targetManagement.findAllTargetIdsByFilters(pageReq, null, null, null, Boolean.FALSE, + targTagD.getName())).as("has number of elements").hasSize(200).as("and contains the following elements") + .containsAll(expectedIdNames).as("and NAMED filter query returns the same result") + .containsAll(targetManagement.findAllTargetIdsByTargetFilterQuery(pageReq, + new TargetFilterQuery("test", query))); + + } + + @Step + private void verifyThatRepositoryContains400Targets() { + assertThat(targetManagement.findTargetByFilters(pageReq, null, null, null, null, new String[0]).getContent()) + .as("Overall we expect that many targets in the repository").hasSize(400) + .as("which is also reflected by repository count") + .hasSize(Ints.saturatedCast(targetManagement.countTargetsAll())) + .as("which is also reflected by call without specification") + .containsAll(targetManagement.findTargetsAll(pageReq).getContent()); } - // TODO kaizimmerm: add filter tests @Test @Description("Tests the correct order of targets based on selected distribution set. The system expects to have an order based on installed, assigned DS.") public void targetSearchWithVariousFilterCombinationsAndOrderByDistributionSet() { @@ -200,14 +688,14 @@ public class TargetManagementSearchTest extends AbstractIntegrationTest { final DistributionSet ds = TestDataUtil.generateDistributionSet("a", softwareManagement, distributionSetManagement); - targAssigned = deploymentManagement.assignDistributionSet(ds, targAssigned).getAssignedTargets(); - targInstalled = deploymentManagement.assignDistributionSet(ds, targInstalled).getAssignedTargets(); + targAssigned = deploymentManagement.assignDistributionSet(ds, targAssigned).getAssignedEntity(); + targInstalled = deploymentManagement.assignDistributionSet(ds, targInstalled).getAssignedEntity(); targInstalled = sendUpdateActionStatusToTargets(ds, targInstalled, Status.FINISHED, "installed"); final Slice result = targetManagement.findTargetsAllOrderByLinkedDistributionSet(pageReq, ds.getId(), - null, null, null, Boolean.FALSE, null); + null, null, null, Boolean.FALSE, new String[0]); - final Comparator byId = (e1, e2) -> Long.compare(e2.getId(), e1.getId()); + final Comparator byId = (e1, e2) -> Long.compare(e2.getId(), e1.getId()); assertThat(result.getNumberOfElements()).isEqualTo(9); final List expected = new ArrayList(); @@ -222,6 +710,113 @@ public class TargetManagementSearchTest extends AbstractIntegrationTest { } + @Test + @Description("Verfies that targets with given assigned DS are returned from repository.") + public void findTargetByAssignedDistributionSet() { + final DistributionSet assignedSet = TestDataUtil.generateDistributionSet("", softwareManagement, + distributionSetManagement); + targetManagement.createTargets(TestDataUtil.generateTargets(10, "unassigned")); + List assignedtargets = targetManagement.createTargets(TestDataUtil.generateTargets(10, "assigned")); + + deploymentManagement.assignDistributionSet(assignedSet, assignedtargets); + + // get final updated version of targets + assignedtargets = targetManagement.findTargetByControllerID( + assignedtargets.stream().map(target -> target.getControllerId()).collect(Collectors.toList())); + + assertThat(targetManagement.findTargetByAssignedDistributionSet(assignedSet.getId(), pageReq)) + .as("Contains the assigned targets").containsAll(assignedtargets) + .as("and that means the following expected amount").hasSize(10); + + } + + @Test + @Description("Verfies that targets with given assigned DS and additonal specification are returned from repository.") + public void findTargetByAssignedDistributionSetWithAdditonalSpecification() { + final DistributionSet assignedSet = TestDataUtil.generateDistributionSet("", softwareManagement, + distributionSetManagement); + final DistributionSet installedSet = TestDataUtil.generateDistributionSet("another", softwareManagement, + distributionSetManagement); + targetManagement.createTargets(TestDataUtil.generateTargets(10, "unassigned")); + List assignedtargets = targetManagement.createTargets(TestDataUtil.generateTargets(10, "assigned")); + + // set on installed and assign another one + deploymentManagement.assignDistributionSet(installedSet, assignedtargets).getActions().forEach(actionId -> { + final Action action = deploymentManagement.findActionWithDetails(actionId); + action.setStatus(Status.FINISHED); + controllerManagament.addUpdateActionStatus( + new ActionStatus(action, Status.FINISHED, System.currentTimeMillis(), "message"), action); + }); + deploymentManagement.assignDistributionSet(assignedSet, assignedtargets); + + assignedtargets = targetManagement.findTargetByControllerID( + assignedtargets.stream().map(target -> target.getControllerId()).collect(Collectors.toList())); + + assertThat(targetManagement.findTargetByAssignedDistributionSet(assignedSet.getId(), + TargetSpecifications.hasInstalledDistributionSet(installedSet.getId()), pageReq)) + .as("Contains the assigned targets").containsAll(assignedtargets) + .as("and that means the following expected amount").hasSize(10); + } + + @Test + @Description("Verfies that targets with given installed DS are returned from repository.") + public void findTargetByInstalledDistributionSet() { + final DistributionSet assignedSet = TestDataUtil.generateDistributionSet("", softwareManagement, + distributionSetManagement); + final DistributionSet installedSet = TestDataUtil.generateDistributionSet("another", softwareManagement, + distributionSetManagement); + targetManagement.createTargets(TestDataUtil.generateTargets(10, "unassigned")); + List installedtargets = targetManagement.createTargets(TestDataUtil.generateTargets(10, "assigned")); + + // set on installed and assign another one + deploymentManagement.assignDistributionSet(installedSet, installedtargets).getActions().forEach(actionId -> { + final Action action = deploymentManagement.findActionWithDetails(actionId); + action.setStatus(Status.FINISHED); + controllerManagament.addUpdateActionStatus( + new ActionStatus(action, Status.FINISHED, System.currentTimeMillis(), "message"), action); + }); + deploymentManagement.assignDistributionSet(assignedSet, installedtargets); + + // get final updated version of targets + installedtargets = targetManagement.findTargetByControllerID( + installedtargets.stream().map(target -> target.getControllerId()).collect(Collectors.toList())); + + assertThat(targetManagement.findTargetByInstalledDistributionSet(installedSet.getId(), pageReq)) + .as("Contains the assigned targets").containsAll(installedtargets) + .as("and that means the following expected amount").hasSize(10); + + } + + @Test + @Description("Verfies that targets with given installed DS and additonal specification are returned from repository.") + public void findTargetByInstalledDistributionSetWithAdditonalSpecification() { + final DistributionSet assignedSet = TestDataUtil.generateDistributionSet("", softwareManagement, + distributionSetManagement); + final DistributionSet installedSet = TestDataUtil.generateDistributionSet("another", softwareManagement, + distributionSetManagement); + targetManagement.createTargets(TestDataUtil.generateTargets(10, "unassigned")); + List installedtargets = targetManagement.createTargets(TestDataUtil.generateTargets(10, "assigned")); + + // set on installed and assign another one + deploymentManagement.assignDistributionSet(installedSet, installedtargets).getActions().forEach(actionId -> { + final Action action = deploymentManagement.findActionWithDetails(actionId); + action.setStatus(Status.FINISHED); + controllerManagament.addUpdateActionStatus( + new ActionStatus(action, Status.FINISHED, System.currentTimeMillis(), "message"), action); + }); + deploymentManagement.assignDistributionSet(assignedSet, installedtargets); + + // get final updated version of targets + installedtargets = targetManagement.findTargetByControllerID( + installedtargets.stream().map(target -> target.getControllerId()).collect(Collectors.toList())); + + assertThat(targetManagement.findTargetByInstalledDistributionSet(installedSet.getId(), + TargetSpecifications.hasAssignedDistributionSet(assignedSet.getId()), pageReq)) + .as("Contains the assigned targets").containsAll(installedtargets) + .as("and that means the following expected amount").hasSize(10); + + } + private List sendUpdateActionStatusToTargets(final DistributionSet dsA, final Iterable targs, final Status status, final String... msgs) { final List result = new ArrayList(); diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/TargetManagementTest.java b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/TargetManagementTest.java index 20dffde29..1c039c8c8 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/TargetManagementTest.java +++ b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/TargetManagementTest.java @@ -14,6 +14,7 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; +import java.net.URI; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; @@ -29,7 +30,9 @@ import javax.validation.ConstraintViolationException; import org.eclipse.hawkbit.AbstractIntegrationTest; import org.eclipse.hawkbit.TestDataUtil; +import org.eclipse.hawkbit.WithSpringAuthorityRule; import org.eclipse.hawkbit.WithUser; +import org.eclipse.hawkbit.im.authentication.SpPermission; import org.eclipse.hawkbit.repository.exception.EntityAlreadyExistsException; import org.eclipse.hawkbit.repository.exception.TenantNotExistException; import org.eclipse.hawkbit.repository.model.Action; @@ -54,14 +57,45 @@ import ru.yandex.qatools.allure.annotations.Stories; @Stories("Target Management") public class TargetManagementTest extends AbstractIntegrationTest { + @Test + @Description("Ensures that retrieving the target security is only permitted with the necessary permissions.") + public void getTargetSecurityTokenOnlyWithCorrectPermission() throws Exception { + final Target createdTarget = targetManagement.createTarget(new Target("targetWithSecurityToken")); + + // retrieve security token only with READ_TARGET_SEC_TOKEN permission + final String securityTokenWithReadPermission = securityRule.runAs(WithSpringAuthorityRule + .withUser("OnlyTargetReadPermission", false, SpPermission.READ_TARGET_SEC_TOKEN.toString()), () -> { + return createdTarget.getSecurityToken(); + }); + + // retrieve security token as system code execution + final String securityTokenAsSystemCode = systemSecurityContext.runAsSystem(() -> { + return createdTarget.getSecurityToken(); + }); + + // retrieve security token without any permissions + final String securityTokenWithoutPermission = securityRule + .runAs(WithSpringAuthorityRule.withUser("NoPermission", false), () -> { + return createdTarget.getSecurityToken(); + }); + + assertThat(createdTarget.getSecurityToken()).isNotNull(); + assertThat(securityTokenWithReadPermission).isNotNull(); + assertThat(securityTokenAsSystemCode).isNotNull(); + + assertThat(securityTokenWithoutPermission).isNull(); + + } + @Test @Description("Ensures that targets cannot be created e.g. in plug'n play scenarios when tenant does not exists.") @WithUser(tenantId = "tenantWhichDoesNotExists", allSpPermissions = true, autoCreateTenant = false) public void createTargetForTenantWhichDoesNotExistThrowsTenantNotExistException() { try { targetManagement.createTarget(new Target("targetId123")); - fail("tenant not exist"); + fail("should not be possible as the tenant does not exist"); } catch (final TenantNotExistException e) { + // ok } } @@ -206,6 +240,12 @@ public class TargetManagementTest extends AbstractIntegrationTest { } + @Test + @Description("Ensures that repositoy returns null if given controller ID does not exist without exception.") + public void findTargetByControllerIDWithDetailsReturnsNullForNonexisting() { + assertThat(targetManagement.findTargetByControllerIDWithDetails("dsfsdfsdfsd")).as("Expected as").isNull(); + } + @Test @Description("Checks if the EntityAlreadyExistsException is thrown if the targets with the same controller ID are created twice.") public void createMultipleTargetsDuplicate() { @@ -717,4 +757,20 @@ public class TargetManagementTest extends AbstractIntegrationTest { assertThat(25).as("Targets with no tag").isEqualTo(targetsListWithNoTag.size()); } + + @Test + @Description("Tests the a target can be read with only the read target permission") + public void targetCanBeReadWithOnlyReadTargetPermission() throws Exception { + final String knownTargetControllerId = "readTarget"; + controllerManagament.findOrRegisterTargetIfItDoesNotexist(knownTargetControllerId, new URI("http://127.0.0.1")); + + securityRule.runAs(WithSpringAuthorityRule.withUser("bumlux", "READ_TARGET"), () -> { + final Target findTargetByControllerID = targetManagement.findTargetByControllerID(knownTargetControllerId); + assertThat(findTargetByControllerID).isNotNull(); + assertThat(findTargetByControllerID.getTargetInfo()).isNotNull(); + assertThat(findTargetByControllerID.getTargetInfo().getPollStatus()).isNotNull(); + return null; + }); + + } } diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/TenantConfigurationManagementTest.java b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/TenantConfigurationManagementTest.java index 3425c6479..1427df25b 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/TenantConfigurationManagementTest.java +++ b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/TenantConfigurationManagementTest.java @@ -9,6 +9,7 @@ package org.eclipse.hawkbit.repository; import static org.fest.assertions.api.Assertions.assertThat; +import static org.junit.Assert.fail; import java.time.Duration; import java.util.Arrays; @@ -91,13 +92,19 @@ public class TenantConfigurationManagementTest extends AbstractIntegrationTestWi .isEqualTo(value2); } - @Test(expected = TenantConfigurationValidatorException.class) + @Test @Description("Tests that the get configuration throws exception in case the value cannot be automatically converted from String to Boolean") public void wrongTenantConfigurationValueTypeThrowsException() { final TenantConfigurationKey configKey = TenantConfigurationKey.AUTHENTICATION_MODE_HEADER_ENABLED; final String value1 = "thisIsNotABoolean"; + // add value as String - tenantConfigurationManagement.addOrUpdateConfiguration(configKey, value1); + try { + tenantConfigurationManagement.addOrUpdateConfiguration(configKey, value1); + fail("should not have worked as string is not a boolean"); + } catch (final TenantConfigurationValidatorException e) { + + } } @Test @@ -128,46 +135,71 @@ public class TenantConfigurationManagementTest extends AbstractIntegrationTestWi assertThat(tenantConfigurationManagement.getConfigurationValue(configKey, String.class).getValue()).isNull(); } - @Test(expected = TenantConfigurationValidatorException.class) + @Test @Description("Test that an Exception is thrown, when an integer is stored but a string expected.") public void storesIntegerWhenStringIsExpected() { final TenantConfigurationKey configKey = TenantConfigurationKey.AUTHENTICATION_MODE_GATEWAY_SECURITY_TOKEN_NAME; final Integer wrongDataype = 123; - tenantConfigurationManagement.addOrUpdateConfiguration(configKey, wrongDataype); + try { + tenantConfigurationManagement.addOrUpdateConfiguration(configKey, wrongDataype); + fail("should not have worked as integer is not a string"); + } catch (final TenantConfigurationValidatorException e) { + + } } - @Test(expected = TenantConfigurationValidatorException.class) + @Test @Description("Test that an Exception is thrown, when an integer is stored but a boolean expected.") public void storesIntegerWhenBooleanIsExpected() { final TenantConfigurationKey configKey = TenantConfigurationKey.AUTHENTICATION_MODE_GATEWAY_SECURITY_TOKEN_ENABLED; final Integer wrongDataype = 123; - tenantConfigurationManagement.addOrUpdateConfiguration(configKey, wrongDataype); + try { + tenantConfigurationManagement.addOrUpdateConfiguration(configKey, wrongDataype); + fail("should not have worked as integer is not a boolean"); + } catch (final TenantConfigurationValidatorException e) { + + } } - @Test(expected = TenantConfigurationValidatorException.class) + @Test @Description("Test that an Exception is thrown, when an integer is stored as PollingTime.") public void storesIntegerWhenPollingIntervalIsExpected() { final TenantConfigurationKey configKey = TenantConfigurationKey.POLLING_TIME_INTERVAL; final Integer wrongDataype = 123; - tenantConfigurationManagement.addOrUpdateConfiguration(configKey, wrongDataype); + try { + tenantConfigurationManagement.addOrUpdateConfiguration(configKey, wrongDataype); + fail("should not have worked as integer is not a time field"); + } catch (final TenantConfigurationValidatorException e) { + + } } - @Test(expected = TenantConfigurationValidatorException.class) + @Test @Description("Test that an Exception is thrown, when an invalid formatted string is stored as PollingTime.") public void storesWrongFormattedStringAsPollingInterval() { final TenantConfigurationKey configKey = TenantConfigurationKey.POLLING_TIME_INTERVAL; final String wrongFormatted = "wrongFormatted"; - tenantConfigurationManagement.addOrUpdateConfiguration(configKey, wrongFormatted); + try { + tenantConfigurationManagement.addOrUpdateConfiguration(configKey, wrongFormatted); + fail("should not have worked as string is not a time field"); + } catch (final TenantConfigurationValidatorException e) { + + } } - @Test(expected = TenantConfigurationValidatorException.class) + @Test @Description("Test that an Exception is thrown, when an invalid formatted string is stored as PollingTime.") public void storesTooSmallDurationAsPollingInterval() { final TenantConfigurationKey configKey = TenantConfigurationKey.POLLING_TIME_INTERVAL; final String tooSmallDuration = DurationHelper .durationToFormattedString(DurationHelper.getDurationByTimeValues(0, 0, 1)); - tenantConfigurationManagement.addOrUpdateConfiguration(configKey, tooSmallDuration); + try { + tenantConfigurationManagement.addOrUpdateConfiguration(configKey, tooSmallDuration); + fail("should not have worked as string has an invalid format"); + } catch (final TenantConfigurationValidatorException e) { + + } } @Test diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/model/ModelEqualsHashcodeTest.java b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/model/ModelEqualsHashcodeTest.java new file mode 100644 index 000000000..45e56167a --- /dev/null +++ b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/model/ModelEqualsHashcodeTest.java @@ -0,0 +1,102 @@ +/** + * 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 static org.fest.assertions.api.Assertions.assertThat; + +import org.eclipse.hawkbit.AbstractIntegrationTest; +import org.junit.Test; + +import ru.yandex.qatools.allure.annotations.Description; +import ru.yandex.qatools.allure.annotations.Features; +import ru.yandex.qatools.allure.annotations.Stories; + +@Features("Unit Tests - Repository") +@Stories("Repository Model") +public class ModelEqualsHashcodeTest extends AbstractIntegrationTest { + + @Test + @Description("Verfies that different objects even with identical primary key, version and tenant " + + "return different hash codes.") + public void differentEntitiesReturnDifferentHashCodes() { + assertThat(new Action().hashCode()).as("action should have different hashcode than action status") + .isNotEqualTo(new ActionStatus().hashCode()); + assertThat(new DistributionSet().hashCode()) + .as("Distribution set should have different hashcode than software module") + .isNotEqualTo(new SoftwareModule().hashCode()); + assertThat(new DistributionSet().hashCode()) + .as("Distribution set should have different hashcode than action status") + .isNotEqualTo(new ActionStatus().hashCode()); + assertThat(new DistributionSetType().hashCode()) + .as("Distribution set type should have different hashcode than action status") + .isNotEqualTo(new ActionStatus().hashCode()); + } + + @Test + @Description("Verfies that different object even with identical primary key, version and tenant " + + "are not equal.") + public void differentEntitiesAreNotEqual() { + assertThat(new Action().equals(new ActionStatus())).as("action equals action status").isFalse(); + assertThat(new DistributionSet().equals(new SoftwareModule())).as("Distribution set equals software module") + .isFalse(); + assertThat(new DistributionSet().equals(new ActionStatus())).as("Distribution set equals action status") + .isFalse(); + assertThat(new DistributionSetType().equals(new ActionStatus())) + .as("Distribution set type equals action status").isFalse(); + } + + @Test + @Description("Verfies that updated entities are not equal.") + public void changedEntitiesAreNotEqual() { + final SoftwareModuleType type = softwareManagement + .createSoftwareModuleType(new SoftwareModuleType("test", "test", "test", 1)); + assertThat(type).as("persited entity is not equal to regular object") + .isNotEqualTo(new SoftwareModuleType("test", "test", "test", 1)); + + type.setDescription("another"); + final SoftwareModuleType updated = softwareManagement.updateSoftwareModuleType(type); + assertThat(type).as("Changed entity is not equal to the previous version").isNotEqualTo(updated); + } + + @Test + @Description("Verify that no proxy of the entity manager has an influence on the equals or hashcode result.") + public void managedEntityIsEqualToUnamangedObjectWithSameKey() { + final SoftwareModuleType type = softwareManagement + .createSoftwareModuleType(new SoftwareModuleType("test", "test", "test", 1)); + + final SoftwareModuleType mock = new SoftwareModuleType("test", "test", "test", 1); + mock.setId(type.getId()); + mock.setOptLockRevision(type.getOptLockRevision()); + mock.setTenant(type.getTenant()); + + assertThat(type).as("managed entity is equal to regular object with same content").isEqualTo(mock); + assertThat(type.hashCode()).as("managed entity has same hash code as regular object with same content") + .isEqualTo(mock.hashCode()); + } + + @Test + @Description("Verfies that updated entities do not have the same hashcode.") + public void updatedEntitiesHaveDifferentHashcodes() { + final SoftwareModuleType type = softwareManagement + .createSoftwareModuleType(new SoftwareModuleType("test", "test", "test", 1)); + assertThat(type.hashCode()).as("persited entity does not have same hashcode as regular object") + .isNotEqualTo(new SoftwareModuleType("test", "test", "test", 1).hashCode()); + + final int beforeChange = type.hashCode(); + type.setDescription("another"); + assertThat(type.hashCode()) + .as("Changed entity has no different hashcode than the previous version until updated in repository") + .isEqualTo(beforeChange); + + final SoftwareModuleType updated = softwareManagement.updateSoftwareModuleType(type); + assertThat(type.hashCode()).as("Updated entity has different hashcode than the previous version") + .isNotEqualTo(updated.hashCode()); + } + +} diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLDistributionSetFieldTest.java b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLDistributionSetFieldTest.java index ea1db0ed8..6b1682820 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLDistributionSetFieldTest.java +++ b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLDistributionSetFieldTest.java @@ -35,18 +35,18 @@ public class RSQLDistributionSetFieldTest extends AbstractIntegrationTest { @Before public void seuptBeforeTest() { - final DistributionSet ds = TestDataUtil.generateDistributionSet("DS", softwareManagement, - distributionSetManagement); + DistributionSet ds = TestDataUtil.generateDistributionSet("DS", softwareManagement, distributionSetManagement); ds.setDescription("DS"); - ds.getMetadata().add(new DistributionSetMetadata("metaKey", ds, "metaValue")); - distributionSetManagement.updateDistributionSet(ds); + ds = distributionSetManagement.updateDistributionSet(ds); + distributionSetManagement + .createDistributionSetMetadata(new DistributionSetMetadata("metaKey", ds, "metaValue")); - final DistributionSet ds2 = TestDataUtil + DistributionSet ds2 = TestDataUtil .generateDistributionSets("NewDS", 3, softwareManagement, distributionSetManagement).get(0); ds2.setDescription("DS%"); - ds2.getMetadata().add(new DistributionSetMetadata("metaKey", ds2, "value")); - distributionSetManagement.updateDistributionSet(ds2); + ds2 = distributionSetManagement.updateDistributionSet(ds2); + distributionSetManagement.createDistributionSetMetadata(new DistributionSetMetadata("metaKey", ds2, "value")); final DistributionSetTag targetTag = tagManagement.createDistributionSetTag(new DistributionSetTag("Tag1")); tagManagement.createDistributionSetTag(new DistributionSetTag("Tag2")); diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLDistributionSetMetadataFieldsTest.java b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLDistributionSetMetadataFieldsTest.java index 1d1e8b7f3..755e5a61f 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLDistributionSetMetadataFieldsTest.java +++ b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLDistributionSetMetadataFieldsTest.java @@ -10,6 +10,9 @@ package org.eclipse.hawkbit.repository.rsql; import static org.fest.assertions.api.Assertions.assertThat; +import java.util.ArrayList; +import java.util.List; + import org.eclipse.hawkbit.AbstractIntegrationTest; import org.eclipse.hawkbit.TestDataUtil; import org.eclipse.hawkbit.repository.DistributionSetMetadataFields; @@ -35,13 +38,13 @@ public class RSQLDistributionSetMetadataFieldsTest extends AbstractIntegrationTe final DistributionSet distributionSet = TestDataUtil.generateDistributionSet("DS", softwareManagement, distributionSetManagement); distributionSetId = distributionSet.getId(); + + final List metadata = new ArrayList<>(); for (int i = 0; i < 5; i++) { - final DistributionSetMetadata distributionSetMetadata = new DistributionSetMetadata("" + i, distributionSet, - "" + i); - distributionSet.getMetadata().add(distributionSetMetadata); + metadata.add(new DistributionSetMetadata("" + i, distributionSet, "" + i)); } - distributionSetManagement.updateDistributionSet(distributionSet); + distributionSetManagement.createDistributionSetMetadata(metadata); } @Test diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLSoftwareModuleFieldTest.java b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLSoftwareModuleFieldTest.java index 88f0817f7..0c113fd2b 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLSoftwareModuleFieldTest.java +++ b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLSoftwareModuleFieldTest.java @@ -28,8 +28,7 @@ import ru.yandex.qatools.allure.annotations.Stories; public class RSQLSoftwareModuleFieldTest extends AbstractIntegrationTest { @Before - public void seuptBeforeTest() { - + public void setupBeforeTest() { final SoftwareModule ah = softwareManagement .createSoftwareModule(new SoftwareModule(appType, "agent-hub", "1.0.1", "agent-hub", "")); softwareManagement.createSoftwareModule(new SoftwareModule(runtimeType, "oracle-jre", "1.7.2", "aa", "")); @@ -40,14 +39,9 @@ public class RSQLSoftwareModuleFieldTest extends AbstractIntegrationTest { final SoftwareModuleMetadata softwareModuleMetadata = new SoftwareModuleMetadata("metaKey", ah, "metaValue"); softwareManagement.createSoftwareModuleMetadata(softwareModuleMetadata); - ah.getMetadata().add(softwareModuleMetadata); - softwareManagement.updateSoftwareModule(ah); final SoftwareModuleMetadata softwareModuleMetadata2 = new SoftwareModuleMetadata("metaKey", ah2, "value"); softwareManagement.createSoftwareModuleMetadata(softwareModuleMetadata2); - ah2.getMetadata().add(softwareModuleMetadata2); - softwareManagement.updateSoftwareModule(ah2); - } @Test diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLSoftwareModuleMetadataFieldsTest.java b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLSoftwareModuleMetadataFieldsTest.java index c863c1460..44fa3e3cd 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLSoftwareModuleMetadataFieldsTest.java +++ b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/rsql/RSQLSoftwareModuleMetadataFieldsTest.java @@ -10,6 +10,9 @@ package org.eclipse.hawkbit.repository.rsql; import static org.fest.assertions.api.Assertions.assertThat; +import java.util.ArrayList; +import java.util.List; + import org.eclipse.hawkbit.AbstractIntegrationTest; import org.eclipse.hawkbit.TestDataUtil; import org.eclipse.hawkbit.repository.SoftwareModuleMetadataFields; @@ -37,13 +40,13 @@ public class RSQLSoftwareModuleMetadataFieldsTest extends AbstractIntegrationTes "application", "1.0.0", "Desc", "vendor Limited, California")); softwareModuleId = softwareModule.getId(); + final List metadata = new ArrayList<>(); for (int i = 0; i < 5; i++) { - final SoftwareModuleMetadata metadata = new SoftwareModuleMetadata("" + i, softwareModule, "" + i); - softwareModule.getMetadata().add(metadata); - softwareModuleMetadataRepository.save(metadata); + metadata.add(new SoftwareModuleMetadata("" + i, softwareModule, "" + i)); } - softwareManagement.updateSoftwareModule(softwareModule); + softwareManagement.createSoftwareModuleMetadata(metadata); + } @Test diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/utils/RepositoryDataGenerator.java b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/utils/RepositoryDataGenerator.java index d7efa50d5..a1c74e791 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/utils/RepositoryDataGenerator.java +++ b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/repository/utils/RepositoryDataGenerator.java @@ -49,7 +49,6 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.data.auditing.AuditingHandler; -import org.springframework.data.auditing.DateTimeProvider; import org.springframework.data.jpa.repository.Modifying; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.core.context.SecurityContext; @@ -132,24 +131,18 @@ public final class RepositoryDataGenerator { final DistributionSetTag dsTag = tagManagement .createDistributionSetTag(new DistributionSetTag("For " + group + "s")); - auditingHandler.setDateTimeProvider(new DateTimeProvider() { - @Override - public Calendar getNow() { - final Calendar instance = Calendar.getInstance(); - instance.add(Calendar.MONTH, -new Random().nextInt(7)); + auditingHandler.setDateTimeProvider(() -> { + final Calendar instance = Calendar.getInstance(); + instance.add(Calendar.MONTH, -new Random().nextInt(7)); - return instance; - } + return instance; }); final List targets = createTargetTestGroup(group, 20 * sizeMultiplikator); - auditingHandler.setDateTimeProvider(new DateTimeProvider() { - @Override - public Calendar getNow() { - final Calendar instance = Calendar.getInstance(); - return instance; - } + auditingHandler.setDateTimeProvider(() -> { + final Calendar instance = Calendar.getInstance(); + return instance; }); LOG.debug("initDemoRepo - start now real action history for group: {}", group); @@ -290,7 +283,7 @@ public final class RepositoryDataGenerator { LOG.debug("createTargetTestGroup: {} targets status updated including IP", group); - return targetManagement.toggleTagAssignment(targAs, targTag).getAssignedTargets(); + return targetManagement.toggleTagAssignment(targAs, targTag).getAssignedEntity(); } private List buildTargets(final int noOfTgts, final String descriptionPrefix) { @@ -328,75 +321,70 @@ public final class RepositoryDataGenerator { private void initDemoRepo(final int sizeMultiplikator, final int loadtestgroups) { final LoremIpsum jlorem = new LoremIpsum(); - runAsAllAuthorityContext(new Runnable() { + runAsAllAuthorityContext(() -> { + dbCleanupUtil.cleanupDB(null); - @Override - public void run() { - dbCleanupUtil.cleanupDB(null); + // generate targets and assign DS + // 5 groups - 100 targets each -> 500 + final String[] targetTestGroups = { "SHC", "CCU", "Vehicle", "Vending machine", "ECU" }; - // generate targets and assign DS - // 5 groups - 100 targets each -> 500 - final String[] targetTestGroups = { "SHC", "CCU", "Vehicle", "Vending machine", "ECU" }; + final String[] modulesTypes = { "HeadUnit_FW", "EDC17_FW", "OSGi_Bundle" }; - final String[] modulesTypes = { "HeadUnit_FW", "EDC17_FW", "OSGi_Bundle" }; + final DistributionSetTag depTag = tagManagement + .createDistributionSetTag(new DistributionSetTag("deprecated")); - final DistributionSetTag depTag = tagManagement - .createDistributionSetTag(new DistributionSetTag("deprecated")); + Arrays.stream(targetTestGroups).forEach(group -> { + generateTestTagetGroup(group, sizeMultiplikator); + }); - Arrays.stream(targetTestGroups).forEach(group -> { - generateTestTagetGroup(group, sizeMultiplikator); - }); + // garbage DS + LOG.debug("initDemoRepo - start now DS garbage"); + TestDataUtil.generateDistributionSets("Generic Software Package", sizeMultiplikator, + softwareManagement, distributionSetManagement); + LOG.debug("initDemoRepo - DS garbage finished"); - // garbage DS - LOG.debug("initDemoRepo - start now DS garbage"); - TestDataUtil.generateDistributionSets("Generic Software Package", sizeMultiplikator, - softwareManagement, distributionSetManagement); - LOG.debug("initDemoRepo - DS garbage finished"); + LOG.debug("initDemoRepo - start now Extra Software Modules and types"); + Arrays.stream(modulesTypes).forEach(typeName -> { + final SoftwareModuleType smtype = softwareManagement.createSoftwareModuleType( + new SoftwareModuleType(typeName.toLowerCase().replaceAll("\\s+", ""), typeName, + jlorem.words(5), Integer.MAX_VALUE)); - LOG.debug("initDemoRepo - start now Extra Software Modules and types"); - Arrays.stream(modulesTypes).forEach(typeName -> { - final SoftwareModuleType smtype = softwareManagement.createSoftwareModuleType( - new SoftwareModuleType(typeName.toLowerCase().replaceAll("\\s+", ""), typeName, - jlorem.words(5), Integer.MAX_VALUE)); - - for (int i = 0; i < sizeMultiplikator; i++) { - softwareManagement.createSoftwareModule(new SoftwareModule(smtype, typeName + i, "1.0." + i, - jlorem.words(5), "the " + typeName + " vendor Inc.")); - } - - }); - LOG.debug("initDemoRepo - Extra Software Modules and types finished"); - - LOG.debug("initDemoRepo - start now target garbage"); - - // garbage targets - // unknown - targetManagement - .createTargets(TestDataUtil.generateTargets(targetTestGroups.length * sizeMultiplikator)); - - // registered - targetManagement.createTargets( - TestDataUtil.generateTargets(targetTestGroups.length * sizeMultiplikator, "registered"), - TargetUpdateStatus.REGISTERED, System.currentTimeMillis(), generateIPAddress()); - - // pending - final DistributionSetTag dsTag = tagManagement - .createDistributionSetTag(new DistributionSetTag("OnlyAssignedTag")); - final DistributionSet ds = TestDataUtil.generateDistributionSet("Pending DS", "v1.0", - softwareManagement, distributionSetManagement, - Arrays.asList(new DistributionSetTag[] { dsTag })); - deploymentManagement.assignDistributionSet(ds, targetManagement.createTargets( - TestDataUtil.generateTargets(targetTestGroups.length * sizeMultiplikator, "pending"))); - - // Load test means additional 1_000_000 target - - for (int i = 0; i < loadtestgroups; i++) { - targetManagement.createTargets(TestDataUtil.generateTargets(i * 1_000, 1_000, "loadtest-")); + for (int i1 = 0; i1 < sizeMultiplikator; i1++) { + softwareManagement.createSoftwareModule(new SoftwareModule(smtype, typeName + i1, "1.0." + i1, + jlorem.words(5), "the " + typeName + " vendor Inc.")); } - LOG.debug("initDemoRepo complete"); + }); + LOG.debug("initDemoRepo - Extra Software Modules and types finished"); + + LOG.debug("initDemoRepo - start now target garbage"); + + // garbage targets + // unknown + targetManagement + .createTargets(TestDataUtil.generateTargets(targetTestGroups.length * sizeMultiplikator)); + + // registered + targetManagement.createTargets( + TestDataUtil.generateTargets(targetTestGroups.length * sizeMultiplikator, "registered"), + TargetUpdateStatus.REGISTERED, System.currentTimeMillis(), generateIPAddress()); + + // pending + final DistributionSetTag dsTag = tagManagement + .createDistributionSetTag(new DistributionSetTag("OnlyAssignedTag")); + final DistributionSet ds = TestDataUtil.generateDistributionSet("Pending DS", "v1.0", + softwareManagement, distributionSetManagement, + Arrays.asList(new DistributionSetTag[] { dsTag })); + deploymentManagement.assignDistributionSet(ds, targetManagement.createTargets( + TestDataUtil.generateTargets(targetTestGroups.length * sizeMultiplikator, "pending"))); + + // Load test means additional 1_000_000 target + + for (int i2 = 0; i2 < loadtestgroups; i2++) { + targetManagement.createTargets(TestDataUtil.generateTargets(i2 * 1_000, 1_000, "loadtest-")); } + LOG.debug("initDemoRepo complete"); }); } /** diff --git a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/tenancy/MultiTenancyEntityTest.java b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/tenancy/MultiTenancyEntityTest.java index 1dd4c9823..67b9b5a26 100644 --- a/hawkbit-repository/src/test/java/org/eclipse/hawkbit/tenancy/MultiTenancyEntityTest.java +++ b/hawkbit-repository/src/test/java/org/eclipse/hawkbit/tenancy/MultiTenancyEntityTest.java @@ -78,6 +78,22 @@ public class MultiTenancyEntityTest extends AbstractIntegrationTest { assertThat(findTargetsForTenant).hasSize(1); } + @Test + @Description(value = "Ensures that tenant with proper permissions can read and delete other tenants.") + @WithUser(tenantId = "mytenant", allSpPermissions = true) + public void deleteAnotherTenantPossible() throws Exception { + // create target for another tenant + final String anotherTenant = "anotherTenant"; + final String controllerAnotherTenant = "anotherController"; + createTargetForTenant(controllerAnotherTenant, anotherTenant); + + assertThat(systemManagement.findTenants()).as("Expected number if tenants before deletion is").hasSize(3); + + systemManagement.deleteTenant(anotherTenant); + + assertThat(systemManagement.findTenants()).as("Expected number if tenants after deletion is").hasSize(2); + } + @Test @Description(value = "Ensures that tenant metadata is retrieved for the current tenant.") @WithUser(tenantId = "mytenant", autoCreateTenant = false, allSpPermissions = true) diff --git a/hawkbit-repository/src/test/resources/application-test.properties b/hawkbit-repository/src/test/resources/application-test.properties index b1904f911..0882d901c 100644 --- a/hawkbit-repository/src/test/resources/application-test.properties +++ b/hawkbit-repository/src/test/resources/application-test.properties @@ -13,7 +13,7 @@ spring.data.mongodb.port=28017 hawkbit.server.ddi.security.authentication.header.enabled=true hawkbit.server.ddi.security.authentication.gatewaytoken.name=TestToken -hawkbit.server.artifact.repo.upload.maxFileSize=5MB +multipart.max-file-size=5MB hawkbit.server.security.dos.maxStatusEntriesPerAction=100 @@ -26,7 +26,6 @@ spring.datasource.username=sa spring.datasource.password=sa flyway.enabled=true -flyway.initOnMigrate=true flyway.sqlMigrationSuffix=${spring.jpa.database}.sql #spring.jpa.show-sql=true diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/MetadataRestPageList.java b/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/MetadataRestPageList.java deleted file mode 100644 index 0d375c582..000000000 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/MetadataRestPageList.java +++ /dev/null @@ -1,38 +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.rest.resource.model; - -import java.util.List; - -/** - * The rest model for a paged meta data list. - * - */ -public class MetadataRestPageList extends PagedList { - - private final List content; - - /** - * @param content - * the meta data rest model list as content - * @param total - * the total number of the meta data - */ - public MetadataRestPageList(final List content, final long total) { - super(content, total); - this.content = content; - } - - /** - * @return the content of this paged list - */ - public List getContent() { - return content; - } -} diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/action/ActionPagedList.java b/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/action/ActionPagedList.java deleted file mode 100644 index 27b36779a..000000000 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/action/ActionPagedList.java +++ /dev/null @@ -1,48 +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.rest.resource.model.action; - -import java.util.Collections; -import java.util.List; - -import org.eclipse.hawkbit.rest.resource.model.PagedList; - -/** - * Paged list rest model for {@link ErrorAction} to RESTful API representation. - * - */ -public class ActionPagedList extends PagedList { - - private final List content; - - /** - * Empty default constructor. - */ - public ActionPagedList() { - super(Collections.emptyList(), 0); - this.content = Collections.emptyList(); - } - - /** - * @param content - * @param total - */ - public ActionPagedList(final List content, final long total) { - super(content, total); - this.content = content; - } - - /** - * @return the content of the paged list. Never {@code null}. - */ - public List getContent() { - return content; - } - -} diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/action/ActionStatusPagedList.java b/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/action/ActionStatusPagedList.java deleted file mode 100644 index d9f19b98e..000000000 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/action/ActionStatusPagedList.java +++ /dev/null @@ -1,54 +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.rest.resource.model.action; - -import java.util.Collections; -import java.util.List; - -import org.eclipse.hawkbit.rest.resource.model.PagedList; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - -/** - * Paged list rest model for ActionStatus to RESTful API representation. - * - * - * - * - */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class ActionStatusPagedList extends PagedList { - - private final List content; - - /** - * @param content - * @param total - */ - public ActionStatusPagedList(final List content, final long total) { - super(content, total); - this.content = content; - } - - /** - * Default constructor. - */ - public ActionStatusPagedList() { - super(Collections.emptyList(), 0); - this.content = Collections.emptyList(); - } - - /** - * @return the content of the paged list. Never {@code null}. - */ - public List getContent() { - return content; - } - -} diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/action/ActionStatussRest.java b/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/action/ActionStatussRest.java deleted file mode 100644 index b3f3207b4..000000000 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/action/ActionStatussRest.java +++ /dev/null @@ -1,277 +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.rest.resource.model.action; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; - -import org.springframework.hateoas.ResourceSupport; - -/** - * A list representation of the ActionStatus because Spring MVC cannot handle - * plain lists interfaces as request body. - * - * - * - * - */ -public class ActionStatussRest extends ResourceSupport implements List { - - private final List delegate = new ArrayList<>(); - - /** - * @return - * @see java.util.List#size() - */ - @Override - public int size() { - return delegate.size(); - } - - /** - * @return - * @see java.util.List#isEmpty() - */ - @Override - public boolean isEmpty() { - return delegate.isEmpty(); - } - - /** - * @param o - * @return - * @see java.util.List#contains(java.lang.Object) - */ - @Override - public boolean contains(final Object o) { - return delegate.contains(o); - } - - /** - * @return - * @see java.util.List#iterator() - */ - @Override - public Iterator iterator() { - return delegate.iterator(); - } - - /** - * @return - * @see java.util.List#toArray() - */ - @Override - public Object[] toArray() { - return delegate.toArray(); - } - - /** - * @param a - * @return - * @see java.util.List#toArray(java.lang.Object[]) - */ - @Override - public T[] toArray(final T[] a) { - return delegate.toArray(a); - } - - /** - * @param e - * @return - * @see java.util.List#add(java.lang.Object) - */ - @Override - public boolean add(final ActionStatusRest e) { - return delegate.add(e); - } - - /** - * @param o - * @return - * @see java.util.List#remove(java.lang.Object) - */ - @Override - public boolean remove(final Object o) { - return delegate.remove(o); - } - - /** - * @param c - * @return - * @see java.util.List#containsAll(java.util.Collection) - */ - @Override - public boolean containsAll(final Collection c) { - return delegate.containsAll(c); - } - - /** - * @param c - * @return - * @see java.util.List#addAll(java.util.Collection) - */ - @Override - public boolean addAll(final Collection c) { - return delegate.addAll(c); - } - - /** - * @param index - * @param c - * @return - * @see java.util.List#addAll(int, java.util.Collection) - */ - @Override - public boolean addAll(final int index, final Collection c) { - return delegate.addAll(index, c); - } - - /** - * @param c - * @return - * @see java.util.List#removeAll(java.util.Collection) - */ - @Override - public boolean removeAll(final Collection c) { - return delegate.removeAll(c); - } - - /** - * @param c - * @return - * @see java.util.List#retainAll(java.util.Collection) - */ - @Override - public boolean retainAll(final Collection c) { - return delegate.retainAll(c); - } - - /** - * - * @see java.util.List#clear() - */ - @Override - public void clear() { - delegate.clear(); - } - - /** - * @param o - * @return - * @see java.util.List#equals(java.lang.Object) - */ - @Override - public boolean equals(final Object o) { - return delegate.equals(o); - } - - /** - * @return - * @see java.util.List#hashCode() - */ - @Override - public int hashCode() { - return delegate.hashCode(); - } - - /** - * @param index - * @return - * @see java.util.List#get(int) - */ - @Override - public ActionStatusRest get(final int index) { - return delegate.get(index); - } - - /** - * @param index - * @param element - * @return - * @see java.util.List#set(int, java.lang.Object) - */ - @Override - public ActionStatusRest set(final int index, final ActionStatusRest element) { - return delegate.set(index, element); - } - - /** - * @param index - * @param element - * @see java.util.List#add(int, java.lang.Object) - */ - @Override - public void add(final int index, final ActionStatusRest element) { - delegate.add(index, element); - } - - /** - * @param index - * @return - * @see java.util.List#remove(int) - */ - @Override - public ActionStatusRest remove(final int index) { - return delegate.remove(index); - } - - /** - * @param o - * @return - * @see java.util.List#indexOf(java.lang.Object) - */ - @Override - public int indexOf(final Object o) { - return delegate.indexOf(o); - } - - /** - * @param o - * @return - * @see java.util.List#lastIndexOf(java.lang.Object) - */ - @Override - public int lastIndexOf(final Object o) { - return delegate.lastIndexOf(o); - } - - /** - * @return - * @see java.util.List#listIterator() - */ - @Override - public ListIterator listIterator() { - return delegate.listIterator(); - } - - /** - * @param index - * @return - * @see java.util.List#listIterator(int) - */ - @Override - public ListIterator listIterator(final int index) { - return delegate.listIterator(index); - } - - /** - * @param fromIndex - * @param toIndex - * @return - * @see java.util.List#subList(int, int) - */ - @Override - public List subList(final int fromIndex, final int toIndex) { - return delegate.subList(fromIndex, toIndex); - } - -} diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/action/ActionsRest.java b/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/action/ActionsRest.java deleted file mode 100644 index 9c3659f30..000000000 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/action/ActionsRest.java +++ /dev/null @@ -1,276 +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.rest.resource.model.action; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; - -import org.springframework.hateoas.ResourceSupport; - -/** - * A json annotated rest model for Actions to RESTful API representation. - * - * - * - * - */ -public class ActionsRest extends ResourceSupport implements List { - - private final List delegate = new ArrayList<>(); - - /** - * @return - * @see java.util.List#size() - */ - @Override - public int size() { - return delegate.size(); - } - - /** - * @return - * @see java.util.List#isEmpty() - */ - @Override - public boolean isEmpty() { - return delegate.isEmpty(); - } - - /** - * @param o - * @return - * @see java.util.List#contains(java.lang.Object) - */ - @Override - public boolean contains(final Object o) { - return delegate.contains(o); - } - - /** - * @return - * @see java.util.List#iterator() - */ - @Override - public Iterator iterator() { - return delegate.iterator(); - } - - /** - * @return - * @see java.util.List#toArray() - */ - @Override - public Object[] toArray() { - return delegate.toArray(); - } - - /** - * @param a - * @return - * @see java.util.List#toArray(java.lang.Object[]) - */ - @Override - public T[] toArray(final T[] a) { - return delegate.toArray(a); - } - - /** - * @param e - * @return - * @see java.util.List#add(java.lang.Object) - */ - @Override - public boolean add(final ActionRest e) { - return delegate.add(e); - } - - /** - * @param o - * @return - * @see java.util.List#remove(java.lang.Object) - */ - @Override - public boolean remove(final Object o) { - return delegate.remove(o); - } - - /** - * @param c - * @return - * @see java.util.List#containsAll(java.util.Collection) - */ - @Override - public boolean containsAll(final Collection c) { - return delegate.containsAll(c); - } - - /** - * @param c - * @return - * @see java.util.List#addAll(java.util.Collection) - */ - @Override - public boolean addAll(final Collection c) { - return delegate.addAll(c); - } - - /** - * @param index - * @param c - * @return - * @see java.util.List#addAll(int, java.util.Collection) - */ - @Override - public boolean addAll(final int index, final Collection c) { - return delegate.addAll(index, c); - } - - /** - * @param c - * @return - * @see java.util.List#removeAll(java.util.Collection) - */ - @Override - public boolean removeAll(final Collection c) { - return delegate.removeAll(c); - } - - /** - * @param c - * @return - * @see java.util.List#retainAll(java.util.Collection) - */ - @Override - public boolean retainAll(final Collection c) { - return delegate.retainAll(c); - } - - /** - * - * @see java.util.List#clear() - */ - @Override - public void clear() { - delegate.clear(); - } - - /** - * @param o - * @return - * @see java.util.List#equals(java.lang.Object) - */ - @Override - public boolean equals(final Object o) { - return delegate.equals(o); - } - - /** - * @return - * @see java.util.List#hashCode() - */ - @Override - public int hashCode() { - return delegate.hashCode(); - } - - /** - * @param index - * @return - * @see java.util.List#get(int) - */ - @Override - public ActionRest get(final int index) { - return delegate.get(index); - } - - /** - * @param index - * @param element - * @return - * @see java.util.List#set(int, java.lang.Object) - */ - @Override - public ActionRest set(final int index, final ActionRest element) { - return delegate.set(index, element); - } - - /** - * @param index - * @param element - * @see java.util.List#add(int, java.lang.Object) - */ - @Override - public void add(final int index, final ActionRest element) { - delegate.add(index, element); - } - - /** - * @param index - * @return - * @see java.util.List#remove(int) - */ - @Override - public ActionRest remove(final int index) { - return delegate.remove(index); - } - - /** - * @param o - * @return - * @see java.util.List#indexOf(java.lang.Object) - */ - @Override - public int indexOf(final Object o) { - return delegate.indexOf(o); - } - - /** - * @param o - * @return - * @see java.util.List#lastIndexOf(java.lang.Object) - */ - @Override - public int lastIndexOf(final Object o) { - return delegate.lastIndexOf(o); - } - - /** - * @return - * @see java.util.List#listIterator() - */ - @Override - public ListIterator listIterator() { - return delegate.listIterator(); - } - - /** - * @param index - * @return - * @see java.util.List#listIterator(int) - */ - @Override - public ListIterator listIterator(final int index) { - return delegate.listIterator(index); - } - - /** - * @param fromIndex - * @param toIndex - * @return - * @see java.util.List#subList(int, int) - */ - @Override - public List subList(final int fromIndex, final int toIndex) { - return delegate.subList(fromIndex, toIndex); - } - -} diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/artifact/ArtifactsRest.java b/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/artifact/ArtifactsRest.java deleted file mode 100644 index 172e4d315..000000000 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/artifact/ArtifactsRest.java +++ /dev/null @@ -1,273 +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.rest.resource.model.artifact; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; - -import org.springframework.hateoas.ResourceSupport; - -/** - * List representation of the {@link ArtifactRest}. - * - */ -public class ArtifactsRest extends ResourceSupport implements List { - - private final List delegate = new ArrayList<>(); - - /** - * @return - * @see java.util.List#size() - */ - @Override - public int size() { - return delegate.size(); - } - - /** - * @return - * @see java.util.List#isEmpty() - */ - @Override - public boolean isEmpty() { - return delegate.isEmpty(); - } - - /** - * @param o - * @return - * @see java.util.List#contains(java.lang.Object) - */ - @Override - public boolean contains(final Object o) { - return delegate.contains(o); - } - - /** - * @return - * @see java.util.List#iterator() - */ - @Override - public Iterator iterator() { - return delegate.iterator(); - } - - /** - * @return - * @see java.util.List#toArray() - */ - @Override - public Object[] toArray() { - return delegate.toArray(); - } - - /** - * @param a - * @return - * @see java.util.List#toArray(java.lang.Object[]) - */ - @Override - public T[] toArray(final T[] a) { - return delegate.toArray(a); - } - - /** - * @param e - * @return - * @see java.util.List#add(java.lang.Object) - */ - @Override - public boolean add(final ArtifactRest e) { - return delegate.add(e); - } - - /** - * @param o - * @return - * @see java.util.List#remove(java.lang.Object) - */ - @Override - public boolean remove(final Object o) { - return delegate.remove(o); - } - - /** - * @param c - * @return - * @see java.util.List#containsAll(java.util.Collection) - */ - @Override - public boolean containsAll(final Collection c) { - return delegate.containsAll(c); - } - - /** - * @param c - * @return - * @see java.util.List#addAll(java.util.Collection) - */ - @Override - public boolean addAll(final Collection c) { - return delegate.addAll(c); - } - - /** - * @param index - * @param c - * @return - * @see java.util.List#addAll(int, java.util.Collection) - */ - @Override - public boolean addAll(final int index, final Collection c) { - return delegate.addAll(index, c); - } - - /** - * @param c - * @return - * @see java.util.List#removeAll(java.util.Collection) - */ - @Override - public boolean removeAll(final Collection c) { - return delegate.removeAll(c); - } - - /** - * @param c - * @return - * @see java.util.List#retainAll(java.util.Collection) - */ - @Override - public boolean retainAll(final Collection c) { - return delegate.retainAll(c); - } - - /** - * - * @see java.util.List#clear() - */ - @Override - public void clear() { - delegate.clear(); - } - - /** - * @param o - * @return - * @see java.util.List#equals(java.lang.Object) - */ - @Override - public boolean equals(final Object o) { - return delegate.equals(o); - } - - /** - * @return - * @see java.util.List#hashCode() - */ - @Override - public int hashCode() { - return delegate.hashCode(); - } - - /** - * @param index - * @return - * @see java.util.List#get(int) - */ - @Override - public ArtifactRest get(final int index) { - return delegate.get(index); - } - - /** - * @param index - * @param element - * @return - * @see java.util.List#set(int, java.lang.Object) - */ - @Override - public ArtifactRest set(final int index, final ArtifactRest element) { - return delegate.set(index, element); - } - - /** - * @param index - * @param element - * @see java.util.List#add(int, java.lang.Object) - */ - @Override - public void add(final int index, final ArtifactRest element) { - delegate.add(index, element); - } - - /** - * @param index - * @return - * @see java.util.List#remove(int) - */ - @Override - public ArtifactRest remove(final int index) { - return delegate.remove(index); - } - - /** - * @param o - * @return - * @see java.util.List#indexOf(java.lang.Object) - */ - @Override - public int indexOf(final Object o) { - return delegate.indexOf(o); - } - - /** - * @param o - * @return - * @see java.util.List#lastIndexOf(java.lang.Object) - */ - @Override - public int lastIndexOf(final Object o) { - return delegate.lastIndexOf(o); - } - - /** - * @return - * @see java.util.List#listIterator() - */ - @Override - public ListIterator listIterator() { - return delegate.listIterator(); - } - - /** - * @param index - * @return - * @see java.util.List#listIterator(int) - */ - @Override - public ListIterator listIterator(final int index) { - return delegate.listIterator(index); - } - - /** - * @param fromIndex - * @param toIndex - * @return - * @see java.util.List#subList(int, int) - */ - @Override - public List subList(final int fromIndex, final int toIndex) { - return delegate.subList(fromIndex, toIndex); - } - -} diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/distributionset/DistributionSetPagedList.java b/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/distributionset/DistributionSetPagedList.java deleted file mode 100644 index b7ad1eddb..000000000 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/distributionset/DistributionSetPagedList.java +++ /dev/null @@ -1,39 +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.rest.resource.model.distributionset; - -import java.util.List; - -import org.eclipse.hawkbit.rest.resource.model.PagedList; - -/** - * Paged list for SoftwareModule. - * - */ -public class DistributionSetPagedList extends PagedList { - - private final List content; - - /** - * @param content - * @param total - */ - public DistributionSetPagedList(final List content, final long total) { - super(content, total); - this.content = content; - } - - /** - * @return the content of the paged list. Never {@code null}. - */ - public List getContent() { - return content; - } - -} diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/distributionset/DistributionSetsRest.java b/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/distributionset/DistributionSetsRest.java deleted file mode 100644 index ce7b4d1f1..000000000 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/distributionset/DistributionSetsRest.java +++ /dev/null @@ -1,277 +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.rest.resource.model.distributionset; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; - -import org.springframework.hateoas.ResourceSupport; - -/** - * List representation of the {@link DistributionSetRest} because Spring MVC - * cannot handle plain lists interfaces as request body. - * - * - * - * - */ -public class DistributionSetsRest extends ResourceSupport implements List { - - private final List delegate = new ArrayList<>(); - - /** - * @return - * @see java.util.List#size() - */ - @Override - public int size() { - return delegate.size(); - } - - /** - * @return - * @see java.util.List#isEmpty() - */ - @Override - public boolean isEmpty() { - return delegate.isEmpty(); - } - - /** - * @param o - * @return - * @see java.util.List#contains(java.lang.Object) - */ - @Override - public boolean contains(final Object o) { - return delegate.contains(o); - } - - /** - * @return - * @see java.util.List#iterator() - */ - @Override - public Iterator iterator() { - return delegate.iterator(); - } - - /** - * @return - * @see java.util.List#toArray() - */ - @Override - public Object[] toArray() { - return delegate.toArray(); - } - - /** - * @param a - * @return - * @see java.util.List#toArray(java.lang.Object[]) - */ - @Override - public T[] toArray(final T[] a) { - return delegate.toArray(a); - } - - /** - * @param e - * @return - * @see java.util.List#add(java.lang.Object) - */ - @Override - public boolean add(final DistributionSetRest e) { - return delegate.add(e); - } - - /** - * @param o - * @return - * @see java.util.List#remove(java.lang.Object) - */ - @Override - public boolean remove(final Object o) { - return delegate.remove(o); - } - - /** - * @param c - * @return - * @see java.util.List#containsAll(java.util.Collection) - */ - @Override - public boolean containsAll(final Collection c) { - return delegate.containsAll(c); - } - - /** - * @param c - * @return - * @see java.util.List#addAll(java.util.Collection) - */ - @Override - public boolean addAll(final Collection c) { - return delegate.addAll(c); - } - - /** - * @param index - * @param c - * @return - * @see java.util.List#addAll(int, java.util.Collection) - */ - @Override - public boolean addAll(final int index, final Collection c) { - return delegate.addAll(index, c); - } - - /** - * @param c - * @return - * @see java.util.List#removeAll(java.util.Collection) - */ - @Override - public boolean removeAll(final Collection c) { - return delegate.removeAll(c); - } - - /** - * @param c - * @return - * @see java.util.List#retainAll(java.util.Collection) - */ - @Override - public boolean retainAll(final Collection c) { - return delegate.retainAll(c); - } - - /** - * - * @see java.util.List#clear() - */ - @Override - public void clear() { - delegate.clear(); - } - - /** - * @param o - * @return - * @see java.util.List#equals(java.lang.Object) - */ - @Override - public boolean equals(final Object o) { - return delegate.equals(o); - } - - /** - * @return - * @see java.util.List#hashCode() - */ - @Override - public int hashCode() { - return delegate.hashCode(); - } - - /** - * @param index - * @return - * @see java.util.List#get(int) - */ - @Override - public DistributionSetRest get(final int index) { - return delegate.get(index); - } - - /** - * @param index - * @param element - * @return - * @see java.util.List#set(int, java.lang.Object) - */ - @Override - public DistributionSetRest set(final int index, final DistributionSetRest element) { - return delegate.set(index, element); - } - - /** - * @param index - * @param element - * @see java.util.List#add(int, java.lang.Object) - */ - @Override - public void add(final int index, final DistributionSetRest element) { - delegate.add(index, element); - } - - /** - * @param index - * @return - * @see java.util.List#remove(int) - */ - @Override - public DistributionSetRest remove(final int index) { - return delegate.remove(index); - } - - /** - * @param o - * @return - * @see java.util.List#indexOf(java.lang.Object) - */ - @Override - public int indexOf(final Object o) { - return delegate.indexOf(o); - } - - /** - * @param o - * @return - * @see java.util.List#lastIndexOf(java.lang.Object) - */ - @Override - public int lastIndexOf(final Object o) { - return delegate.lastIndexOf(o); - } - - /** - * @return - * @see java.util.List#listIterator() - */ - @Override - public ListIterator listIterator() { - return delegate.listIterator(); - } - - /** - * @param index - * @return - * @see java.util.List#listIterator(int) - */ - @Override - public ListIterator listIterator(final int index) { - return delegate.listIterator(index); - } - - /** - * @param fromIndex - * @param toIndex - * @return - * @see java.util.List#subList(int, int) - */ - @Override - public List subList(final int fromIndex, final int toIndex) { - return delegate.subList(fromIndex, toIndex); - } - -} diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/distributionsettype/DistributionSetTypePagedList.java b/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/distributionsettype/DistributionSetTypePagedList.java deleted file mode 100644 index 57b15f5e8..000000000 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/distributionsettype/DistributionSetTypePagedList.java +++ /dev/null @@ -1,40 +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.rest.resource.model.distributionsettype; - -import java.util.List; - -import org.eclipse.hawkbit.rest.resource.model.PagedList; - -/** - * Paged list for DistributionSetType. - * - * - */ -public class DistributionSetTypePagedList extends PagedList { - - private final List content; - - /** - * @param content - * @param total - */ - public DistributionSetTypePagedList(final List content, final long total) { - super(content, total); - this.content = content; - } - - /** - * @return the content of the paged list. Never {@code null}. - */ - public List getContent() { - return content; - } - -} diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/distributionsettype/DistributionSetTypesRest.java b/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/distributionsettype/DistributionSetTypesRest.java deleted file mode 100644 index f3cd42a85..000000000 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/distributionsettype/DistributionSetTypesRest.java +++ /dev/null @@ -1,274 +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.rest.resource.model.distributionsettype; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; - -import org.springframework.hateoas.ResourceSupport; - -/** - * List representation of the {@link DistributionSetTypeRest} because Spring MVC - * cannot handle plain lists interfaces as request body. - * - */ -public class DistributionSetTypesRest extends ResourceSupport implements List { - - private final List delegate = new ArrayList<>(); - - /** - * @return - * @see java.util.List#size() - */ - @Override - public int size() { - return delegate.size(); - } - - /** - * @return - * @see java.util.List#isEmpty() - */ - @Override - public boolean isEmpty() { - return delegate.isEmpty(); - } - - /** - * @param o - * @return - * @see java.util.List#contains(java.lang.Object) - */ - @Override - public boolean contains(final Object o) { - return delegate.contains(o); - } - - /** - * @return - * @see java.util.List#iterator() - */ - @Override - public Iterator iterator() { - return delegate.iterator(); - } - - /** - * @return - * @see java.util.List#toArray() - */ - @Override - public Object[] toArray() { - return delegate.toArray(); - } - - /** - * @param a - * @return - * @see java.util.List#toArray(java.lang.Object[]) - */ - @Override - public T[] toArray(final T[] a) { - return delegate.toArray(a); - } - - /** - * @param e - * @return - * @see java.util.List#add(java.lang.Object) - */ - @Override - public boolean add(final DistributionSetTypeRest e) { - return delegate.add(e); - } - - /** - * @param o - * @return - * @see java.util.List#remove(java.lang.Object) - */ - @Override - public boolean remove(final Object o) { - return delegate.remove(o); - } - - /** - * @param c - * @return - * @see java.util.List#containsAll(java.util.Collection) - */ - @Override - public boolean containsAll(final Collection c) { - return delegate.containsAll(c); - } - - /** - * @param c - * @return - * @see java.util.List#addAll(java.util.Collection) - */ - @Override - public boolean addAll(final Collection c) { - return delegate.addAll(c); - } - - /** - * @param index - * @param c - * @return - * @see java.util.List#addAll(int, java.util.Collection) - */ - @Override - public boolean addAll(final int index, final Collection c) { - return delegate.addAll(index, c); - } - - /** - * @param c - * @return - * @see java.util.List#removeAll(java.util.Collection) - */ - @Override - public boolean removeAll(final Collection c) { - return delegate.removeAll(c); - } - - /** - * @param c - * @return - * @see java.util.List#retainAll(java.util.Collection) - */ - @Override - public boolean retainAll(final Collection c) { - return delegate.retainAll(c); - } - - /** - * - * @see java.util.List#clear() - */ - @Override - public void clear() { - delegate.clear(); - } - - /** - * @param o - * @return - * @see java.util.List#equals(java.lang.Object) - */ - @Override - public boolean equals(final Object o) { - return delegate.equals(o); - } - - /** - * @return - * @see java.util.List#hashCode() - */ - @Override - public int hashCode() { - return delegate.hashCode(); - } - - /** - * @param index - * @return - * @see java.util.List#get(int) - */ - @Override - public DistributionSetTypeRest get(final int index) { - return delegate.get(index); - } - - /** - * @param index - * @param element - * @return - * @see java.util.List#set(int, java.lang.Object) - */ - @Override - public DistributionSetTypeRest set(final int index, final DistributionSetTypeRest element) { - return delegate.set(index, element); - } - - /** - * @param index - * @param element - * @see java.util.List#add(int, java.lang.Object) - */ - @Override - public void add(final int index, final DistributionSetTypeRest element) { - delegate.add(index, element); - } - - /** - * @param index - * @return - * @see java.util.List#remove(int) - */ - @Override - public DistributionSetTypeRest remove(final int index) { - return delegate.remove(index); - } - - /** - * @param o - * @return - * @see java.util.List#indexOf(java.lang.Object) - */ - @Override - public int indexOf(final Object o) { - return delegate.indexOf(o); - } - - /** - * @param o - * @return - * @see java.util.List#lastIndexOf(java.lang.Object) - */ - @Override - public int lastIndexOf(final Object o) { - return delegate.lastIndexOf(o); - } - - /** - * @return - * @see java.util.List#listIterator() - */ - @Override - public ListIterator listIterator() { - return delegate.listIterator(); - } - - /** - * @param index - * @return - * @see java.util.List#listIterator(int) - */ - @Override - public ListIterator listIterator(final int index) { - return delegate.listIterator(index); - } - - /** - * @param fromIndex - * @param toIndex - * @return - * @see java.util.List#subList(int, int) - */ - @Override - public List subList(final int fromIndex, final int toIndex) { - return delegate.subList(fromIndex, toIndex); - } - -} diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/rollout/RolloutPagedList.java b/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/rollout/RolloutPagedList.java deleted file mode 100644 index ea1544991..000000000 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/rollout/RolloutPagedList.java +++ /dev/null @@ -1,36 +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.rest.resource.model.rollout; - -import java.util.List; - -import org.eclipse.hawkbit.rest.resource.model.PagedList; - -/** - * Paged list for Rollout. - * - * - */ -public class RolloutPagedList extends PagedList { - - private final List content; - - public RolloutPagedList(final List content, final long total) { - super(content, total); - this.content = content; - } - - /** - * @return the content of the paged list. Never {@code null}. - */ - public List getContent() { - return content; - } - -} diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/rolloutgroup/RolloutGroupPagedList.java b/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/rolloutgroup/RolloutGroupPagedList.java deleted file mode 100644 index a341ac6ba..000000000 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/rolloutgroup/RolloutGroupPagedList.java +++ /dev/null @@ -1,35 +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.rest.resource.model.rolloutgroup; - -import java.util.List; - -import org.eclipse.hawkbit.rest.resource.model.PagedList; - -/** - * Paged list for Rollout. - * - */ -public class RolloutGroupPagedList extends PagedList { - - private final List content; - - public RolloutGroupPagedList(final List content, final long total) { - super(content, total); - this.content = content; - } - - /** - * @return the content of the paged list. Never {@code null}. - */ - public List getContent() { - return content; - } - -} diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/softwaremodule/SoftwareModulePagedList.java b/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/softwaremodule/SoftwareModulePagedList.java deleted file mode 100644 index a49f41dc9..000000000 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/softwaremodule/SoftwareModulePagedList.java +++ /dev/null @@ -1,39 +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.rest.resource.model.softwaremodule; - -import java.util.List; - -import org.eclipse.hawkbit.rest.resource.model.PagedList; - -/** - * Paged list for SoftwareModule. - * - */ -public class SoftwareModulePagedList extends PagedList { - - private final List content; - - /** - * @param content - * @param total - */ - public SoftwareModulePagedList(final List content, final long total) { - super(content, total); - this.content = content; - } - - /** - * @return the content of the paged list. Never {@code null}. - */ - public List getContent() { - return content; - } - -} diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/softwaremodule/SoftwareModulesRest.java b/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/softwaremodule/SoftwareModulesRest.java deleted file mode 100644 index b40c98d36..000000000 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/softwaremodule/SoftwareModulesRest.java +++ /dev/null @@ -1,277 +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.rest.resource.model.softwaremodule; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; - -import org.springframework.hateoas.ResourceSupport; - -/** - * List representation of the {@link SoftwareModuleRest} because Spring MVC - * cannot handle plain lists interfaces as request body. - * - * - * - * - */ -public class SoftwareModulesRest extends ResourceSupport implements List { - - private final List delegate = new ArrayList<>(); - - /** - * @return - * @see java.util.List#size() - */ - @Override - public int size() { - return delegate.size(); - } - - /** - * @return - * @see java.util.List#isEmpty() - */ - @Override - public boolean isEmpty() { - return delegate.isEmpty(); - } - - /** - * @param o - * @return - * @see java.util.List#contains(java.lang.Object) - */ - @Override - public boolean contains(final Object o) { - return delegate.contains(o); - } - - /** - * @return - * @see java.util.List#iterator() - */ - @Override - public Iterator iterator() { - return delegate.iterator(); - } - - /** - * @return - * @see java.util.List#toArray() - */ - @Override - public Object[] toArray() { - return delegate.toArray(); - } - - /** - * @param a - * @return - * @see java.util.List#toArray(java.lang.Object[]) - */ - @Override - public T[] toArray(final T[] a) { - return delegate.toArray(a); - } - - /** - * @param e - * @return - * @see java.util.List#add(java.lang.Object) - */ - @Override - public boolean add(final SoftwareModuleRest e) { - return delegate.add(e); - } - - /** - * @param o - * @return - * @see java.util.List#remove(java.lang.Object) - */ - @Override - public boolean remove(final Object o) { - return delegate.remove(o); - } - - /** - * @param c - * @return - * @see java.util.List#containsAll(java.util.Collection) - */ - @Override - public boolean containsAll(final Collection c) { - return delegate.containsAll(c); - } - - /** - * @param c - * @return - * @see java.util.List#addAll(java.util.Collection) - */ - @Override - public boolean addAll(final Collection c) { - return delegate.addAll(c); - } - - /** - * @param index - * @param c - * @return - * @see java.util.List#addAll(int, java.util.Collection) - */ - @Override - public boolean addAll(final int index, final Collection c) { - return delegate.addAll(index, c); - } - - /** - * @param c - * @return - * @see java.util.List#removeAll(java.util.Collection) - */ - @Override - public boolean removeAll(final Collection c) { - return delegate.removeAll(c); - } - - /** - * @param c - * @return - * @see java.util.List#retainAll(java.util.Collection) - */ - @Override - public boolean retainAll(final Collection c) { - return delegate.retainAll(c); - } - - /** - * - * @see java.util.List#clear() - */ - @Override - public void clear() { - delegate.clear(); - } - - /** - * @param o - * @return - * @see java.util.List#equals(java.lang.Object) - */ - @Override - public boolean equals(final Object o) { - return delegate.equals(o); - } - - /** - * @return - * @see java.util.List#hashCode() - */ - @Override - public int hashCode() { - return delegate.hashCode(); - } - - /** - * @param index - * @return - * @see java.util.List#get(int) - */ - @Override - public SoftwareModuleRest get(final int index) { - return delegate.get(index); - } - - /** - * @param index - * @param element - * @return - * @see java.util.List#set(int, java.lang.Object) - */ - @Override - public SoftwareModuleRest set(final int index, final SoftwareModuleRest element) { - return delegate.set(index, element); - } - - /** - * @param index - * @param element - * @see java.util.List#add(int, java.lang.Object) - */ - @Override - public void add(final int index, final SoftwareModuleRest element) { - delegate.add(index, element); - } - - /** - * @param index - * @return - * @see java.util.List#remove(int) - */ - @Override - public SoftwareModuleRest remove(final int index) { - return delegate.remove(index); - } - - /** - * @param o - * @return - * @see java.util.List#indexOf(java.lang.Object) - */ - @Override - public int indexOf(final Object o) { - return delegate.indexOf(o); - } - - /** - * @param o - * @return - * @see java.util.List#lastIndexOf(java.lang.Object) - */ - @Override - public int lastIndexOf(final Object o) { - return delegate.lastIndexOf(o); - } - - /** - * @return - * @see java.util.List#listIterator() - */ - @Override - public ListIterator listIterator() { - return delegate.listIterator(); - } - - /** - * @param index - * @return - * @see java.util.List#listIterator(int) - */ - @Override - public ListIterator listIterator(final int index) { - return delegate.listIterator(index); - } - - /** - * @param fromIndex - * @param toIndex - * @return - * @see java.util.List#subList(int, int) - */ - @Override - public List subList(final int fromIndex, final int toIndex) { - return delegate.subList(fromIndex, toIndex); - } - -} diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/softwaremoduletype/SoftwareModuleTypePagedList.java b/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/softwaremoduletype/SoftwareModuleTypePagedList.java deleted file mode 100644 index 7e85cdca9..000000000 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/softwaremoduletype/SoftwareModuleTypePagedList.java +++ /dev/null @@ -1,39 +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.rest.resource.model.softwaremoduletype; - -import java.util.List; - -import org.eclipse.hawkbit.rest.resource.model.PagedList; - -/** - * Paged list for SoftwareModuleType. - * - */ -public class SoftwareModuleTypePagedList extends PagedList { - - private final List content; - - /** - * @param content - * @param total - */ - public SoftwareModuleTypePagedList(final List content, final long total) { - super(content, total); - this.content = content; - } - - /** - * @return the content of the paged list. Never {@code null}. - */ - public List getContent() { - return content; - } - -} diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/softwaremoduletype/SoftwareModuleTypesRest.java b/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/softwaremoduletype/SoftwareModuleTypesRest.java deleted file mode 100644 index 91f440187..000000000 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/softwaremoduletype/SoftwareModuleTypesRest.java +++ /dev/null @@ -1,274 +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.rest.resource.model.softwaremoduletype; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; - -import org.springframework.hateoas.ResourceSupport; - -/** - * List representation of the {@link SoftwareModuleTypeRest} because Spring MVC - * cannot handle plain lists interfaces as request body. - * - */ -public class SoftwareModuleTypesRest extends ResourceSupport implements List { - - private final List delegate = new ArrayList<>(); - - /** - * @return - * @see java.util.List#size() - */ - @Override - public int size() { - return delegate.size(); - } - - /** - * @return - * @see java.util.List#isEmpty() - */ - @Override - public boolean isEmpty() { - return delegate.isEmpty(); - } - - /** - * @param o - * @return - * @see java.util.List#contains(java.lang.Object) - */ - @Override - public boolean contains(final Object o) { - return delegate.contains(o); - } - - /** - * @return - * @see java.util.List#iterator() - */ - @Override - public Iterator iterator() { - return delegate.iterator(); - } - - /** - * @return - * @see java.util.List#toArray() - */ - @Override - public Object[] toArray() { - return delegate.toArray(); - } - - /** - * @param a - * @return - * @see java.util.List#toArray(java.lang.Object[]) - */ - @Override - public T[] toArray(final T[] a) { - return delegate.toArray(a); - } - - /** - * @param e - * @return - * @see java.util.List#add(java.lang.Object) - */ - @Override - public boolean add(final SoftwareModuleTypeRest e) { - return delegate.add(e); - } - - /** - * @param o - * @return - * @see java.util.List#remove(java.lang.Object) - */ - @Override - public boolean remove(final Object o) { - return delegate.remove(o); - } - - /** - * @param c - * @return - * @see java.util.List#containsAll(java.util.Collection) - */ - @Override - public boolean containsAll(final Collection c) { - return delegate.containsAll(c); - } - - /** - * @param c - * @return - * @see java.util.List#addAll(java.util.Collection) - */ - @Override - public boolean addAll(final Collection c) { - return delegate.addAll(c); - } - - /** - * @param index - * @param c - * @return - * @see java.util.List#addAll(int, java.util.Collection) - */ - @Override - public boolean addAll(final int index, final Collection c) { - return delegate.addAll(index, c); - } - - /** - * @param c - * @return - * @see java.util.List#removeAll(java.util.Collection) - */ - @Override - public boolean removeAll(final Collection c) { - return delegate.removeAll(c); - } - - /** - * @param c - * @return - * @see java.util.List#retainAll(java.util.Collection) - */ - @Override - public boolean retainAll(final Collection c) { - return delegate.retainAll(c); - } - - /** - * - * @see java.util.List#clear() - */ - @Override - public void clear() { - delegate.clear(); - } - - /** - * @param o - * @return - * @see java.util.List#equals(java.lang.Object) - */ - @Override - public boolean equals(final Object o) { - return delegate.equals(o); - } - - /** - * @return - * @see java.util.List#hashCode() - */ - @Override - public int hashCode() { - return delegate.hashCode(); - } - - /** - * @param index - * @return - * @see java.util.List#get(int) - */ - @Override - public SoftwareModuleTypeRest get(final int index) { - return delegate.get(index); - } - - /** - * @param index - * @param element - * @return - * @see java.util.List#set(int, java.lang.Object) - */ - @Override - public SoftwareModuleTypeRest set(final int index, final SoftwareModuleTypeRest element) { - return delegate.set(index, element); - } - - /** - * @param index - * @param element - * @see java.util.List#add(int, java.lang.Object) - */ - @Override - public void add(final int index, final SoftwareModuleTypeRest element) { - delegate.add(index, element); - } - - /** - * @param index - * @return - * @see java.util.List#remove(int) - */ - @Override - public SoftwareModuleTypeRest remove(final int index) { - return delegate.remove(index); - } - - /** - * @param o - * @return - * @see java.util.List#indexOf(java.lang.Object) - */ - @Override - public int indexOf(final Object o) { - return delegate.indexOf(o); - } - - /** - * @param o - * @return - * @see java.util.List#lastIndexOf(java.lang.Object) - */ - @Override - public int lastIndexOf(final Object o) { - return delegate.lastIndexOf(o); - } - - /** - * @return - * @see java.util.List#listIterator() - */ - @Override - public ListIterator listIterator() { - return delegate.listIterator(); - } - - /** - * @param index - * @return - * @see java.util.List#listIterator(int) - */ - @Override - public ListIterator listIterator(final int index) { - return delegate.listIterator(index); - } - - /** - * @param fromIndex - * @param toIndex - * @return - * @see java.util.List#subList(int, int) - */ - @Override - public List subList(final int fromIndex, final int toIndex) { - return delegate.subList(fromIndex, toIndex); - } - -} diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/tag/TagPagedList.java b/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/tag/TagPagedList.java deleted file mode 100644 index d549a9efa..000000000 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/tag/TagPagedList.java +++ /dev/null @@ -1,43 +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.rest.resource.model.tag; - -import java.util.List; - -import org.eclipse.hawkbit.rest.resource.model.PagedList; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -/** - * Paged list for tags. - * - */ -public class TagPagedList extends PagedList { - - private final List content; - - /** - * @param content - * @param total - */ - @JsonCreator - public TagPagedList(@JsonProperty("content") final List content, @JsonProperty("total") final long total) { - super(content, total); - this.content = content; - } - - /** - * @return the content of the paged list. Never {@code null}. - */ - public List getContent() { - return content; - } - -} diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/tag/TagsRest.java b/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/tag/TagsRest.java deleted file mode 100644 index df0638358..000000000 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/tag/TagsRest.java +++ /dev/null @@ -1,275 +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.rest.resource.model.tag; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; - -import org.springframework.hateoas.ResourceSupport; - -/** - * List representation of the {@link TagRest} because Spring MVC cannot handle - * plain lists interfaces as request body. - * - * - */ -public class TagsRest extends ResourceSupport implements List { - - private final List delegate = new ArrayList<>(); - - /** - * @return - * @see java.util.List#size() - */ - @Override - public int size() { - return delegate.size(); - } - - /** - * @return - * @see java.util.List#isEmpty() - */ - @Override - public boolean isEmpty() { - return delegate.isEmpty(); - } - - /** - * @param o - * @return - * @see java.util.List#contains(java.lang.Object) - */ - @Override - public boolean contains(final Object o) { - return delegate.contains(o); - } - - /** - * @return - * @see java.util.List#iterator() - */ - @Override - public Iterator iterator() { - return delegate.iterator(); - } - - /** - * @return - * @see java.util.List#toArray() - */ - @Override - public Object[] toArray() { - return delegate.toArray(); - } - - /** - * @param a - * @return - * @see java.util.List#toArray(java.lang.Object[]) - */ - @Override - public T[] toArray(final T[] a) { - return delegate.toArray(a); - } - - /** - * @param e - * @return - * @see java.util.List#add(java.lang.Object) - */ - @Override - public boolean add(final TagRest e) { - return delegate.add(e); - } - - /** - * @param o - * @return - * @see java.util.List#remove(java.lang.Object) - */ - @Override - public boolean remove(final Object o) { - return delegate.remove(o); - } - - /** - * @param c - * @return - * @see java.util.List#containsAll(java.util.Collection) - */ - @Override - public boolean containsAll(final Collection c) { - return delegate.containsAll(c); - } - - /** - * @param c - * @return - * @see java.util.List#addAll(java.util.Collection) - */ - @Override - public boolean addAll(final Collection c) { - return delegate.addAll(c); - } - - /** - * @param index - * @param c - * @return - * @see java.util.List#addAll(int, java.util.Collection) - */ - @Override - public boolean addAll(final int index, final Collection c) { - return delegate.addAll(index, c); - } - - /** - * @param c - * @return - * @see java.util.List#removeAll(java.util.Collection) - */ - @Override - public boolean removeAll(final Collection c) { - return delegate.removeAll(c); - } - - /** - * @param c - * @return - * @see java.util.List#retainAll(java.util.Collection) - */ - @Override - public boolean retainAll(final Collection c) { - return delegate.retainAll(c); - } - - /** - * - * @see java.util.List#clear() - */ - @Override - public void clear() { - delegate.clear(); - } - - /** - * @param o - * @return - * @see java.util.List#equals(java.lang.Object) - */ - @Override - public boolean equals(final Object o) { - return delegate.equals(o); - } - - /** - * @return - * @see java.util.List#hashCode() - */ - @Override - public int hashCode() { - return delegate.hashCode(); - } - - /** - * @param index - * @return - * @see java.util.List#get(int) - */ - @Override - public TagRest get(final int index) { - return delegate.get(index); - } - - /** - * @param index - * @param element - * @return - * @see java.util.List#set(int, java.lang.Object) - */ - @Override - public TagRest set(final int index, final TagRest element) { - return delegate.set(index, element); - } - - /** - * @param index - * @param element - * @see java.util.List#add(int, java.lang.Object) - */ - @Override - public void add(final int index, final TagRest element) { - delegate.add(index, element); - } - - /** - * @param index - * @return - * @see java.util.List#remove(int) - */ - @Override - public TagRest remove(final int index) { - return delegate.remove(index); - } - - /** - * @param o - * @return - * @see java.util.List#indexOf(java.lang.Object) - */ - @Override - public int indexOf(final Object o) { - return delegate.indexOf(o); - } - - /** - * @param o - * @return - * @see java.util.List#lastIndexOf(java.lang.Object) - */ - @Override - public int lastIndexOf(final Object o) { - return delegate.lastIndexOf(o); - } - - /** - * @return - * @see java.util.List#listIterator() - */ - @Override - public ListIterator listIterator() { - return delegate.listIterator(); - } - - /** - * @param index - * @return - * @see java.util.List#listIterator(int) - */ - @Override - public ListIterator listIterator(final int index) { - return delegate.listIterator(index); - } - - /** - * @param fromIndex - * @param toIndex - * @return - * @see java.util.List#subList(int, int) - */ - @Override - public List subList(final int fromIndex, final int toIndex) { - return delegate.subList(fromIndex, toIndex); - } - -} diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/target/TargetPagedList.java b/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/target/TargetPagedList.java deleted file mode 100644 index d7bb5ccca..000000000 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/target/TargetPagedList.java +++ /dev/null @@ -1,39 +0,0 @@ -/** - * Copyright (c) 2011-2015 Bosch Software Innovations GmbH, Germany. All rights reserved. - */ -package org.eclipse.hawkbit.rest.resource.model.target; - -import java.util.List; - -import org.eclipse.hawkbit.rest.resource.model.PagedList; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -/** - * Paged list for targets. - * - */ -public class TargetPagedList extends PagedList { - - private final List content; - - /** - * @param content - * @param total - */ - @JsonCreator - public TargetPagedList(@JsonProperty("content") final List content, - @JsonProperty("total") final long total) { - super(content, total); - this.content = content; - } - - /** - * @return the content of the paged list. Never {@code null}. - */ - public List getContent() { - return content; - } - -} diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/target/TargetsRest.java b/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/target/TargetsRest.java deleted file mode 100644 index 6344ee93b..000000000 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/target/TargetsRest.java +++ /dev/null @@ -1,269 +0,0 @@ -/** - * Copyright (c) 2011-2015 Bosch Software Innovations GmbH, Germany. All rights reserved. - */ -package org.eclipse.hawkbit.rest.resource.model.target; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; - -import org.springframework.hateoas.ResourceSupport; - -/** - * A list representation of the {@link TargetRest} because Spring MVC cannot - * handle plain lists interfaces as request body. - * - */ -public class TargetsRest extends ResourceSupport implements List { - - private final List delegate = new ArrayList<>(); - - /** - * @return - * @see java.util.List#size() - */ - @Override - public int size() { - return delegate.size(); - } - - /** - * @return - * @see java.util.List#isEmpty() - */ - @Override - public boolean isEmpty() { - return delegate.isEmpty(); - } - - /** - * @param o - * @return - * @see java.util.List#contains(java.lang.Object) - */ - @Override - public boolean contains(final Object o) { - return delegate.contains(o); - } - - /** - * @return - * @see java.util.List#iterator() - */ - @Override - public Iterator iterator() { - return delegate.iterator(); - } - - /** - * @return - * @see java.util.List#toArray() - */ - @Override - public Object[] toArray() { - return delegate.toArray(); - } - - /** - * @param a - * @return - * @see java.util.List#toArray(java.lang.Object[]) - */ - @Override - public T[] toArray(final T[] a) { - return delegate.toArray(a); - } - - /** - * @param e - * @return - * @see java.util.List#add(java.lang.Object) - */ - @Override - public boolean add(final TargetRest e) { - return delegate.add(e); - } - - /** - * @param o - * @return - * @see java.util.List#remove(java.lang.Object) - */ - @Override - public boolean remove(final Object o) { - return delegate.remove(o); - } - - /** - * @param c - * @return - * @see java.util.List#containsAll(java.util.Collection) - */ - @Override - public boolean containsAll(final Collection c) { - return delegate.containsAll(c); - } - - /** - * @param c - * @return - * @see java.util.List#addAll(java.util.Collection) - */ - @Override - public boolean addAll(final Collection c) { - return delegate.addAll(c); - } - - /** - * @param index - * @param c - * @return - * @see java.util.List#addAll(int, java.util.Collection) - */ - @Override - public boolean addAll(final int index, final Collection c) { - return delegate.addAll(index, c); - } - - /** - * @param c - * @return - * @see java.util.List#removeAll(java.util.Collection) - */ - @Override - public boolean removeAll(final Collection c) { - return delegate.removeAll(c); - } - - /** - * @param c - * @return - * @see java.util.List#retainAll(java.util.Collection) - */ - @Override - public boolean retainAll(final Collection c) { - return delegate.retainAll(c); - } - - /** - * - * @see java.util.List#clear() - */ - @Override - public void clear() { - delegate.clear(); - } - - /** - * @param o - * @return - * @see java.util.List#equals(java.lang.Object) - */ - @Override - public boolean equals(final Object o) { - return delegate.equals(o); - } - - /** - * @return - * @see java.util.List#hashCode() - */ - @Override - public int hashCode() { - return delegate.hashCode(); - } - - /** - * @param index - * @return - * @see java.util.List#get(int) - */ - @Override - public TargetRest get(final int index) { - return delegate.get(index); - } - - /** - * @param index - * @param element - * @return - * @see java.util.List#set(int, java.lang.Object) - */ - @Override - public TargetRest set(final int index, final TargetRest element) { - return delegate.set(index, element); - } - - /** - * @param index - * @param element - * @see java.util.List#add(int, java.lang.Object) - */ - @Override - public void add(final int index, final TargetRest element) { - delegate.add(index, element); - } - - /** - * @param index - * @return - * @see java.util.List#remove(int) - */ - @Override - public TargetRest remove(final int index) { - return delegate.remove(index); - } - - /** - * @param o - * @return - * @see java.util.List#indexOf(java.lang.Object) - */ - @Override - public int indexOf(final Object o) { - return delegate.indexOf(o); - } - - /** - * @param o - * @return - * @see java.util.List#lastIndexOf(java.lang.Object) - */ - @Override - public int lastIndexOf(final Object o) { - return delegate.lastIndexOf(o); - } - - /** - * @return - * @see java.util.List#listIterator() - */ - @Override - public ListIterator listIterator() { - return delegate.listIterator(); - } - - /** - * @param index - * @return - * @see java.util.List#listIterator(int) - */ - @Override - public ListIterator listIterator(final int index) { - return delegate.listIterator(index); - } - - /** - * @param fromIndex - * @param toIndex - * @return - * @see java.util.List#subList(int, int) - */ - @Override - public List subList(final int fromIndex, final int toIndex) { - return delegate.subList(fromIndex, toIndex); - } - -} diff --git a/hawkbit-rest-core/pom.xml b/hawkbit-rest-core/pom.xml new file mode 100644 index 000000000..a4a421f0d --- /dev/null +++ b/hawkbit-rest-core/pom.xml @@ -0,0 +1,90 @@ + + + 4.0.0 + + org.eclipse.hawkbit + hawkbit-parent + 0.2.0-SNAPSHOT + + hawkbit-rest-core + hawkBit :: REST Core + + + + + org.eclipse.hawkbit + hawkbit-repository + ${project.version} + + + org.eclipse.hawkbit + hawkbit-core + ${project.version} + + + + javax.servlet + javax.servlet-api + provided + + + org.apache.tomcat.embed + tomcat-embed-core + provided + + + + + org.easytesting + fest-assert + test + + + org.eclipse.hawkbit + hawkbit-repository + ${project.version} + tests + + + ru.yandex.qatools.allure + allure-junit-adaptor + test + + + org.springframework.boot + spring-boot-starter-test + test + + + org.json + json + test + + + + + + + org.apache.maven.plugins + maven-jar-plugin + + + + test-jar + + + + + + + \ No newline at end of file diff --git a/hawkbit-rest-core/src/main/java/org/eclipse/hawkbit/rest/configuration/RestConfiguration.java b/hawkbit-rest-core/src/main/java/org/eclipse/hawkbit/rest/configuration/RestConfiguration.java new file mode 100644 index 000000000..e2c4ec2a1 --- /dev/null +++ b/hawkbit-rest-core/src/main/java/org/eclipse/hawkbit/rest/configuration/RestConfiguration.java @@ -0,0 +1,52 @@ +/** + * 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.rest.configuration; + +import javax.servlet.http.HttpServletResponse; + +import org.eclipse.hawkbit.rest.util.FilterHttpResponse; +import org.eclipse.hawkbit.rest.util.HttpResponseFactoryBean; +import org.eclipse.hawkbit.rest.util.RequestResponseContextHolder; +import org.springframework.beans.factory.FactoryBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Scope; +import org.springframework.web.context.WebApplicationContext; + +/** + * Configuration for Rest api. + */ +@Configuration +public class RestConfiguration { + + /** + * Create filter for {@link HttpServletResponse}. + */ + @Bean + public FilterHttpResponse filterHttpResponse() { + return new FilterHttpResponse(); + } + + /** + * Create factory bean for {@link HttpServletResponse}. + */ + @Bean + public FactoryBean httpResponseFactoryBean() { + return new HttpResponseFactoryBean(); + } + + /** + * Create factory bean for {@link HttpServletResponse}. + */ + @Bean + @Scope(value = WebApplicationContext.SCOPE_REQUEST) + public RequestResponseContextHolder requestResponseContextHolder() { + return new RequestResponseContextHolder(); + } +} diff --git a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/SortDirection.java b/hawkbit-rest-core/src/main/java/org/eclipse/hawkbit/rest/data/SortDirection.java similarity index 89% rename from hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/SortDirection.java rename to hawkbit-rest-core/src/main/java/org/eclipse/hawkbit/rest/data/SortDirection.java index 344c27ce7..ca33d25b3 100644 --- a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/SortDirection.java +++ b/hawkbit-rest-core/src/main/java/org/eclipse/hawkbit/rest/data/SortDirection.java @@ -6,7 +6,9 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource; +package org.eclipse.hawkbit.rest.data; + +import org.eclipse.hawkbit.rest.exception.SortParameterUnsupportedDirectionException; /** * A definition of possible sorting direction. diff --git a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/MessageNotReadableException.java b/hawkbit-rest-core/src/main/java/org/eclipse/hawkbit/rest/exception/MessageNotReadableException.java similarity index 95% rename from hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/MessageNotReadableException.java rename to hawkbit-rest-core/src/main/java/org/eclipse/hawkbit/rest/exception/MessageNotReadableException.java index 023b67352..3c5e0aee3 100644 --- a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/MessageNotReadableException.java +++ b/hawkbit-rest-core/src/main/java/org/eclipse/hawkbit/rest/exception/MessageNotReadableException.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource; +package org.eclipse.hawkbit.rest.exception; import org.eclipse.hawkbit.exception.SpServerError; import org.eclipse.hawkbit.exception.SpServerRtException; diff --git a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/ResponseExceptionHandler.java b/hawkbit-rest-core/src/main/java/org/eclipse/hawkbit/rest/exception/ResponseExceptionHandler.java similarity index 98% rename from hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/ResponseExceptionHandler.java rename to hawkbit-rest-core/src/main/java/org/eclipse/hawkbit/rest/exception/ResponseExceptionHandler.java index 25ddc7c4c..0f8da9ebe 100644 --- a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/ResponseExceptionHandler.java +++ b/hawkbit-rest-core/src/main/java/org/eclipse/hawkbit/rest/exception/ResponseExceptionHandler.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource; +package org.eclipse.hawkbit.rest.exception; import java.util.EnumMap; import java.util.Map; @@ -16,7 +16,7 @@ import javax.servlet.http.HttpServletRequest; import org.apache.tomcat.util.http.fileupload.FileUploadBase.FileSizeLimitExceededException; import org.eclipse.hawkbit.exception.SpServerError; import org.eclipse.hawkbit.exception.SpServerRtException; -import org.eclipse.hawkbit.rest.resource.model.ExceptionInfo; +import org.eclipse.hawkbit.rest.json.model.ExceptionInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; @@ -86,7 +86,8 @@ public class ResponseExceptionHandler { * as entity. */ @ExceptionHandler(SpServerRtException.class) - public ResponseEntity handleSpServerRtExceptions(final HttpServletRequest request, final Exception ex) { + public ResponseEntity handleSpServerRtExceptions(final HttpServletRequest request, + final Exception ex) { LOG.debug("Handling exception of request {}", request.getRequestURL()); final ExceptionInfo response = new ExceptionInfo(); final HttpStatus responseStatus; diff --git a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/SortParameterSyntaxErrorException.java b/hawkbit-rest-core/src/main/java/org/eclipse/hawkbit/rest/exception/SortParameterSyntaxErrorException.java similarity index 95% rename from hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/SortParameterSyntaxErrorException.java rename to hawkbit-rest-core/src/main/java/org/eclipse/hawkbit/rest/exception/SortParameterSyntaxErrorException.java index b6bacd9d2..a8d476ac1 100644 --- a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/SortParameterSyntaxErrorException.java +++ b/hawkbit-rest-core/src/main/java/org/eclipse/hawkbit/rest/exception/SortParameterSyntaxErrorException.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource; +package org.eclipse.hawkbit.rest.exception; import org.eclipse.hawkbit.exception.SpServerError; import org.eclipse.hawkbit.exception.SpServerRtException; diff --git a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/SortParameterUnsupportedDirectionException.java b/hawkbit-rest-core/src/main/java/org/eclipse/hawkbit/rest/exception/SortParameterUnsupportedDirectionException.java similarity index 97% rename from hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/SortParameterUnsupportedDirectionException.java rename to hawkbit-rest-core/src/main/java/org/eclipse/hawkbit/rest/exception/SortParameterUnsupportedDirectionException.java index 60fa3d8df..b44b94917 100644 --- a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/SortParameterUnsupportedDirectionException.java +++ b/hawkbit-rest-core/src/main/java/org/eclipse/hawkbit/rest/exception/SortParameterUnsupportedDirectionException.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource; +package org.eclipse.hawkbit.rest.exception; import org.eclipse.hawkbit.exception.SpServerError; import org.eclipse.hawkbit.exception.SpServerRtException; diff --git a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/SortParameterUnsupportedFieldException.java b/hawkbit-rest-core/src/main/java/org/eclipse/hawkbit/rest/exception/SortParameterUnsupportedFieldException.java similarity index 97% rename from hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/SortParameterUnsupportedFieldException.java rename to hawkbit-rest-core/src/main/java/org/eclipse/hawkbit/rest/exception/SortParameterUnsupportedFieldException.java index 20c6f03d6..c9ce0dcdd 100644 --- a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/SortParameterUnsupportedFieldException.java +++ b/hawkbit-rest-core/src/main/java/org/eclipse/hawkbit/rest/exception/SortParameterUnsupportedFieldException.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource; +package org.eclipse.hawkbit.rest.exception; import org.eclipse.hawkbit.exception.SpServerError; import org.eclipse.hawkbit.exception.SpServerRtException; diff --git a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/ExceptionInfo.java b/hawkbit-rest-core/src/main/java/org/eclipse/hawkbit/rest/json/model/ExceptionInfo.java similarity index 97% rename from hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/ExceptionInfo.java rename to hawkbit-rest-core/src/main/java/org/eclipse/hawkbit/rest/json/model/ExceptionInfo.java index e2d808943..d68e0037f 100644 --- a/hawkbit-rest-api/src/main/java/org/eclipse/hawkbit/rest/resource/model/ExceptionInfo.java +++ b/hawkbit-rest-core/src/main/java/org/eclipse/hawkbit/rest/json/model/ExceptionInfo.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource.model; +package org.eclipse.hawkbit.rest.json.model; import java.util.List; diff --git a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/helper/ByteRange.java b/hawkbit-rest-core/src/main/java/org/eclipse/hawkbit/rest/util/ByteRange.java similarity index 98% rename from hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/helper/ByteRange.java rename to hawkbit-rest-core/src/main/java/org/eclipse/hawkbit/rest/util/ByteRange.java index df72e2c53..667fc197d 100644 --- a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/helper/ByteRange.java +++ b/hawkbit-rest-core/src/main/java/org/eclipse/hawkbit/rest/util/ByteRange.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource.helper; +package org.eclipse.hawkbit.rest.util; /** * Byte range for resume download operations. diff --git a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/FileSteamingFailedException.java b/hawkbit-rest-core/src/main/java/org/eclipse/hawkbit/rest/util/FileSteamingFailedException.java similarity index 90% rename from hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/FileSteamingFailedException.java rename to hawkbit-rest-core/src/main/java/org/eclipse/hawkbit/rest/util/FileSteamingFailedException.java index b4dae3b88..abf7c0245 100644 --- a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/FileSteamingFailedException.java +++ b/hawkbit-rest-core/src/main/java/org/eclipse/hawkbit/rest/util/FileSteamingFailedException.java @@ -6,22 +6,16 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.controller; +package org.eclipse.hawkbit.rest.util; import org.eclipse.hawkbit.exception.SpServerError; import org.eclipse.hawkbit.exception.SpServerRtException; /** * Thrown if artifact content streaming to client failed. - * - * - * - * */ public final class FileSteamingFailedException extends SpServerRtException { - /** - * - */ + private static final long serialVersionUID = 1L; /** @@ -33,6 +27,8 @@ public final class FileSteamingFailedException extends SpServerRtException { } /** + * Constructor with Throwable. + * * @param cause * for the exception */ @@ -41,6 +37,8 @@ public final class FileSteamingFailedException extends SpServerRtException { } /** + * Constructor with error string. + * * @param message * of the error */ diff --git a/hawkbit-rest-core/src/main/java/org/eclipse/hawkbit/rest/util/FilterHttpResponse.java b/hawkbit-rest-core/src/main/java/org/eclipse/hawkbit/rest/util/FilterHttpResponse.java new file mode 100644 index 000000000..7620e7404 --- /dev/null +++ b/hawkbit-rest-core/src/main/java/org/eclipse/hawkbit/rest/util/FilterHttpResponse.java @@ -0,0 +1,54 @@ +/** + * 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.rest.util; + +import java.io.IOException; + +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletResponse; + +/** + * Filter is needed to autowire the {@link HttpServletResponse}. + * + */ +public class FilterHttpResponse implements Filter { + + private ThreadLocal threadLocalResponse = new ThreadLocal<>(); + + @Override + public void init(final FilterConfig filterConfig) throws ServletException { + // not needed + } + + @Override + public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) + throws IOException, ServletException { + try { + threadLocalResponse.set((HttpServletResponse) response); + chain.doFilter(request, response); + } finally { + threadLocalResponse.remove(); + } + } + + public HttpServletResponse getHttpServletReponse() { + return threadLocalResponse.get(); + } + + @Override + public void destroy() { + threadLocalResponse = null; + } + +} diff --git a/hawkbit-rest-core/src/main/java/org/eclipse/hawkbit/rest/util/HttpResponseFactoryBean.java b/hawkbit-rest-core/src/main/java/org/eclipse/hawkbit/rest/util/HttpResponseFactoryBean.java new file mode 100644 index 000000000..6df7987e6 --- /dev/null +++ b/hawkbit-rest-core/src/main/java/org/eclipse/hawkbit/rest/util/HttpResponseFactoryBean.java @@ -0,0 +1,55 @@ +/** + * 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.rest.util; + +import javax.servlet.http.HttpServletResponse; + +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.FactoryBean; +import org.springframework.beans.factory.NamedBean; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; + +/** + * + * Factory bean to autowire the {@link HttpServletResponse}. + * + */ +public class HttpResponseFactoryBean implements FactoryBean, ApplicationContextAware, NamedBean { + + public static final String FACTORY_BEAN_NAME = "httpResponseFactoryBean"; + + private ApplicationContext applicationContext; + + @Override + public HttpServletResponse getObject() throws Exception { + return applicationContext.getBean(FilterHttpResponse.class).getHttpServletReponse(); + } + + @Override + public Class getObjectType() { + return HttpServletResponse.class; + } + + @Override + public boolean isSingleton() { + return false; + } + + @Override + public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException { + this.applicationContext = applicationContext; + } + + @Override + public String getBeanName() { + return FACTORY_BEAN_NAME; + } + +} diff --git a/hawkbit-rest-core/src/main/java/org/eclipse/hawkbit/rest/util/RequestResponseContextHolder.java b/hawkbit-rest-core/src/main/java/org/eclipse/hawkbit/rest/util/RequestResponseContextHolder.java new file mode 100644 index 000000000..f25a98810 --- /dev/null +++ b/hawkbit-rest-core/src/main/java/org/eclipse/hawkbit/rest/util/RequestResponseContextHolder.java @@ -0,0 +1,43 @@ +/** + * 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.rest.util; + +import javax.annotation.Resource; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.beans.factory.annotation.Autowired; + +/** + * Store the request and response for the rest resources. + */ +public class RequestResponseContextHolder { + + private HttpServletRequest httpServletRequest; + + private HttpServletResponse httpServletResponse; + + public HttpServletRequest getHttpServletRequest() { + return httpServletRequest; + } + + public HttpServletResponse getHttpServletResponse() { + return httpServletResponse; + } + + @Autowired + public void setHttpServletRequest(final HttpServletRequest httpServletRequest) { + this.httpServletRequest = httpServletRequest; + } + + @Resource(name = HttpResponseFactoryBean.FACTORY_BEAN_NAME) + public void setHttpServletResponse(final HttpServletResponse httpServletResponse) { + this.httpServletResponse = httpServletResponse; + } +} diff --git a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/helper/RestResourceConversionHelper.java b/hawkbit-rest-core/src/main/java/org/eclipse/hawkbit/rest/util/RestResourceConversionHelper.java similarity index 89% rename from hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/helper/RestResourceConversionHelper.java rename to hawkbit-rest-core/src/main/java/org/eclipse/hawkbit/rest/util/RestResourceConversionHelper.java index e7b588222..181ccc1f8 100644 --- a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/helper/RestResourceConversionHelper.java +++ b/hawkbit-rest-core/src/main/java/org/eclipse/hawkbit/rest/util/RestResourceConversionHelper.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource.helper; +package org.eclipse.hawkbit.rest.util; import static com.google.common.base.Preconditions.checkNotNull; @@ -23,10 +23,7 @@ import javax.servlet.http.HttpServletResponse; import org.eclipse.hawkbit.artifact.repository.model.DbArtifact; import org.eclipse.hawkbit.cache.CacheWriteNotify; -import org.eclipse.hawkbit.controller.FileSteamingFailedException; -import org.eclipse.hawkbit.repository.model.Action.ActionType; import org.eclipse.hawkbit.repository.model.LocalArtifact; -import org.eclipse.hawkbit.rest.resource.model.distributionset.ActionTypeRest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; @@ -39,9 +36,6 @@ import com.google.common.net.HttpHeaders; /** * Utility class for the Rest Source API. * - * - * - * */ public final class RestResourceConversionHelper { private static final Logger LOG = LoggerFactory.getLogger(RestResourceConversionHelper.class); @@ -67,7 +61,7 @@ public final class RestResourceConversionHelper { * * @return http code */ - public static ResponseEntity writeFileResponse(final LocalArtifact artifact, + public static ResponseEntity writeFileResponse(final LocalArtifact artifact, final HttpServletResponse servletResponse, final HttpServletRequest request, final DbArtifact file) { return writeFileResponse(artifact, servletResponse, request, file, null, null); } @@ -75,7 +69,7 @@ public final class RestResourceConversionHelper { /** *

    * Write response with target relation and publishes events concerning the - * download progress based on given {@link UpdateActionStatus}. + * download progress based on given update action status. *

    * *

    @@ -95,18 +89,15 @@ public final class RestResourceConversionHelper { * @param statusId * of the UpdateActionStatus * - * @throws IOException - * in case of exceptions - * * @return http code * * @see https://tools.ietf.org/html/rfc7233 */ - public static ResponseEntity writeFileResponse(final LocalArtifact artifact, + public static ResponseEntity writeFileResponse(final LocalArtifact artifact, final HttpServletResponse response, final HttpServletRequest request, final DbArtifact file, final CacheWriteNotify cacheWriteNotify, final Long statusId) { - ResponseEntity result = null; + ResponseEntity result = null; final String etag = artifact.getSha1Hash(); final Long lastModified = artifact.getLastModifiedAt() != null ? artifact.getLastModifiedAt() @@ -187,9 +178,9 @@ public final class RestResourceConversionHelper { } } - private static ResponseEntity extractRange(final HttpServletResponse response, final long length, + private static ResponseEntity extractRange(final HttpServletResponse response, final long length, final List ranges, final String range) { - ResponseEntity result = null; + ResponseEntity result = null; if (ranges.isEmpty()) { for (final String part : range.substring(6).split(",")) { long start = sublong(part, 0, part.indexOf('-')); @@ -286,7 +277,7 @@ public final class RestResourceConversionHelper { private static long copyStreams(final InputStream from, final OutputStream to, final CacheWriteNotify cacheWriteNotify, final Long statusId, final long start, final long length) - throws IOException { + throws IOException { checkNotNull(from); checkNotNull(to); final byte[] buf = new byte[BUFFER_SIZE]; @@ -347,28 +338,4 @@ public final class RestResourceConversionHelper { return Arrays.binarySearch(matchValues, toMatch) > -1 || Arrays.binarySearch(matchValues, "*") > -1; } - /** - * Convert a action rest type to a action repository type. - * - * @param actionTypeRest - * the rest type - * @return or the action repository type - */ - public static ActionType convertActionType(final ActionTypeRest actionTypeRest) { - if (actionTypeRest == null) { - return null; - } - - switch (actionTypeRest) { - case SOFT: - return ActionType.SOFT; - case FORCED: - return ActionType.FORCED; - case TIMEFORCED: - return ActionType.TIMEFORCED; - default: - throw new IllegalStateException("Action Type is not supported"); - } - - } } diff --git a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/SortUtility.java b/hawkbit-rest-core/src/main/java/org/eclipse/hawkbit/rest/util/SortUtility.java similarity index 94% rename from hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/SortUtility.java rename to hawkbit-rest-core/src/main/java/org/eclipse/hawkbit/rest/util/SortUtility.java index f8b997bf9..d0abc47a7 100644 --- a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/SortUtility.java +++ b/hawkbit-rest-core/src/main/java/org/eclipse/hawkbit/rest/util/SortUtility.java @@ -6,12 +6,15 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource; +package org.eclipse.hawkbit.rest.util; import java.util.List; import java.util.StringTokenizer; import org.eclipse.hawkbit.repository.FieldNameProvider; +import org.eclipse.hawkbit.rest.exception.SortParameterSyntaxErrorException; +import org.eclipse.hawkbit.rest.exception.SortParameterUnsupportedDirectionException; +import org.eclipse.hawkbit.rest.exception.SortParameterUnsupportedFieldException; import org.springframework.data.domain.Sort.Direction; import org.springframework.data.domain.Sort.Order; diff --git a/hawkbit-rest-core/src/test/java/org/eclipse/hawkbit/rest/AbstractRestIntegrationTest.java b/hawkbit-rest-core/src/test/java/org/eclipse/hawkbit/rest/AbstractRestIntegrationTest.java new file mode 100644 index 000000000..38f36859b --- /dev/null +++ b/hawkbit-rest-core/src/test/java/org/eclipse/hawkbit/rest/AbstractRestIntegrationTest.java @@ -0,0 +1,33 @@ +/** + * Copyright (c) 2015 Bosch Software Innovations GmbH and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + */ +package org.eclipse.hawkbit.rest; + +import org.eclipse.hawkbit.AbstractIntegrationTest; +import org.eclipse.hawkbit.rest.configuration.RestConfiguration; +import org.eclipse.hawkbit.rest.util.FilterHttpResponse; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.test.web.servlet.setup.DefaultMockMvcBuilder; + +/** + * Abstract Test for Rest tests. + */ +@SpringApplicationConfiguration(classes = { RestConfiguration.class }) +public abstract class AbstractRestIntegrationTest extends AbstractIntegrationTest { + + @Autowired + private FilterHttpResponse filterHttpResponse; + + @Override + protected DefaultMockMvcBuilder createMvcWebAppContext() { + final DefaultMockMvcBuilder createMvcWebAppContext = super.createMvcWebAppContext(); + return createMvcWebAppContext.addFilter(filterHttpResponse); + } + +} diff --git a/hawkbit-rest-core/src/test/java/org/eclipse/hawkbit/rest/AbstractRestIntegrationTestWithMongoDB.java b/hawkbit-rest-core/src/test/java/org/eclipse/hawkbit/rest/AbstractRestIntegrationTestWithMongoDB.java new file mode 100644 index 000000000..9a25eb631 --- /dev/null +++ b/hawkbit-rest-core/src/test/java/org/eclipse/hawkbit/rest/AbstractRestIntegrationTestWithMongoDB.java @@ -0,0 +1,32 @@ +/** + * 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.rest; + +import org.eclipse.hawkbit.AbstractIntegrationTestWithMongoDB; +import org.eclipse.hawkbit.rest.configuration.RestConfiguration; +import org.eclipse.hawkbit.rest.util.FilterHttpResponse; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.SpringApplicationConfiguration; +import org.springframework.test.web.servlet.setup.DefaultMockMvcBuilder; + +/** + * Abstract Test for Rest tests. + */ +@SpringApplicationConfiguration(classes = { RestConfiguration.class }) +public abstract class AbstractRestIntegrationTestWithMongoDB extends AbstractIntegrationTestWithMongoDB { + + @Autowired + private FilterHttpResponse filterHttpResponse; + + @Override + protected DefaultMockMvcBuilder createMvcWebAppContext() { + DefaultMockMvcBuilder createMvcWebAppContext = super.createMvcWebAppContext(); + return createMvcWebAppContext.addFilter(filterHttpResponse); + } +} diff --git a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/model/ExceptionInfoTest.java b/hawkbit-rest-core/src/test/java/org/eclipse/hawkbit/rest/json/model/ExceptionInfoTest.java similarity index 95% rename from hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/model/ExceptionInfoTest.java rename to hawkbit-rest-core/src/test/java/org/eclipse/hawkbit/rest/json/model/ExceptionInfoTest.java index d240a814b..263bb75c5 100644 --- a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/model/ExceptionInfoTest.java +++ b/hawkbit-rest-core/src/test/java/org/eclipse/hawkbit/rest/json/model/ExceptionInfoTest.java @@ -6,13 +6,14 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource.model; +package org.eclipse.hawkbit.rest.json.model; import static org.fest.assertions.Assertions.assertThat; import java.util.ArrayList; import java.util.List; +import org.eclipse.hawkbit.rest.json.model.ExceptionInfo; import org.junit.Test; import ru.yandex.qatools.allure.annotations.Description; diff --git a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/JsonBuilder.java b/hawkbit-rest-core/src/test/java/org/eclipse/hawkbit/rest/util/JsonBuilder.java similarity index 99% rename from hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/JsonBuilder.java rename to hawkbit-rest-core/src/test/java/org/eclipse/hawkbit/rest/util/JsonBuilder.java index dec0bb070..b73320f0e 100644 --- a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/JsonBuilder.java +++ b/hawkbit-rest-core/src/test/java/org/eclipse/hawkbit/rest/util/JsonBuilder.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource; +package org.eclipse.hawkbit.rest.util; import java.util.ArrayList; import java.util.List; diff --git a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/MockMvcResultPrinter.java b/hawkbit-rest-core/src/test/java/org/eclipse/hawkbit/rest/util/MockMvcResultPrinter.java similarity index 97% rename from hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/MockMvcResultPrinter.java rename to hawkbit-rest-core/src/test/java/org/eclipse/hawkbit/rest/util/MockMvcResultPrinter.java index b01bb4e9f..b1de56f61 100644 --- a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/MockMvcResultPrinter.java +++ b/hawkbit-rest-core/src/test/java/org/eclipse/hawkbit/rest/util/MockMvcResultPrinter.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit; +package org.eclipse.hawkbit.rest.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/SortUtilityTest.java b/hawkbit-rest-core/src/test/java/org/eclipse/hawkbit/rest/util/SortUtilityTest.java similarity index 91% rename from hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/SortUtilityTest.java rename to hawkbit-rest-core/src/test/java/org/eclipse/hawkbit/rest/util/SortUtilityTest.java index 09a90c39c..8f1b814bf 100644 --- a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/SortUtilityTest.java +++ b/hawkbit-rest-core/src/test/java/org/eclipse/hawkbit/rest/util/SortUtilityTest.java @@ -6,14 +6,17 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource; +package org.eclipse.hawkbit.rest.util; -import static org.fest.assertions.api.Assertions.assertThat; +import static org.fest.assertions.Assertions.assertThat; import static org.junit.Assert.fail; import java.util.List; import org.eclipse.hawkbit.repository.TargetFields; +import org.eclipse.hawkbit.rest.exception.SortParameterSyntaxErrorException; +import org.eclipse.hawkbit.rest.exception.SortParameterUnsupportedDirectionException; +import org.eclipse.hawkbit.rest.exception.SortParameterUnsupportedFieldException; import org.junit.Test; import org.springframework.data.domain.Sort.Order; diff --git a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/SuccessCondition.java b/hawkbit-rest-core/src/test/java/org/eclipse/hawkbit/rest/util/SuccessCondition.java similarity index 92% rename from hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/SuccessCondition.java rename to hawkbit-rest-core/src/test/java/org/eclipse/hawkbit/rest/util/SuccessCondition.java index be6e166ef..f3424b0c0 100644 --- a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/SuccessCondition.java +++ b/hawkbit-rest-core/src/test/java/org/eclipse/hawkbit/rest/util/SuccessCondition.java @@ -6,7 +6,7 @@ * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ -package org.eclipse.hawkbit.rest.resource; +package org.eclipse.hawkbit.rest.util; /** * diff --git a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/ArtifactStoreController.java b/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/ArtifactStoreController.java deleted file mode 100644 index c2dbd3ba5..000000000 --- a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/ArtifactStoreController.java +++ /dev/null @@ -1,188 +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.controller; - -import java.io.IOException; -import java.util.List; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.eclipse.hawkbit.artifact.repository.model.DbArtifact; -import org.eclipse.hawkbit.cache.CacheWriteNotify; -import org.eclipse.hawkbit.repository.ArtifactManagement; -import org.eclipse.hawkbit.repository.ControllerManagement; -import org.eclipse.hawkbit.repository.model.Action; -import org.eclipse.hawkbit.repository.model.Action.Status; -import org.eclipse.hawkbit.repository.model.ActionStatus; -import org.eclipse.hawkbit.repository.model.Artifact; -import org.eclipse.hawkbit.repository.model.LocalArtifact; -import org.eclipse.hawkbit.repository.model.Target; -import org.eclipse.hawkbit.rest.resource.helper.RestResourceConversionHelper; -import org.eclipse.hawkbit.security.HawkbitSecurityProperties; -import org.eclipse.hawkbit.util.IpUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.security.web.bind.annotation.AuthenticationPrincipal; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.bind.annotation.RestController; - -/** - * The {@link ArtifactStoreController} of the SP server controller API that is - * queried by the SP target in order to download artifacts independent of their - * own individual resource. This is offered in addition to the - * {@link RootController#downloadArtifact(String, Long, Long, javax.servlet.http.HttpServletResponse)} - * for legacy controllers that can not be fed with a download URI at runtime. - * - * - * - * - * - */ -@RestController -@RequestMapping(ControllerConstants.ARTIFACTS_V1_REQUEST_MAPPING) -public class ArtifactStoreController { - private static final Logger LOG = LoggerFactory.getLogger(ArtifactStoreController.class); - - @Autowired - private ArtifactManagement artifactManagement; - - @Autowired - private ControllerManagement controllerManagement; - - @Autowired - private CacheWriteNotify cacheWriteNotify; - - @Autowired - private HawkbitSecurityProperties securityProperties; - - /** - * Handles GET {@link Artifact} download request. This could be full or - * partial download request. - * - * @param fileName - * to search for - * @param response - * to write to - * @param request - * from the client - * @param targetid - * of authenticated target - * - * @return response of the servlet which in case of success is status code - * {@link HttpStatus#OK} or in case of partial download - * {@link HttpStatus#PARTIAL_CONTENT}. - */ - @RequestMapping(method = RequestMethod.GET, value = ControllerConstants.ARTIFACT_DOWNLOAD_BY_FILENAME - + "/{fileName}") - @ResponseBody - public ResponseEntity downloadArtifactByFilename(@PathVariable final String fileName, - final HttpServletResponse response, final HttpServletRequest request, - @AuthenticationPrincipal final String targetid) { - ResponseEntity result; - - final List foundArtifacts = artifactManagement.findLocalArtifactByFilename(fileName); - - if (foundArtifacts.isEmpty()) { - LOG.warn("Software artifact with name {} could not be found.", fileName); - result = new ResponseEntity<>(HttpStatus.NOT_FOUND); - } else { - if (foundArtifacts.size() > 1) { - LOG.warn("Software artifact name {} is not unique. We will use the first entry.", fileName); - } - - final LocalArtifact artifact = foundArtifacts.get(0); - - final String ifMatch = request.getHeader("If-Match"); - if (ifMatch != null && !RestResourceConversionHelper.matchesHttpHeader(ifMatch, artifact.getSha1Hash())) { - result = new ResponseEntity<>(HttpStatus.PRECONDITION_FAILED); - } else { - final DbArtifact file = artifactManagement.loadLocalArtifactBinary(artifact); - - // we set a download status only if we are aware of the - // targetid, i.e. - // authenticated and not anonymous - if (targetid != null && !"anonymous".equals(targetid)) { - final Action action = checkAndReportDownloadByTarget(request, targetid, artifact); - result = RestResourceConversionHelper.writeFileResponse(artifact, response, request, file, - cacheWriteNotify, action.getId()); - } else { - result = RestResourceConversionHelper.writeFileResponse(artifact, response, request, file); - } - - } - } - - return result; - } - - private Action checkAndReportDownloadByTarget(final HttpServletRequest request, final String targetid, - final LocalArtifact artifact) { - final Target target = controllerManagement.updateLastTargetQuery(targetid, - IpUtil.getClientIpFromRequest(request, securityProperties.getClients().getRemoteIpHeader())); - - final Action action = controllerManagement - .getActionForDownloadByTargetAndSoftwareModule(target.getControllerId(), artifact.getSoftwareModule()); - final String range = request.getHeader("Range"); - - final ActionStatus actionStatus = new ActionStatus(); - actionStatus.setAction(action); - actionStatus.setOccurredAt(System.currentTimeMillis()); - actionStatus.setStatus(Status.DOWNLOAD); - - if (range != null) { - actionStatus.addMessage("It is a partial download request: " + range); - } else { - actionStatus.addMessage("Target downloads"); - } - controllerManagement.addActionStatusMessage(actionStatus); - return action; - } - - /** - * Handles GET {@link Artifact} MD5 checksum file download request. - * - * @param fileName - * to search for - * @param response - * to write to - * - * @return response of the servlet - */ - @RequestMapping(method = RequestMethod.GET, value = ControllerConstants.ARTIFACT_DOWNLOAD_BY_FILENAME - + "/{fileName}" + ControllerConstants.ARTIFACT_MD5_DWNL_SUFFIX) - @ResponseBody - public ResponseEntity downloadArtifactMD5ByFilename(@PathVariable final String fileName, - final HttpServletResponse response) { - final List foundArtifacts = artifactManagement.findLocalArtifactByFilename(fileName); - - if (foundArtifacts.isEmpty()) { - LOG.warn("Softeare artifact with name {} could not be found.", fileName); - return new ResponseEntity<>(HttpStatus.NOT_FOUND); - } else if (foundArtifacts.size() > 1) { - LOG.error("Softeare artifact name {} is not unique.", fileName); - } - - try { - DataConversionHelper.writeMD5FileResponse(fileName, response, foundArtifacts.get(0)); - } catch (final IOException e) { - LOG.error("Failed to stream MD5 File", e); - return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); - } - - return new ResponseEntity<>(HttpStatus.OK); - } - -} 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 deleted file mode 100644 index ef4468815..000000000 --- a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/DataConversionHelper.java +++ /dev/null @@ -1,150 +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.controller; - -import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; -import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.stream.Collectors; - -import javax.servlet.http.HttpServletResponse; - -import org.eclipse.hawkbit.controller.model.Artifact; -import org.eclipse.hawkbit.controller.model.Chunk; -import org.eclipse.hawkbit.controller.model.Config; -import org.eclipse.hawkbit.controller.model.ControllerBase; -import org.eclipse.hawkbit.controller.model.Polling; -import org.eclipse.hawkbit.repository.model.Action; -import org.eclipse.hawkbit.repository.model.Action.Status; -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 com.google.common.base.Charsets; - -/** - * Utility class for the Controller API. - * - * - * - * - */ -public final class DataConversionHelper { - - // 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))) - .collect(Collectors.toList()); - - } - - private static String mapChunkLegacyKeys(final String key) { - if ("application".equals(key)) { - return "bApp"; - } - if ("runtime".equals(key)) { - return "jvm"; - } - - return key; - } - - /** - * Creates all (rest) artifacts for a given software module. - * - * @param targetid - * 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 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")); - - files.add(file); - }); - return files; - } - - static ControllerBase fromTarget(final Target target, final List actions, - final String defaultControllerPollTime, final TenantAware tenantAware) { - final ControllerBase result = new ControllerBase(new Config(new Polling(defaultControllerPollTime))); - - boolean addedUpdate = false; - boolean addedCancel = false; - final long countCancelingActions = actions.stream().filter(a -> a.getStatus() == Status.CANCELING).count(); - for (final Action action : actions) { - if (countCancelingActions <= 0 && !action.isCancelingOrCanceled() && !addedUpdate) { - // we need to add the hashcode here of the actionWithStatus - // because the action might - // have changed from 'soft' to 'forced' type and we need to - // change the payload of the - // response because of eTags. - result.add(linkTo(methodOn(RootController.class, tenantAware.getCurrentTenant()) - .getControllerBasedeploymentAction(target.getControllerId(), action.getId(), actions.hashCode(), - null)).withRel(ControllerConstants.DEPLOYMENT_BASE_ACTION)); - addedUpdate = true; - } else if (action.isCancelingOrCanceled() && !addedCancel) { - result.add(linkTo(methodOn(RootController.class, tenantAware.getCurrentTenant()) - .getControllerCancelAction(target.getControllerId(), action.getId(), null)) - .withRel(ControllerConstants.CANCEL_ACTION)); - addedCancel = true; - } - } - - if (target.getTargetInfo().isRequestControllerAttributes()) { - result.add(linkTo(methodOn(RootController.class, tenantAware.getCurrentTenant()).putConfigData(null, - target.getControllerId(), null)).withRel(ControllerConstants.CONFIG_DATA_ACTION)); - } - return result; - } - - static void writeMD5FileResponse(final String fileName, final HttpServletResponse response, - final LocalArtifact artifact) throws IOException { - final StringBuilder builder = new StringBuilder(); - builder.append(artifact.getMd5Hash()); - builder.append(" "); - builder.append(fileName); - final byte[] content = builder.toString().getBytes(Charsets.US_ASCII); - - final StringBuilder header = new StringBuilder(); - header.append("attachment;filename="); - header.append(fileName); - header.append(ControllerConstants.ARTIFACT_MD5_DWNL_SUFFIX); - - response.setContentLength(content.length); - response.setHeader("Content-Disposition", header.toString()); - - response.getOutputStream().write(content, 0, content.length); - } - -} diff --git a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/model/ControllerBase.java b/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/model/ControllerBase.java deleted file mode 100644 index d319bcf11..000000000 --- a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/controller/model/ControllerBase.java +++ /dev/null @@ -1,39 +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.controller.model; - -import org.springframework.hateoas.ResourceSupport; - -/** - * {@link ControllerBase} resource content. - * - */ -public class ControllerBase extends ResourceSupport { - - private final Config config; - - /** - * Constructor. - * - * @param config - * configuration of the SP target - */ - public ControllerBase(final Config config) { - super(); - this.config = config; - } - - /** - * @return the config - */ - public Config getConfig() { - return config; - } - -} diff --git a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/OffsetBasedPageRequest.java b/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/OffsetBasedPageRequest.java deleted file mode 100644 index 5ab6b33c6..000000000 --- a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/OffsetBasedPageRequest.java +++ /dev/null @@ -1,69 +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.rest.resource; - -import org.springframework.data.domain.PageRequest; -import org.springframework.data.domain.Sort; - -/** - * An implementation of the {@link PageRequest} which is offset based by means - * the offset is given and not the page number as in the original - * {@link PageRequest} implemntation where the offset is generated. Due that the - * REST-API is working with {@code offset} and {@code limit} parameter we need - * an offset based page request for JPA. - * - * - * - * - */ -public final class OffsetBasedPageRequest extends PageRequest { - - private static final long serialVersionUID = 1L; - private final int offset; - - /** - * Creates a new {@link OffsetBasedPageRequest}. Offsets are zero indexed, - * thus providing 0 for {@code offset} will return the first entry. - * - * @param offset - * zero-based offset index. - * @param limit - * the limit of the page to be returned. - */ - public OffsetBasedPageRequest(final int offset, final int limit) { - this(offset, limit, null); - } - - /** - * Creates a new {@link OffsetBasedPageRequest}. Offsets are zero indexed, - * thus providing 0 for {@code offset} will return the first entry. - * - * @param offset - * zero-based offset index. - * @param limit - * the limit of the page to be returned. - * @param sort - * sort can be {@literal null}. - */ - public OffsetBasedPageRequest(final int offset, final int limit, final Sort sort) { - super(0, limit, sort); - this.offset = offset; - } - - @Override - public int getOffset() { - return offset; - } - - @Override - public String toString() { - return "OffsetBasedPageRequest [offset=" + offset + ", getPageSize()=" + getPageSize() + ", getPageNumber()=" - + getPageNumber() + "]"; - } -} diff --git a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/RestModelMapper.java b/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/RestModelMapper.java deleted file mode 100644 index 52668f1f1..000000000 --- a/hawkbit-rest-resource/src/main/java/org/eclipse/hawkbit/rest/resource/RestModelMapper.java +++ /dev/null @@ -1,48 +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.rest.resource; - -import org.eclipse.hawkbit.repository.model.BaseEntity; -import org.eclipse.hawkbit.repository.model.NamedEntity; -import org.eclipse.hawkbit.rest.resource.model.BaseEntityRest; -import org.eclipse.hawkbit.rest.resource.model.NamedEntityRest; - -/** - * A mapper which maps repository model to RESTful model representation and - * back. - * - * - * - * - */ -final class RestModelMapper { - - // private constructor, utility class - private RestModelMapper() { - - } - - static void mapBaseToBase(final BaseEntityRest response, final BaseEntity base) { - response.setCreatedBy(base.getCreatedBy()); - response.setLastModifiedBy(base.getLastModifiedBy()); - if (base.getCreatedAt() != null) { - response.setCreatedAt(base.getCreatedAt()); - } - if (base.getLastModifiedAt() != null) { - response.setLastModifiedAt(base.getLastModifiedAt()); - } - } - - static void mapNamedToNamed(final NamedEntityRest response, final NamedEntity base) { - mapBaseToBase(response, base); - - response.setName(base.getName()); - response.setDescription(base.getDescription()); - } -} diff --git a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/ConfigurationResourceTest.java b/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/ConfigurationResourceTest.java deleted file mode 100644 index 39e571a2c..000000000 --- a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/ConfigurationResourceTest.java +++ /dev/null @@ -1,146 +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.rest.resource; - -import static org.fest.assertions.api.Assertions.assertThat; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.Matchers.hasSize; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import org.eclipse.hawkbit.AbstractIntegrationTest; -import org.eclipse.hawkbit.MockMvcResultPrinter; -import org.eclipse.hawkbit.exception.SpServerError; -import org.eclipse.hawkbit.repository.model.TenantConfigurationValue; -import org.eclipse.hawkbit.rest.resource.model.ExceptionInfo; -import org.eclipse.hawkbit.tenancy.configuration.TenantConfigurationKey; -import org.junit.Test; -import org.springframework.http.MediaType; -import org.springframework.test.web.servlet.MvcResult; -import org.springframework.test.web.servlet.ResultActions; - -import ru.yandex.qatools.allure.annotations.Description; -import ru.yandex.qatools.allure.annotations.Features; -import ru.yandex.qatools.allure.annotations.Stories; - -@Features("Component Tests - Management RESTful API") -@Stories("ConfigurationResource") -public class ConfigurationResourceTest extends AbstractIntegrationTest { - - private static String BASE_JSON_REQUEST_STRING = "{\"value\":\"%s\"}"; - - @Test - @Description("perform a GET request on all existing configurations.") - public void getConfigurationValues() throws Exception { - - final ResultActions resultActions = mvc.perform(get(RestConstants.SYSTEM_V1_REQUEST_MAPPING + "/configs/")) - .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) - .andExpect(jsonPath("$.*", hasSize(TenantConfigurationKey.values().length))); - - for (final TenantConfigurationKey key : TenantConfigurationKey.values()) { - - final TenantConfigurationValue confValue = tenantConfigurationManagement.getConfigurationValue(key); - resultActions.andExpect(jsonPath("$.['" + key.getKeyName() + "'].value", equalTo(confValue.getValue()))) - .andExpect(jsonPath("$.['" + key.getKeyName() + "'].global", equalTo(confValue.isGlobal()))); - } - } - - @Test - @Description("perform a GET request on a existing configuration key.") - public void getConfigurationValue() throws Exception { - - final TenantConfigurationKey key = TenantConfigurationKey.AUTHENTICATION_MODE_HEADER_AUTHORITY_NAME; - final String notGlobalValue = "notTheGlobalHeaderAuthoryName"; - - tenantConfigurationManagement.addOrUpdateConfiguration(key, notGlobalValue); - - mvc.perform(get(RestConstants.SYSTEM_V1_REQUEST_MAPPING + "/configs/{configId}/", key.getKeyName())) - .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()) - .andExpect(jsonPath("value", equalTo(notGlobalValue))).andExpect(jsonPath("global", equalTo(false))) - .andExpect(jsonPath("createdAt", notNullValue())).andExpect(jsonPath("createdBy", notNullValue())); - } - - @Test - @Description("perform a PUT request on a existing configuration key with a valid value.") - public void putConfigurationValue() throws Exception { - - final TenantConfigurationKey key = TenantConfigurationKey.AUTHENTICATION_MODE_HEADER_AUTHORITY_NAME; - final String testValue = "12:12:12"; - - mvc.perform(put(RestConstants.SYSTEM_V1_REQUEST_MAPPING + "/configs/{configId}/", key.getKeyName()) - .content(String.format(BASE_JSON_REQUEST_STRING, testValue)).contentType(MediaType.APPLICATION_JSON)) - .andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); - - assertThat(tenantConfigurationManagement.getConfigurationValue(key, String.class).getValue()) - .isEqualTo(testValue); - } - - @Test - @Description("perform a DELETE request on a existing configuration key.") - public void deleteConfigurationValue() throws Exception { - - final TenantConfigurationKey key = TenantConfigurationKey.AUTHENTICATION_MODE_HEADER_AUTHORITY_NAME; - final String notGlobalValue = "notTheGlobalHeaderAuthoryName"; - - tenantConfigurationManagement.addOrUpdateConfiguration(key, notGlobalValue); - assertThat(tenantConfigurationManagement.getConfigurationValue(key, String.class).isGlobal()).isEqualTo(false); - - assertThat(tenantConfigurationManagement.getConfigurationValue(key, String.class).getValue()) - .isEqualTo(notGlobalValue); - - mvc.perform(delete(RestConstants.SYSTEM_V1_REQUEST_MAPPING + "/configs/{configId}/", key.getKeyName())) - .andDo(MockMvcResultPrinter.print()).andExpect(status().isNoContent()); - - assertThat(tenantConfigurationManagement.getConfigurationValue(key, String.class).isGlobal()).isEqualTo(true); - assertThat(tenantConfigurationManagement.getConfigurationValue(key, String.class).getValue()) - .isNotEqualTo(notGlobalValue); - } - - @Test - @Description("perform a (put) request on a not existing configuration key.") - public void putInvalidConfigurationKey() throws Exception { - - final String notExistingKey = "notExistingKey"; - final String testValue = "12:12:12"; - - final MvcResult mvcResult = mvc - .perform(put(RestConstants.SYSTEM_V1_REQUEST_MAPPING + "/configs/{configId}", notExistingKey) - .content(String.format(BASE_JSON_REQUEST_STRING, testValue)) - .contentType(MediaType.APPLICATION_JSON)) - .andDo(MockMvcResultPrinter.print()).andExpect(status().isBadRequest()).andReturn(); - - // verify response json exception message - final ExceptionInfo exceptionInfo = ResourceUtility - .convertException(mvcResult.getResponse().getContentAsString()); - assertThat(exceptionInfo.getErrorCode()).isEqualTo(SpServerError.SP_CONFIGURATION_KEY_INVALID.getKey()); - } - - @Test - @Description("perform a put request with a not matching configuration value.") - public void putInvalidConfigurationValue() throws Exception { - - final TenantConfigurationKey key = TenantConfigurationKey.POLLING_TIME_INTERVAL; - final String testValue = "invalidFormattedDuration"; - - final MvcResult mvcResult = mvc - .perform(put(RestConstants.SYSTEM_V1_REQUEST_MAPPING + "/configs/{configId}", key.getKeyName()) - .content(String.format(BASE_JSON_REQUEST_STRING, testValue)) - .contentType(MediaType.APPLICATION_JSON)) - .andDo(MockMvcResultPrinter.print()).andExpect(status().isBadRequest()).andReturn(); - - // verify response json exception message - final ExceptionInfo exceptionInfo = ResourceUtility - .convertException(mvcResult.getResponse().getContentAsString()); - assertThat(exceptionInfo.getErrorCode()).isEqualTo(SpServerError.SP_CONFIGURATION_VALUE_INVALID.getKey()); - } -} diff --git a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/SystemManagementResourceTest.java b/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/SystemManagementResourceTest.java deleted file mode 100644 index 76cd68d64..000000000 --- a/hawkbit-rest-resource/src/test/java/org/eclipse/hawkbit/rest/resource/SystemManagementResourceTest.java +++ /dev/null @@ -1,175 +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.rest.resource; - -import static org.fest.assertions.api.Assertions.assertThat; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import java.io.ByteArrayInputStream; -import java.util.List; -import java.util.Random; - -import org.eclipse.hawkbit.AbstractIntegrationTestWithMongoDB; -import org.eclipse.hawkbit.MockMvcResultPrinter; -import org.eclipse.hawkbit.TestDataUtil; -import org.eclipse.hawkbit.WithSpringAuthorityRule; -import org.eclipse.hawkbit.WithUser; -import org.eclipse.hawkbit.im.authentication.SpPermission; -import org.eclipse.hawkbit.repository.model.DistributionSet; -import org.eclipse.hawkbit.repository.model.SoftwareModule; -import org.eclipse.hawkbit.repository.model.Target; -import org.junit.Test; -import org.springframework.http.MediaType; - -import ru.yandex.qatools.allure.annotations.Description; -import ru.yandex.qatools.allure.annotations.Features; -import ru.yandex.qatools.allure.annotations.Stories; - -/** - * - * - */ -@Features("Component Tests - Management API") -@Stories("System Management Resource") -public class SystemManagementResourceTest extends AbstractIntegrationTestWithMongoDB { - - @Test - @WithUser(tenantId = "mytenant", authorities = { SpPermission.SYSTEM_ADMIN }) - @Description("Tests that the system is able to collect statistics for the entire system.") - public void collectSystemStatistics() throws Exception { - createTestTenantsForSystemStatistics(2, 2000, 100, 2); - - mvc.perform(get("/system/admin/usage").accept(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()) - .andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andExpect(jsonPath("$tenantStats.[?(@.tenantName==tenant0)][0].targets", equalTo(100))) - .andExpect(jsonPath("$tenantStats.[?(@.tenantName==tenant0)][0].overallArtifactVolumeInBytes", - equalTo(2000))) - .andExpect(jsonPath("$tenantStats.[?(@.tenantName==tenant0)][0].artifacts", equalTo(1))) - .andExpect(jsonPath("$tenantStats.[?(@.tenantName==tenant0)][0].actions", equalTo(200))) - .andExpect(jsonPath("$overallTargets", equalTo(200))) - .andExpect(jsonPath("$overallArtifacts", equalTo(2))) - .andExpect(jsonPath("$overallArtifactVolumeInBytes", equalTo(4000))) - .andExpect(jsonPath("$overallActions", equalTo(400))) - .andExpect(jsonPath("$overallTenants", equalTo(4))); - } - - @Test - @WithUser(tenantId = "mytenant", authorities = { SpPermission.DELETE_TARGET, SpPermission.DELETE_REPOSITORY, - SpPermission.CREATE_REPOSITORY, SpPermission.READ_REPOSITORY }) - @Description("Tests that the system is not able to collect statistics for the entire system if the .") - public void collectSystemStatisticsWithMissingPermissionFails() throws Exception { - - mvc.perform(get("/system/admin/usage").accept(MediaType.APPLICATION_JSON)).andDo(MockMvcResultPrinter.print()) - .andExpect(status().isForbidden()); - } - - @Test - @WithUser(tenantId = "mytenant", allSpPermissions = true) - @Description("Tests that a tenant can be deletd by API.") - public void deleteTenant() throws Exception { - - final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement, - distributionSetManagement); - - assertThat(distributionSetManagement.findDistributionSetById(dsA.getId())).isNotNull(); - - mvc.perform(delete("/system/admin/tenants/mytenant")).andDo(MockMvcResultPrinter.print()) - .andExpect(status().isOk()); - - assertThat(distributionSetManagement.findDistributionSetById(dsA.getId())).isNull(); - - } - - @Test - @WithUser(tenantId = "mytenant", authorities = { SpPermission.DELETE_TARGET, SpPermission.DELETE_REPOSITORY, - SpPermission.CREATE_REPOSITORY, SpPermission.READ_REPOSITORY }) - @Description("Tenant deletion is only possible for SYSTEM_ADMINs. Repository or target delete is not sufficient.") - public void deleteTenantFailsMissingPermission() throws Exception { - - final DistributionSet dsA = TestDataUtil.generateDistributionSet("", softwareManagement, - distributionSetManagement); - assertThat(distributionSetManagement.findDistributionSetById(dsA.getId())).isNotNull(); - - mvc.perform(delete("/system/admin/tenants/mytenant")).andDo(MockMvcResultPrinter.print()) - .andExpect(status().isForbidden()); - - assertThat(distributionSetManagement.findDistributionSetById(dsA.getId())).isNotNull(); - } - - @Test - public void getCachesReturnStatus200() throws Exception { - mvc.perform(get("/system/admin/caches")).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); - } - - @Test - public void invalidateCachesReturnStatus200() throws Exception { - mvc.perform(delete("/system/admin/caches")).andDo(MockMvcResultPrinter.print()).andExpect(status().isOk()); - } - - private byte[] createTestTenantsForSystemStatistics(final int tenants, final int artifactSize, final int targets, - final int updates) throws Exception { - final Random randomgen = new Random(); - final byte random[] = new byte[artifactSize]; - randomgen.nextBytes(random); - - for (int i = 0; i < tenants; i++) { - final String tenantname = "tenant" + i; - securityRule.runAs(WithSpringAuthorityRule.withUserAndTenant("bumlux", tenantname), () -> { - systemManagement.getTenantMetadata(tenantname); - if (artifactSize > 0) { - createTestArtifact(random); - createDeletedTestArtifact(random); - } - if (targets > 0) { - final List createdTargets = createTestTargets(targets); - if (updates > 0) { - for (int x = 0; x < updates; x++) { - final DistributionSet ds = TestDataUtil.generateDistributionSet("to be deployed" + x, - softwareManagement, distributionSetManagement, true); - - deploymentManagement.assignDistributionSet(ds, createdTargets); - } - } - } - - return null; - }); - } - - return random; - } - - private List createTestTargets(final int targets) { - return targetManagement - .createTargets(TestDataUtil.buildTargetFixtures(targets, "testTargetOfTenant", "testTargetOfTenant")); - } - - private void createTestArtifact(final byte[] random) { - SoftwareModule sm = new SoftwareModule(softwareManagement.findSoftwareModuleTypeByKey("os"), "name 1", - "version 1", null, null); - sm = softwareModuleRepository.save(sm); - - artifactManagement.createLocalArtifact(new ByteArrayInputStream(random), sm.getId(), "file1", false); - } - - private void createDeletedTestArtifact(final byte[] random) { - final DistributionSet ds = TestDataUtil.generateDistributionSet("deleted garbage", softwareManagement, - distributionSetManagement, true); - ds.getModules().stream().forEach(module -> { - artifactManagement.createLocalArtifact(new ByteArrayInputStream(random), module.getId(), "file1", false); - softwareManagement.deleteSoftwareModule(module); - }); - } - -} 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-core/src/main/java/org/eclipse/hawkbit/im/authentication/TenantUserPasswordAuthenticationToken.java b/hawkbit-security-core/src/main/java/org/eclipse/hawkbit/im/authentication/TenantUserPasswordAuthenticationToken.java index 3bacfac6f..77beaa698 100644 --- a/hawkbit-security-core/src/main/java/org/eclipse/hawkbit/im/authentication/TenantUserPasswordAuthenticationToken.java +++ b/hawkbit-security-core/src/main/java/org/eclipse/hawkbit/im/authentication/TenantUserPasswordAuthenticationToken.java @@ -19,12 +19,10 @@ import org.springframework.security.core.GrantedAuthority; * */ public class TenantUserPasswordAuthenticationToken extends UsernamePasswordAuthenticationToken { - - /** - * - */ private static final long serialVersionUID = 1L; + // Exception squid:S1948 - no need to be Serializable + @SuppressWarnings({ "squid:S1948" }) final Object tenant; /** diff --git a/hawkbit-security-core/src/main/java/org/eclipse/hawkbit/security/SystemSecurityContext.java b/hawkbit-security-core/src/main/java/org/eclipse/hawkbit/security/SystemSecurityContext.java index b22b54e39..f849eb541 100644 --- a/hawkbit-security-core/src/main/java/org/eclipse/hawkbit/security/SystemSecurityContext.java +++ b/hawkbit-security-core/src/main/java/org/eclipse/hawkbit/security/SystemSecurityContext.java @@ -49,6 +49,21 @@ public class SystemSecurityContext { this.tenantAware = tenantAware; } + /** + * Runs a given {@link Callable} within a system security context, which is + * permitted to call secured system code. Often the system needs to call + * secured methods by it's own without relying on the current security + * context e.g. if the current security context does not contain the + * necessary permission it's necessary to execute code as system code to + * execute necessary methods and functionality. + * + * The security context will be switched to the system code and back after + * the callable is called. + * + * @param callable + * the callable to call within the system security context + * @return the return value of the {@link Callable#call()} method. + */ public T runAsSystem(final Callable callable) { final SecurityContext oldContext = SecurityContextHolder.getContext(); try { @@ -68,6 +83,14 @@ public class SystemSecurityContext { } } + /** + * @return {@code true} if the current running code is running as system + * code block. + */ + public boolean isCurrentThreadSystemCode() { + return SecurityContextHolder.getContext().getAuthentication() instanceof SystemCodeAuthentication; + } + private static void setSystemContext() { final SecurityContextImpl securityContextImpl = new SecurityContextImpl(); securityContextImpl.setAuthentication(new SystemCodeAuthentication()); diff --git a/hawkbit-security-integration/pom.xml b/hawkbit-security-integration/pom.xml index 9d89c1806..c17317b3d 100644 --- a/hawkbit-security-integration/pom.xml +++ b/hawkbit-security-integration/pom.xml @@ -35,7 +35,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/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 deleted file mode 100644 index d9d8b9fa7..000000000 --- a/hawkbit-security-integration/src/main/java/org/eclipse/hawkbit/security/CoapAnonymousPreAuthenticatedFilter.java +++ /dev/null @@ -1,37 +0,0 @@ -/** - * Copyright (c) 2015 Bosch Software Innovations GmbH and others. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - */ -package org.eclipse.hawkbit.security; - -import org.eclipse.hawkbit.dmf.json.model.TenantSecruityToken; - -/** - * A Filter for device which download via coap. - * - * - * - */ -public class CoapAnonymousPreAuthenticatedFilter implements PreAuthenficationFilter { - - @Override - public HeaderAuthentication getPreAuthenticatedPrincipal(final TenantSecruityToken secruityToken) { - return new HeaderAuthentication(secruityToken.getControllerId(), TenantSecruityToken.COAP_TOKEN_VALUE); - } - - @Override - public HeaderAuthentication getPreAuthenticatedCredentials(final TenantSecruityToken secruityToken) { - return new HeaderAuthentication(secruityToken.getControllerId(), TenantSecruityToken.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); - } - -} 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/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/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/PreAuthTokenSourceTrustAuthenticationProvider.java b/hawkbit-security-integration/src/main/java/org/eclipse/hawkbit/security/PreAuthTokenSourceTrustAuthenticationProvider.java index ca38404f7..b4960737d 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 @@ -24,11 +24,11 @@ import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken; /** - * An spring authentication provider which supportes authentication tokens of + * An spring authentication provider which supports authentication tokens of * type {@link PreAuthenticatedAuthenticationToken} created by the * {@link ControllerPreAuthenticatedSecurityHeaderFilter}. * - * Addtionally to the authentication token providing the principal and the + * Additionally to the authentication token providing the principal and the * credentials which must be match, this authentication provider can also check * the remote IP address of the request. * @@ -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 8aa957005..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 org.eclipse.hawkbit.dmf.json.model.TenantSecruityToken; +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. @@ -25,7 +30,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 +39,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 +48,18 @@ public interface PreAuthenficationFilter { * the secruityToken * @return the extracted tenant and controller id */ - HeaderAuthentication getPreAuthenticatedCredentials(TenantSecruityToken secruityToken); + 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(); + }; } 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)); + } +} diff --git a/hawkbit-ui/README.md b/hawkbit-ui/README.md new file mode 100644 index 000000000..4bf9d67da --- /dev/null +++ b/hawkbit-ui/README.md @@ -0,0 +1,34 @@ +# hawkBit User Interface + +The hawkBit user interface is based on the Vaadin and Vaadin-Spring framework and allows to manage software updates and large scale roll-outs via a user interface. + +## Debugging client-side code +### Debug using SuperDevMode +The SuperDevMode can be used to debug client side code without any browser plugin. + +#### Using SuperDevMode with chrome : + +- Add required maven dependencies + - Add vaadin-client-compiler dependency + - Add jetty dependencies (version : 8.1x) +- Set redirect property in the AppWidgetSet.gwt.xml module descriptor as follows + - < set-configuration-property name="devModeRedirectEnabled" value="true" /> +- Create launch configuration for the SuperDevMode + - The main class to execute should be com.google.gwt.dev.codeserver.CodeServer. + - Add fully-qualified class name of widgetset (org.eclipse.hawkbit.ui.AppWidgetSet) as parameter +- Enable debug in chrome + - Chrome inspector window ▸ Click on settings icon ▸ Scripts ▸ Enable source maps option +- Run the SuperDevMode Code Server with the launch configuration created above +- Open http://localhost:8080/UI/?debug .Click on "SuperDev" button in debug console (Alternatively can directly add ?superdevmode parameter to URL) +- Widgetset is compiled and you can see the java code files loaded in 'Chrome inspector window ▸ Source tab' + + +#### Using SuperDevMode with Eclipse : + +- Install the plugin from http://sdbg.github.io/p2 +- Start the server and Super Dev Mode as mentioned above +- Create a new launch configuration in Eclipse + - Type is "Launch Chrome" + - http://localhost:8080/UI/?superdevmode +- Launch the new configuration in debug mode +- Now breakpoints in eclipse can be set diff --git a/hawkbit-ui/pom.xml b/hawkbit-ui/pom.xml index e0bde576a..6a3f76df6 100644 --- a/hawkbit-ui/pom.xml +++ b/hawkbit-ui/pom.xml @@ -8,8 +8,7 @@ http://www.eclipse.org/legal/epl-v10.html --> - + 4.0.0 org.eclipse.hawkbit @@ -28,8 +27,8 @@ -Xmx1g -Xss1024k - ${project.build.directory}/classes/VAADIN/widgetsets - ${project.build.directory}/classes/VAADIN/widgetsets + src/main/resources/VAADIN/widgetsets + src/main/resources/VAADIN/widgetsets src/main/resources true @@ -43,12 +42,12 @@ + process-classes - clean resources update-theme update-widgetset @@ -58,29 +57,47 @@ - - org.apache.maven.plugins - maven-jar-plugin - - - true - - true - true - - - CustomRenderers - 1 - org.eclipse.hawkbit.ui.customrenderers.CustomRendererWidgetSet - - - - + + org.apache.maven.plugins + maven-antrun-plugin + + + process-classes + + + + + + + + + run + + + + + + org.apache.maven.plugins + maven-jar-plugin + + + true + + true + true + + + CustomRenderers + 1 + org.eclipse.hawkbit.ui.customrenderers.CustomRendererWidgetSet + + + + - + org.eclipse.m2e lifecycle-mapping @@ -171,11 +188,11 @@ com.vaadin vaadin-server - - com.vaadin - vaadin-client - - + + com.vaadin + vaadin-client + + com.vaadin vaadin-push diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/HawkbitEventProvider.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/HawkbitEventProvider.java new file mode 100644 index 000000000..4358bb734 --- /dev/null +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/HawkbitEventProvider.java @@ -0,0 +1,60 @@ +/** + * Copyright (c) 2015 Bosch Software Innovations GmbH and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + */ +package org.eclipse.hawkbit.ui; + +import java.util.HashSet; +import java.util.Set; + +import org.eclipse.hawkbit.eventbus.event.DistributionSetTagCreatedBulkEvent; +import org.eclipse.hawkbit.eventbus.event.DistributionSetTagDeletedEvent; +import org.eclipse.hawkbit.eventbus.event.DistributionSetTagUpdateEvent; +import org.eclipse.hawkbit.eventbus.event.Event; +import org.eclipse.hawkbit.eventbus.event.RolloutChangeEvent; +import org.eclipse.hawkbit.eventbus.event.RolloutGroupChangeEvent; +import org.eclipse.hawkbit.eventbus.event.TargetCreatedEvent; +import org.eclipse.hawkbit.eventbus.event.TargetDeletedEvent; +import org.eclipse.hawkbit.eventbus.event.TargetInfoUpdateEvent; +import org.eclipse.hawkbit.eventbus.event.TargetTagCreatedBulkEvent; +import org.eclipse.hawkbit.eventbus.event.TargetTagDeletedEvent; +import org.eclipse.hawkbit.eventbus.event.TargetTagUpdateEvent; + +/** + * The default hawkbit event provider. + */ +public class HawkbitEventProvider implements UIEventProvider { + + private static final Set> SINGLE_EVENTS = new HashSet<>(6); + private static final Set> BULK_EVENTS = new HashSet<>(3); + + static { + SINGLE_EVENTS.add(TargetTagCreatedBulkEvent.class); + SINGLE_EVENTS.add(DistributionSetTagCreatedBulkEvent.class); + SINGLE_EVENTS.add(DistributionSetTagDeletedEvent.class); + SINGLE_EVENTS.add(TargetTagDeletedEvent.class); + SINGLE_EVENTS.add(DistributionSetTagUpdateEvent.class); + SINGLE_EVENTS.add(RolloutGroupChangeEvent.class); + SINGLE_EVENTS.add(RolloutChangeEvent.class); + SINGLE_EVENTS.add(TargetTagUpdateEvent.class); + + BULK_EVENTS.add(TargetCreatedEvent.class); + BULK_EVENTS.add(TargetInfoUpdateEvent.class); + BULK_EVENTS.add(TargetDeletedEvent.class); + } + + @Override + public Set> getSingleEvents() { + return SINGLE_EVENTS; + } + + @Override + public Set> getBulkEvents() { + return BULK_EVENTS; + } + +} diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/UIEventProvider.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/UIEventProvider.java new file mode 100644 index 000000000..5663ce897 --- /dev/null +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/UIEventProvider.java @@ -0,0 +1,60 @@ +/** + * Copyright (c) 2015 Bosch Software Innovations GmbH and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + */ +package org.eclipse.hawkbit.ui; + +import java.util.Collections; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +import org.eclipse.hawkbit.eventbus.event.Event; + +/** + * The UI event provider hold all supported repository events which will + * delegated to the UI. A event type can delegated as single event or bulk + * event. Bulk event means, that all events from one type is collected by the + * provider. The delegater and delegated as a list of this events. + */ +public interface UIEventProvider { + + /** + * Return all supported repository single event types. All events which this + * type are delegated to the UI as single event. + * + * @return list of provided event types. Should not be null + */ + default Set> getSingleEvents() { + return Collections.emptySet(); + } + + /** + * Return all supported repository bulk event types. All events which this + * type are delegated to the UI as a list. This list contains all collected + * events from one type. + * + * @return list of provided bulk event types. Should not be null + */ + default Set> getBulkEvents() { + return Collections.emptySet(); + } + + /** + * Return all filtered bulk event types by the given events. The default + * maps the events by class. + * + * @param allEvents + * the events + * @return list of provided bulk event types which are filtered. Should not + * be null + */ + default Set> getFilteredBulkEventsType(final List allEvents) { + return allEvents.stream().map(Event::getClass).filter(getBulkEvents()::contains).collect(Collectors.toSet()); + } + +} diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/UiProperties.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/UiProperties.java index da4e2d50e..cc880fca8 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/UiProperties.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/UiProperties.java @@ -37,6 +37,8 @@ public class UiProperties { /** * Demo user password. */ + // Exception squid:S2068 - Empty password + @SuppressWarnings({ "squid:S2068" }) private String password = ""; public String getPassword() { @@ -64,6 +66,7 @@ public class UiProperties { } } + /** * Links to potentially other systems (e.g. support, user management, * documentation etc.). @@ -227,6 +230,7 @@ public class UiProperties { } } + /** * Configuration of login view. * diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/UploadArtifactView.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/UploadArtifactView.java index 54ba5cc8e..b07aa0276 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/UploadArtifactView.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/UploadArtifactView.java @@ -15,12 +15,12 @@ import org.eclipse.hawkbit.ui.HawkbitUI; import org.eclipse.hawkbit.ui.artifacts.details.ArtifactDetailsLayout; import org.eclipse.hawkbit.ui.artifacts.event.ArtifactDetailsEvent; import org.eclipse.hawkbit.ui.artifacts.event.SoftwareModuleEvent; -import org.eclipse.hawkbit.ui.artifacts.event.SoftwareModuleEvent.SoftwareModuleEventType; import org.eclipse.hawkbit.ui.artifacts.footer.SMDeleteActionsLayout; import org.eclipse.hawkbit.ui.artifacts.smtable.SoftwareModuleTableLayout; import org.eclipse.hawkbit.ui.artifacts.smtype.SMTypeFilterLayout; import org.eclipse.hawkbit.ui.artifacts.state.ArtifactUploadState; import org.eclipse.hawkbit.ui.artifacts.upload.UploadLayout; +import org.eclipse.hawkbit.ui.common.table.BaseEntityEventType; import org.eclipse.hawkbit.ui.management.event.DragEvent; import org.eclipse.hawkbit.ui.utils.I18N; import org.eclipse.hawkbit.ui.utils.SPUIDefinitions; @@ -111,9 +111,9 @@ public class UploadArtifactView extends VerticalLayout implements View, BrowserW @EventBusListenerMethod(scope = EventScope.SESSION) void onEvent(final SoftwareModuleEvent event) { - if (event.getSoftwareModuleEventType() == SoftwareModuleEventType.MINIMIZED) { + if (BaseEntityEventType.MINIMIZED == event.getEventType()) { minimizeSwTable(); - } else if (event.getSoftwareModuleEventType() == SoftwareModuleEventType.MAXIMIZED) { + } else if (BaseEntityEventType.MAXIMIZED == event.getEventType()) { maximizeSwTable(); } } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/details/ArtifactDetailsLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/details/ArtifactDetailsLayout.java index 1bc9da65c..7c5d4153f 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/details/ArtifactDetailsLayout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/details/ArtifactDetailsLayout.java @@ -24,6 +24,7 @@ import org.eclipse.hawkbit.ui.artifacts.event.SoftwareModuleEvent; import org.eclipse.hawkbit.ui.artifacts.event.SoftwareModuleEvent.SoftwareModuleEventType; import org.eclipse.hawkbit.ui.artifacts.state.ArtifactUploadState; import org.eclipse.hawkbit.ui.common.ConfirmationDialog; +import org.eclipse.hawkbit.ui.common.table.BaseEntityEventType; import org.eclipse.hawkbit.ui.components.SPUIButton; import org.eclipse.hawkbit.ui.components.SPUIComponentProvider; import org.eclipse.hawkbit.ui.decorators.SPUIButtonStyleSmallNoBorder; @@ -110,8 +111,6 @@ public class ArtifactDetailsLayout extends VerticalLayout { private boolean fullWindowMode = false; - private UI ui; - private boolean readOnly = false; /** @@ -122,7 +121,6 @@ public class ArtifactDetailsLayout extends VerticalLayout { createComponents(); buildLayout(); eventBus.subscribe(this); - ui = UI.getCurrent(); if (artifactUploadState.getSelectedBaseSoftwareModule().isPresent()) { final SoftwareModule selectedSoftwareModule = artifactUploadState.getSelectedBaseSoftwareModule().get(); populateArtifactDetails(selectedSoftwareModule.getId(), HawkbitCommonUtil @@ -461,23 +459,23 @@ public class ArtifactDetailsLayout extends VerticalLayout { @EventBusListenerMethod(scope = EventScope.SESSION) void onEvent(final SoftwareModuleEvent softwareModuleEvent) { - if (softwareModuleEvent.getSoftwareModuleEventType() == SoftwareModuleEventType.SELECTED_SOFTWARE_MODULE) { - ui.access(() -> { - if (softwareModuleEvent.getSoftwareModule() != null) { - populateArtifactDetails(softwareModuleEvent.getSoftwareModule().getId(), - HawkbitCommonUtil.getFormattedNameVersion(softwareModuleEvent.getSoftwareModule().getName(), - softwareModuleEvent.getSoftwareModule().getVersion())); + if (BaseEntityEventType.SELECTED_ENTITY == softwareModuleEvent.getEventType()) { + UI.getCurrent().access(() -> { + if (softwareModuleEvent.getEntity() != null) { + populateArtifactDetails(softwareModuleEvent.getEntity().getId(), + HawkbitCommonUtil.getFormattedNameVersion(softwareModuleEvent.getEntity().getName(), + softwareModuleEvent.getEntity().getVersion())); } else { populateArtifactDetails(null, null); } }); } if (softwareModuleEvent.getSoftwareModuleEventType() == SoftwareModuleEventType.ARTIFACTS_CHANGED) { - ui.access(() -> { - if (softwareModuleEvent.getSoftwareModule() != null) { - populateArtifactDetails(softwareModuleEvent.getSoftwareModule().getId(), - HawkbitCommonUtil.getFormattedNameVersion(softwareModuleEvent.getSoftwareModule().getName(), - softwareModuleEvent.getSoftwareModule().getVersion())); + UI.getCurrent().access(() -> { + if (softwareModuleEvent.getEntity() != null) { + populateArtifactDetails(softwareModuleEvent.getEntity().getId(), + HawkbitCommonUtil.getFormattedNameVersion(softwareModuleEvent.getEntity().getName(), + softwareModuleEvent.getEntity().getVersion())); } else { populateArtifactDetails(null, null); } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/event/SoftwareModuleEvent.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/event/SoftwareModuleEvent.java index 3d0897dcd..95770cb8f 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/event/SoftwareModuleEvent.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/event/SoftwareModuleEvent.java @@ -9,58 +9,53 @@ package org.eclipse.hawkbit.ui.artifacts.event; import org.eclipse.hawkbit.repository.model.SoftwareModule; +import org.eclipse.hawkbit.ui.common.table.BaseEntityEvent; +import org.eclipse.hawkbit.ui.common.table.BaseEntityEventType; /** * Event to represent software add, update or delete. - * - * * */ -public class SoftwareModuleEvent { +public class SoftwareModuleEvent extends BaseEntityEvent { /** * Software module events in the Upload UI. - * - * * */ public enum SoftwareModuleEventType { - NEW_SOFTWARE_MODULE, UPDATED_SOFTWARE_MODULE, DELETE_SOFTWARE_MODULE, SELECTED_SOFTWARE_MODULE, MAXIMIZED, MINIMIZED, ARTIFACTS_CHANGED, ASSIGN_SOFTWARE_MODULE + ARTIFACTS_CHANGED, ASSIGN_SOFTWARE_MODULE } private SoftwareModuleEventType softwareModuleEventType; - private SoftwareModule softwareModule; + /** + * Creates software module event. + * + * @param entityEventType + * the event type + * @param softwareModule + * the module + */ + public SoftwareModuleEvent(final BaseEntityEventType entityEventType, final SoftwareModule softwareModule) { + super(entityEventType, softwareModule); + } /** * Creates software module event. * * @param softwareModuleEventType - * reference of {@link SoftwareModuleEventType} + * the event type * @param softwareModule - * reference of {@link SoftwareModule} + * the module */ public SoftwareModuleEvent(final SoftwareModuleEventType softwareModuleEventType, final SoftwareModule softwareModule) { - super(); + super(null, softwareModule); this.softwareModuleEventType = softwareModuleEventType; - this.softwareModule = softwareModule; } public SoftwareModuleEventType getSoftwareModuleEventType() { return softwareModuleEventType; } - public void setSoftwareModuleEventType(final SoftwareModuleEventType softwareModuleEventType) { - this.softwareModuleEventType = softwareModuleEventType; - } - - public SoftwareModule getSoftwareModule() { - return softwareModule; - } - - public void setSoftwareModule(final SoftwareModule softwareModule) { - this.softwareModule = softwareModule; - } - } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/event/UploadViewAcceptCriteria.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/event/UploadViewAcceptCriteria.java index a3f045a08..060800fb8 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/event/UploadViewAcceptCriteria.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/event/UploadViewAcceptCriteria.java @@ -14,12 +14,7 @@ import java.util.List; import java.util.Map; import org.eclipse.hawkbit.ui.common.AbstractAcceptCriteria; -import org.eclipse.hawkbit.ui.management.event.DragEvent; import org.eclipse.hawkbit.ui.utils.SPUIComponetIdProvider; -import org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions; -import org.eclipse.hawkbit.ui.utils.UINotification; -import org.springframework.beans.factory.annotation.Autowired; -import org.vaadin.spring.events.EventBus; import com.vaadin.spring.annotation.SpringComponent; import com.vaadin.spring.annotation.ViewScope; @@ -28,8 +23,6 @@ import com.vaadin.ui.Component; /** * Upload UI View for Accept criteria. * - * - * */ @SpringComponent @ViewScope @@ -41,29 +34,6 @@ public class UploadViewAcceptCriteria extends AbstractAcceptCriteria { private static final Map DROP_HINTS_CONFIGS = createDropHintConfigurations(); - @Autowired - private transient UINotification uiNotification; - - @Autowired - private transient EventBus.SessionEventBus eventBus; - - @Override - protected void analyseDragComponent(final Component compsource) { - final String sourceID = getComponentId(compsource); - final Object event = DROP_HINTS_CONFIGS.get(sourceID); - eventBus.publish(this, event); - } - - @Override - protected void hideDropHints() { - eventBus.publish(this, DragEvent.HIDE_DROP_HINT); - } - - @Override - protected void invalidDrop() { - uiNotification.displayValidationError(SPUILabelDefinitions.ACTION_NOT_ALLOWED); - } - @Override protected String getComponentId(final Component component) { String id = component.getId(); @@ -78,11 +48,6 @@ public class UploadViewAcceptCriteria extends AbstractAcceptCriteria { return DROP_HINTS_CONFIGS; } - @Override - protected void publishDragStartEvent(final Object event) { - eventBus.publish(this, event); - } - @Override protected Map> getDropConfigurations() { return DROP_CONFIGS; diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/footer/SMDeleteActionsLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/footer/SMDeleteActionsLayout.java index ef4b17da7..4cb28c2c3 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/footer/SMDeleteActionsLayout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/footer/SMDeleteActionsLayout.java @@ -8,25 +8,17 @@ */ package org.eclipse.hawkbit.ui.artifacts.footer; -import java.util.HashSet; import java.util.Set; -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; - -import org.eclipse.hawkbit.repository.SpPermissionChecker; import org.eclipse.hawkbit.ui.artifacts.event.UploadArtifactUIEvent; import org.eclipse.hawkbit.ui.artifacts.event.UploadViewAcceptCriteria; import org.eclipse.hawkbit.ui.artifacts.state.ArtifactUploadState; import org.eclipse.hawkbit.ui.common.footer.AbstractDeleteActionsLayout; +import org.eclipse.hawkbit.ui.common.table.AbstractTable; import org.eclipse.hawkbit.ui.management.event.DragEvent; -import org.eclipse.hawkbit.ui.utils.I18N; import org.eclipse.hawkbit.ui.utils.SPUIComponetIdProvider; -import org.eclipse.hawkbit.ui.utils.SPUIDefinitions; import org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions; -import org.eclipse.hawkbit.ui.utils.UINotification; import org.springframework.beans.factory.annotation.Autowired; -import org.vaadin.spring.events.EventBus; import org.vaadin.spring.events.EventScope; import org.vaadin.spring.events.annotation.EventBusListenerMethod; @@ -35,7 +27,6 @@ import com.vaadin.event.dd.acceptcriteria.AcceptCriterion; import com.vaadin.spring.annotation.SpringComponent; import com.vaadin.spring.annotation.ViewScope; import com.vaadin.ui.Component; -import com.vaadin.ui.Label; import com.vaadin.ui.Table; import com.vaadin.ui.Table.TableTransferable; import com.vaadin.ui.UI; @@ -50,18 +41,6 @@ public class SMDeleteActionsLayout extends AbstractDeleteActionsLayout { private static final long serialVersionUID = -3273982053389866299L; - @Autowired - private I18N i18n; - - @Autowired - private SpPermissionChecker permChecker; - - @Autowired - private transient EventBus.SessionEventBus eventBus; - - @Autowired - private transient UINotification notification; - @Autowired private ArtifactUploadState artifactUploadState; @@ -71,22 +50,6 @@ public class SMDeleteActionsLayout extends AbstractDeleteActionsLayout { @Autowired private UploadViewAcceptCriteria uploadViewAcceptCriteria; - @Override - @PostConstruct - protected void init() { - super.init(); - eventBus.subscribe(this); - } - - @PreDestroy - void destroy() { - /* - * It's good manners to do this, even though vaadin-spring will - * automatically unsubscribe when this UI is garbage collected. - */ - eventBus.unsubscribe(this); - } - @EventBusListenerMethod(scope = EventScope.SESSION) void onEvent(final UploadArtifactUIEvent event) { @@ -191,13 +154,9 @@ public class SMDeleteActionsLayout extends AbstractDeleteActionsLayout { private void addToDeleteList(final Table sourceTable, final TableTransferable transferable) { @SuppressWarnings("unchecked") - final Set swModuleSelected = (Set) sourceTable.getValue(); - final Set swModuleIdNameSet = new HashSet<>(); - if (!swModuleSelected.contains(transferable.getData(SPUIDefinitions.ITEMID))) { - swModuleIdNameSet.add((Long) transferable.getData(SPUIDefinitions.ITEMID)); - } else { - swModuleIdNameSet.addAll(swModuleSelected); - } + final AbstractTable swTable = (AbstractTable) sourceTable; + final Set swModuleIdNameSet = swTable.getDeletedEntityByTransferable(transferable); + swModuleIdNameSet.forEach(id -> { final String swModuleName = (String) sourceTable.getContainerDataSource().getItem(id) .getItemProperty(SPUILabelDefinitions.NAME_VERSION).getValue(); @@ -211,26 +170,11 @@ public class SMDeleteActionsLayout extends AbstractDeleteActionsLayout { updateActionsCount(count); } - @Override - protected String getNoActionsButtonLabel() { - return i18n.get("button.no.actions"); - } - - @Override - protected String getActionsButtonLabel() { - return i18n.get("button.actions"); - } - @Override protected void restoreActionCount() { updateSWActionCount(); } - @Override - protected String getUnsavedActionsWindowCaption() { - return i18n.get("caption.save.window"); - } - @Override protected void unsavedActionsWindowClosed() { final String message = uploadViewConfirmationWindowLayout.getConsolidatedMessage(); @@ -241,7 +185,7 @@ public class SMDeleteActionsLayout extends AbstractDeleteActionsLayout { @Override protected Component getUnsavedActionsWindowContent() { - uploadViewConfirmationWindowLayout.init(); + uploadViewConfirmationWindowLayout.initialize(); return uploadViewConfirmationWindowLayout; } @@ -251,33 +195,4 @@ public class SMDeleteActionsLayout extends AbstractDeleteActionsLayout { || !artifactUploadState.getSelectedDeleteSWModuleTypes().isEmpty(); } - @Override - protected boolean hasCountMessage() { - return false; - } - - @Override - protected Label getCountMessageLabel() { - return null; - } - - @Override - protected boolean hasBulkUploadPermission() { - return false; - } - - @Override - protected void showBulkUploadWindow() { - /** - * Bulk upload not supported .No implementation required. - */ - } - - @Override - protected void restoreBulkUploadStatusCount() { - /** - * Bulk upload not supported .No implementation required. - */ - } - } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/footer/UploadViewConfirmationWindowLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/footer/UploadViewConfirmationWindowLayout.java index 49e9ab59f..e6284d5d6 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/footer/UploadViewConfirmationWindowLayout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/footer/UploadViewConfirmationWindowLayout.java @@ -14,23 +14,17 @@ import java.util.List; import java.util.Map; import java.util.Set; -import javax.annotation.PostConstruct; - import org.eclipse.hawkbit.repository.SoftwareManagement; import org.eclipse.hawkbit.ui.artifacts.event.UploadArtifactUIEvent; import org.eclipse.hawkbit.ui.artifacts.state.ArtifactUploadState; import org.eclipse.hawkbit.ui.artifacts.state.CustomFile; import org.eclipse.hawkbit.ui.common.confirmwindow.layout.AbstractConfirmationWindowLayout; import org.eclipse.hawkbit.ui.common.confirmwindow.layout.ConfirmationTab; -import org.eclipse.hawkbit.ui.components.SPUIComponentProvider; -import org.eclipse.hawkbit.ui.decorators.SPUIButtonStyleSmallNoBorder; import org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil; -import org.eclipse.hawkbit.ui.utils.I18N; import org.eclipse.hawkbit.ui.utils.SPUIComponetIdProvider; import org.eclipse.hawkbit.ui.utils.SPUIDefinitions; import org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions; import org.springframework.beans.factory.annotation.Autowired; -import org.vaadin.spring.events.EventBus; import com.vaadin.data.Container; import com.vaadin.data.Item; @@ -39,8 +33,8 @@ import com.vaadin.server.FontAwesome; import com.vaadin.spring.annotation.SpringComponent; import com.vaadin.spring.annotation.ViewScope; import com.vaadin.ui.Button; +import com.vaadin.ui.Button.ClickListener; import com.vaadin.ui.Table.Align; -import com.vaadin.ui.themes.ValoTheme; /** * Abstract layout of confirm actions window. @@ -62,32 +56,12 @@ public class UploadViewConfirmationWindowLayout extends AbstractConfirmationWind private static final String DISCARD = "Discard"; - @Autowired - private I18N i18n; - @Autowired private transient SoftwareManagement softwareManagement; - @Autowired - private transient EventBus.SessionEventBus eventBus; - @Autowired private ArtifactUploadState artifactUploadState; - /** - * Initialze the component. - */ - @PostConstruct - void init() { - super.inittialize(); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.hawkbit.server.ui.common.confirmwindow.layout. - * AbstractConfirmationWindowLayout# getConfimrationTabs() - */ @Override protected Map getConfimrationTabs() { final Map tabs = new HashMap<>(); @@ -116,26 +90,13 @@ public class UploadViewConfirmationWindowLayout extends AbstractConfirmationWind // Add the discard action column tab.getTable().addGeneratedColumn(SW_DISCARD_CHGS, (source, itemId, columnId) -> { - final Button deleteswIcon = SPUIComponentProvider.getButton("", "", SPUILabelDefinitions.DISCARD, - ValoTheme.BUTTON_TINY + " " + "redicon", true, FontAwesome.REPLY, - SPUIButtonStyleSmallNoBorder.class); - deleteswIcon.setData(itemId); - deleteswIcon.setImmediate(true); - deleteswIcon.addClickListener(event -> discardSoftwareDelete(event, itemId, tab)); - return deleteswIcon; + final ClickListener clickListener = event -> discardSoftwareDelete(event, itemId, tab); + return createDiscardButton(itemId, clickListener); }); - // set the visible columns - final List visibleColumnIds = new ArrayList<>(); - final List visibleColumnLabels = new ArrayList<>(); - if (visibleColumnIds.isEmpty() && visibleColumnLabels.isEmpty()) { - visibleColumnIds.add(SW_MODULE_NAME_MSG); - visibleColumnIds.add(SW_DISCARD_CHGS); - visibleColumnLabels.add(i18n.get("upload.swModuleTable.header")); - visibleColumnLabels.add(i18n.get("header.second.deletetarget.table")); - } - tab.getTable().setVisibleColumns(visibleColumnIds.toArray()); - tab.getTable().setColumnHeaders(visibleColumnLabels.toArray(new String[0])); + tab.getTable().setVisibleColumns(SW_MODULE_NAME_MSG, SW_DISCARD_CHGS); + tab.getTable().setColumnHeaders(i18n.get("upload.swModuleTable.header"), + i18n.get("header.second.deletetarget.table")); tab.getTable().setColumnExpandRatio(SW_MODULE_NAME_MSG, SPUIDefinitions.TARGET_DISTRIBUTION_COLUMN_WIDTH); tab.getTable().setColumnExpandRatio(SW_DISCARD_CHGS, SPUIDefinitions.DISCARD_COLUMN_WIDTH); @@ -233,30 +194,14 @@ public class UploadViewConfirmationWindowLayout extends AbstractConfirmationWind // Add the discard action column tab.getTable().addGeneratedColumn(DISCARD, (source, itemId, columnId) -> { - final StringBuilder style = new StringBuilder(ValoTheme.BUTTON_TINY); - style.append(' '); - style.append("redicon"); - final Button deleteIcon = SPUIComponentProvider.getButton("", "", SPUILabelDefinitions.DISCARD, - style.toString(), true, FontAwesome.REPLY, SPUIButtonStyleSmallNoBorder.class); - deleteIcon.setData(itemId); - deleteIcon.setImmediate(true); - deleteIcon.addClickListener(event -> discardSoftwareTypeDelete( - (String) ((Button) event.getComponent()).getData(), itemId, tab)); - return deleteIcon; + final ClickListener clickListener = event -> discardSoftwareTypeDelete( + (String) ((Button) event.getComponent()).getData(), itemId, tab); + return createDiscardButton(itemId, clickListener); }); - // set the visible columns - final List visibleColumnIds = new ArrayList<>(); - final List visibleColumnLabels = new ArrayList<>(); - if (visibleColumnIds.isEmpty() && visibleColumnLabels.isEmpty()) { - visibleColumnIds.add(SW_MODULE_TYPE_NAME); - visibleColumnIds.add(DISCARD); - visibleColumnLabels.add(i18n.get("header.first.delete.swmodule.type.table")); - visibleColumnLabels.add(i18n.get("header.second.delete.swmodule.type.table")); - - } - tab.getTable().setVisibleColumns(visibleColumnIds.toArray()); - tab.getTable().setColumnHeaders(visibleColumnLabels.toArray(new String[0])); + tab.getTable().setVisibleColumns(SW_MODULE_TYPE_NAME, DISCARD); + tab.getTable().setColumnHeaders(i18n.get("header.first.delete.swmodule.type.table"), + i18n.get("header.second.delete.swmodule.type.table")); tab.getTable().setColumnExpandRatio(SW_MODULE_TYPE_NAME, 2); tab.getTable().setColumnExpandRatio(SW_DISCARD_CHGS, SPUIDefinitions.DISCARD_COLUMN_WIDTH); @@ -264,9 +209,6 @@ public class UploadViewConfirmationWindowLayout extends AbstractConfirmationWind return tab; } - /** - * @return - */ private Container getSWModuleTypeTableContainer() { final IndexedContainer contactContainer = new IndexedContainer(); contactContainer.addContainerProperty(SW_MODULE_TYPE_NAME, String.class, ""); diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtable/BaseSwModuleBeanQuery.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtable/BaseSwModuleBeanQuery.java index bb48c515a..29bea30eb 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtable/BaseSwModuleBeanQuery.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtable/BaseSwModuleBeanQuery.java @@ -16,6 +16,7 @@ import org.eclipse.hawkbit.repository.OffsetBasedPageRequest; import org.eclipse.hawkbit.repository.SoftwareManagement; import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.repository.model.SoftwareModuleType; +import org.eclipse.hawkbit.ui.common.UserDetailsFormatter; import org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil; import org.eclipse.hawkbit.ui.utils.SPDateTimeUtil; import org.eclipse.hawkbit.ui.utils.SPUIDefinitions; @@ -101,8 +102,8 @@ public class BaseSwModuleBeanQuery extends AbstractBeanQuery { + if (event.getText().equals(oldDescriptionValue) && vendorTextField.getValue().equals(oldVendorValue)) { + saveSoftware.setEnabled(false); + } else { + saveSoftware.setEnabled(true); } }); } private void addVendorTextChangeListener() { - vendorTextField.addTextChangeListener(new TextChangeListener() { - @Override - public void textChange(final TextChangeEvent event) { - if (event.getText().equals(oldVendorValue) && descTextArea.getValue().equals(oldDescriptionValue)) { - saveSoftware.setEnabled(false); - } else { - saveSoftware.setEnabled(true); - } + vendorTextField.addTextChangeListener(event -> { + if (event.getText().equals(oldVendorValue) && descTextArea.getValue().equals(oldDescriptionValue)) { + saveSoftware.setEnabled(false); + } else { + saveSoftware.setEnabled(true); } }); } @@ -280,7 +273,7 @@ public class SoftwareModuleAddUpdateWindow implements Serializable { final String description = HawkbitCommonUtil.trimAndNullIfEmpty(descTextArea.getValue()); final String type = typeComboBox.getValue() != null ? typeComboBox.getValue().toString() : null; if (mandatoryCheck(name, version, type)) { - if (HawkbitCommonUtil.isDuplicate(name, version)) { + if (HawkbitCommonUtil.isDuplicate(name, version, type)) { uiNotifcation.displayValidationError( i18n.get("message.duplicate.softwaremodule", new Object[] { name, version })); } else { @@ -290,8 +283,8 @@ public class SoftwareModuleAddUpdateWindow implements Serializable { /* display success message */ uiNotifcation.displaySuccess(i18n.get("message.save.success", new Object[] { newBaseSoftwareModule.getName() + ":" + newBaseSoftwareModule.getVersion() })); - eventBus.publish(this, new SoftwareModuleEvent(SoftwareModuleEventType.NEW_SOFTWARE_MODULE, - newBaseSoftwareModule)); + eventBus.publish(this, + new SoftwareModuleEvent(BaseEntityEventType.NEW_ENTITY, newBaseSoftwareModule)); } // close the window closeThisWindow(); @@ -310,8 +303,7 @@ public class SoftwareModuleAddUpdateWindow implements Serializable { uiNotifcation.displaySuccess(i18n.get("message.save.success", new Object[] { newSWModule.getName() + ":" + newSWModule.getVersion() })); - eventBus.publish(this, - new SoftwareModuleEvent(SoftwareModuleEventType.UPDATED_SOFTWARE_MODULE, newSWModule)); + eventBus.publish(this, new SoftwareModuleEvent(BaseEntityEventType.UPDATED_ENTITY, newSWModule)); } closeThisWindow(); } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtable/SoftwareModuleDetails.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtable/SoftwareModuleDetails.java index 6eb3e3d5d..9d535f7f5 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtable/SoftwareModuleDetails.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtable/SoftwareModuleDetails.java @@ -8,21 +8,14 @@ */ package org.eclipse.hawkbit.ui.artifacts.smtable; -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; - -import org.eclipse.hawkbit.repository.SpPermissionChecker; import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.ui.artifacts.event.SoftwareModuleEvent; -import org.eclipse.hawkbit.ui.artifacts.event.SoftwareModuleEvent.SoftwareModuleEventType; import org.eclipse.hawkbit.ui.artifacts.state.ArtifactUploadState; -import org.eclipse.hawkbit.ui.common.detailslayout.AbstractTableDetailsLayout; +import org.eclipse.hawkbit.ui.common.detailslayout.AbstractNamedVersionedEntityTableDetailsLayout; import org.eclipse.hawkbit.ui.components.SPUIComponentProvider; import org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil; -import org.eclipse.hawkbit.ui.utils.I18N; import org.eclipse.hawkbit.ui.utils.SPUIComponetIdProvider; import org.springframework.beans.factory.annotation.Autowired; -import org.vaadin.spring.events.EventBus; import org.vaadin.spring.events.EventScope; import org.vaadin.spring.events.annotation.EventBusListenerMethod; @@ -42,42 +35,16 @@ import com.vaadin.ui.Window; */ @SpringComponent @ViewScope -public class SoftwareModuleDetails extends AbstractTableDetailsLayout { +public class SoftwareModuleDetails extends AbstractNamedVersionedEntityTableDetailsLayout { private static final long serialVersionUID = -4900381301076646366L; - @Autowired - private I18N i18n; - - @Autowired - private transient EventBus.SessionEventBus eventBus; - - @Autowired - private SpPermissionChecker permissionChecker; - @Autowired private SoftwareModuleAddUpdateWindow softwareModuleAddUpdateWindow; @Autowired private ArtifactUploadState artifactUploadState; - private UI ui; - - private Long swModuleId; - - private SoftwareModule selectedSwModule; - - /** - * Initialize the component. - */ - @Override - @PostConstruct - protected void init() { - super.init(); - ui = UI.getCurrent(); - eventBus.subscribe(this); - } - @Override protected String getEditButtonId() { return SPUIComponetIdProvider.UPLOAD_SW_MODULE_EDIT_BUTTON; @@ -85,28 +52,31 @@ public class SoftwareModuleDetails extends AbstractTableDetailsLayout { @Override protected void addTabs(final TabSheet detailsTab) { - detailsTab.addTab(createDetailsLayout(), i18n.get("caption.tab.details"), null); - detailsTab.addTab(createDescriptionLayout(), i18n.get("caption.tab.description"), null); - detailsTab.addTab(createLogLayout(), i18n.get("caption.logs.tab"), null); + detailsTab.addTab(createDetailsLayout(), getI18n().get("caption.tab.details"), null); + detailsTab.addTab(createDescriptionLayout(), getI18n().get("caption.tab.description"), null); + detailsTab.addTab(createLogLayout(), getI18n().get("caption.logs.tab"), null); } @Override protected void onEdit(final ClickEvent event) { - final Window addSoftwareModule = softwareModuleAddUpdateWindow.createUpdateSoftwareModuleWindow(swModuleId); - addSoftwareModule.setCaption(i18n.get("upload.caption.update.swmodule")); + final Window addSoftwareModule = softwareModuleAddUpdateWindow + .createUpdateSoftwareModuleWindow(getSelectedBaseEntityId()); + addSoftwareModule.setCaption(getI18n().get("upload.caption.update.swmodule")); UI.getCurrent().addWindow(addSoftwareModule); addSoftwareModule.setVisible(Boolean.TRUE); } - private void populateDetails(final SoftwareModule swModule) { + @Override + protected void populateDetailsWidget() { String maxAssign = HawkbitCommonUtil.SP_STRING_EMPTY; - if (swModule != null) { - if (swModule.getType().getMaxAssignments() == Integer.MAX_VALUE) { - maxAssign = i18n.get("label.multiAssign.type"); + if (getSelectedBaseEntity() != null) { + if (getSelectedBaseEntity().getType().getMaxAssignments() == Integer.MAX_VALUE) { + maxAssign = getI18n().get("label.multiAssign.type"); } else { - maxAssign = i18n.get("label.singleAssign.type"); + maxAssign = getI18n().get("label.singleAssign.type"); } - updateSoftwareModuleDetailsLayout(swModule.getType().getName(), swModule.getVendor(), maxAssign); + updateSoftwareModuleDetailsLayout(getSelectedBaseEntity().getType().getName(), + getSelectedBaseEntity().getVendor(), maxAssign); } else { updateSoftwareModuleDetailsLayout(HawkbitCommonUtil.SP_STRING_EMPTY, HawkbitCommonUtil.SP_STRING_EMPTY, maxAssign); @@ -118,160 +88,50 @@ public class SoftwareModuleDetails extends AbstractTableDetailsLayout { detailsTabLayout.removeAllComponents(); - final Label vendorLabel = SPUIComponentProvider.createNameValueLabel(i18n.get("label.dist.details.vendor"), + final Label vendorLabel = SPUIComponentProvider.createNameValueLabel(getI18n().get("label.dist.details.vendor"), HawkbitCommonUtil.trimAndNullIfEmpty(vendor) == null ? "" : vendor); vendorLabel.setId(SPUIComponetIdProvider.DETAILS_VENDOR_LABEL_ID); detailsTabLayout.addComponent(vendorLabel); if (type != null) { - final Label typeLabel = SPUIComponentProvider.createNameValueLabel(i18n.get("label.dist.details.type"), + final Label typeLabel = SPUIComponentProvider.createNameValueLabel(getI18n().get("label.dist.details.type"), type); typeLabel.setId(SPUIComponetIdProvider.DETAILS_TYPE_LABEL_ID); detailsTabLayout.addComponent(typeLabel); } - final Label assignLabel = SPUIComponentProvider.createNameValueLabel(i18n.get("label.assigned.type"), + final Label assignLabel = SPUIComponentProvider.createNameValueLabel(getI18n().get("label.assigned.type"), HawkbitCommonUtil.trimAndNullIfEmpty(maxAssign) == null ? "" : maxAssign); assignLabel.setId(SPUIComponetIdProvider.SWM_DTLS_MAX_ASSIGN); detailsTabLayout.addComponent(assignLabel); } - private void populateLog(final SoftwareModule softwareModule) { - if (null != softwareModule) { - updateLogLayout(getLogLayout(), softwareModule.getLastModifiedAt(), softwareModule.getLastModifiedBy(), - softwareModule.getCreatedAt(), softwareModule.getCreatedBy(), i18n); - } else { - updateLogLayout(getLogLayout(), null, HawkbitCommonUtil.SP_STRING_EMPTY, null, null, i18n); - } - } - - public void setSwModuleId(final Long swModuleId) { - this.swModuleId = swModuleId; - } - - private void populateDetailsWidget(final SoftwareModule swModule) { - if (swModule != null) { - setSwModuleId(swModule.getId()); - setName(getDefaultCaption(), - HawkbitCommonUtil.getFormattedNameVersion(swModule.getName(), swModule.getVersion())); - populateDetails(swModule); - populateDescription(swModule); - populateLog(swModule); - } else { - setSwModuleId(null); - setName(getDefaultCaption(), HawkbitCommonUtil.SP_STRING_EMPTY); - populateDetails(null); - populateDescription(null); - populateLog(null); - } - } - - private void populateDescription(final SoftwareModule swModule) { - if (swModule != null) { - updateDescriptionLayout(i18n.get("label.description"), swModule.getDescription()); - } else { - updateDescriptionLayout(i18n.get("label.description"), null); - } - } - - @PreDestroy - void destroy() { - /* - * It's good manners to do this, even though vaadin-spring will - * automatically unsubscribe when this UI is garbage collected. - */ - eventBus.unsubscribe(this); - } - - /* - * (non-Javadoc) - * - * @see - * org.eclipse.hawkbit.server.ui.common.detailslayout.TableDetailsLayout# - * getDefaultCaption() - */ @Override protected String getDefaultCaption() { - return i18n.get("upload.swModuleTable.header"); + return getI18n().get("upload.swModuleTable.header"); } - /* - * (non-Javadoc) - * - * @see - * org.eclipse.hawkbit.server.ui.common.detailslayout.TableDetailsLayout# - * onLoadIsSwModuleSelected() - */ @Override protected Boolean onLoadIsTableRowSelected() { return artifactUploadState.getSelectedBaseSoftwareModule().isPresent(); } - /* - * (non-Javadoc) - * - * @see - * org.eclipse.hawkbit.server.ui.common.detailslayout.TableDetailsLayout# - * onLoadIsTableMaximized() - */ @Override protected Boolean onLoadIsTableMaximized() { return artifactUploadState.isSwModuleTableMaximized(); } - /* - * (non-Javadoc) - * - * @see - * org.eclipse.hawkbit.server.ui.common.detailslayout.TableDetailsLayout# - * populateDetailsWidget() - */ - @Override - protected void populateDetailsWidget() { - populateDetailsWidget(selectedSwModule); - } - @EventBusListenerMethod(scope = EventScope.SESSION) void onEvent(final SoftwareModuleEvent softwareModuleEvent) { - if (softwareModuleEvent.getSoftwareModuleEventType() == SoftwareModuleEventType.SELECTED_SOFTWARE_MODULE - || softwareModuleEvent - .getSoftwareModuleEventType() == SoftwareModuleEventType.UPDATED_SOFTWARE_MODULE) { - ui.access(() -> { - /** - * softwareModuleEvent.getSoftwareModule() is null when table - * has no data. - */ - if (softwareModuleEvent.getSoftwareModule() != null) { - selectedSwModule = softwareModuleEvent.getSoftwareModule(); - populateData(true); - } else { - populateData(false); - } - }); - } else if (softwareModuleEvent.getSoftwareModuleEventType() == SoftwareModuleEventType.MINIMIZED) { - showLayout(); - } else if (softwareModuleEvent.getSoftwareModuleEventType() == SoftwareModuleEventType.MAXIMIZED) { - hideLayout(); - } - } - - @Override - protected void clearDetails() { - populateDetailsWidget(null); + onBaseEntityEvent(softwareModuleEvent); } @Override protected Boolean hasEditPermission() { - return permissionChecker.hasUpdateDistributionPermission(); + return getPermissionChecker().hasUpdateDistributionPermission(); } - /* - * (non-Javadoc) - * - * @see hawkbit.server.ui.common.detailslayout.AbstractTableDetailsLayout# - * getTabSheetId() - */ @Override protected String getTabSheetId() { return null; diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtable/SoftwareModuleTable.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtable/SoftwareModuleTable.java index aea80476a..478438891 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtable/SoftwareModuleTable.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtable/SoftwareModuleTable.java @@ -8,29 +8,20 @@ */ package org.eclipse.hawkbit.ui.artifacts.smtable; -import java.util.ArrayList; -import java.util.Collections; import java.util.HashMap; -import java.util.Iterator; import java.util.List; import java.util.Map; -import java.util.Set; - -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; import org.eclipse.hawkbit.repository.SoftwareManagement; import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.ui.artifacts.event.SMFilterEvent; import org.eclipse.hawkbit.ui.artifacts.event.SoftwareModuleEvent; -import org.eclipse.hawkbit.ui.artifacts.event.SoftwareModuleEvent.SoftwareModuleEventType; import org.eclipse.hawkbit.ui.artifacts.event.UploadArtifactUIEvent; import org.eclipse.hawkbit.ui.artifacts.event.UploadViewAcceptCriteria; import org.eclipse.hawkbit.ui.artifacts.state.ArtifactUploadState; -import org.eclipse.hawkbit.ui.common.table.AbstractTable; +import org.eclipse.hawkbit.ui.common.table.AbstractNamedVersionTable; +import org.eclipse.hawkbit.ui.common.table.BaseEntityEventType; import org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil; -import org.eclipse.hawkbit.ui.utils.I18N; -import org.eclipse.hawkbit.ui.utils.SPDateTimeUtil; import org.eclipse.hawkbit.ui.utils.SPUIComponetIdProvider; import org.eclipse.hawkbit.ui.utils.SPUIDefinitions; import org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions; @@ -39,7 +30,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.vaadin.addons.lazyquerycontainer.BeanQueryFactory; import org.vaadin.addons.lazyquerycontainer.LazyQueryContainer; import org.vaadin.addons.lazyquerycontainer.LazyQueryDefinition; -import org.vaadin.spring.events.EventBus; import org.vaadin.spring.events.EventScope; import org.vaadin.spring.events.annotation.EventBusListenerMethod; @@ -58,45 +48,19 @@ import com.vaadin.ui.UI; */ @SpringComponent @ViewScope -public class SoftwareModuleTable extends AbstractTable { +public class SoftwareModuleTable extends AbstractNamedVersionTable { private static final long serialVersionUID = 6469417305487144809L; - @Autowired - private I18N i18n; - @Autowired private ArtifactUploadState artifactUploadState; - @Autowired - private transient EventBus.SessionEventBus eventBus; - @Autowired private transient SoftwareManagement softwareManagement; @Autowired private UploadViewAcceptCriteria uploadViewAcceptCriteria; - /** - * Initialize the filter layout. - */ - @Override - @PostConstruct - protected void init() { - super.init(); - eventBus.subscribe(this); - setNoDataAvailable(); - } - - @PreDestroy - void destroy() { - /* - * It's good manners to do this, even though vaadin-spring will - * automatically unsubscribe when this UI is garbage collected. - */ - eventBus.unsubscribe(this); - } - @EventBusListenerMethod(scope = EventScope.SESSION) void onEvent(final SMFilterEvent filterEvent) { UI.getCurrent().access(() -> { @@ -150,74 +114,40 @@ public class SoftwareModuleTable extends AbstractTable { lqc.addContainerProperty(SPUILabelDefinitions.VAR_LAST_MODIFIED_DATE, String.class, null, false, true); } - @Override - protected void addCustomGeneratedColumns() { - /* No generated columns */ - } - @Override protected boolean isFirstRowSelectedOnLoad() { return artifactUploadState.getSelectedSoftwareModules().isEmpty(); } - /* - * (non-Javadoc) - * - * @see - * org.eclipse.hawkbit.server.ui.common.table.SPTable#getItemIdToSelect() - */ @Override protected Object getItemIdToSelect() { return artifactUploadState.getSelectedSoftwareModules(); } - /* - * (non-Javadoc) - * - * @see org.eclipse.hawkbit.server.ui.common.table.SPTable#isMaximized() - */ @Override protected boolean isMaximized() { return artifactUploadState.isSwModuleTableMaximized(); } - @SuppressWarnings("rawtypes") @Override - protected void onValueChange() { - eventBus.publish(this, UploadArtifactUIEvent.HIDE_DROP_HINTS); - @SuppressWarnings("unchecked") - final Set values = (Set) getValue(); - if (values != null && !values.isEmpty()) { - final Iterator iterator = values.iterator(); - Long value = null; - while (iterator.hasNext()) { - value = iterator.next(); - } - if (null != value) { - artifactUploadState.setSelectedBaseSwModuleId(value); - final SoftwareModule baseSoftwareModule = softwareManagement.findSoftwareModuleById(value); - artifactUploadState.setSelectedBaseSoftwareModule(baseSoftwareModule); - artifactUploadState.setSelectedSoftwareModules(values); - eventBus.publish(this, - new SoftwareModuleEvent(SoftwareModuleEventType.SELECTED_SOFTWARE_MODULE, baseSoftwareModule)); - } - } else { - artifactUploadState.setSelectedBaseSwModuleId(null); - artifactUploadState.setSelectedBaseSoftwareModule(null); - artifactUploadState.setSelectedSoftwareModules(Collections.emptySet()); - eventBus.publish(this, new SoftwareModuleEvent(SoftwareModuleEventType.SELECTED_SOFTWARE_MODULE, null)); - } + protected SoftwareModule findEntityByTableValue(final Long entityTableId) { + return softwareManagement.findSoftwareModuleById(entityTableId); + } + + @Override + protected ArtifactUploadState getManagmentEntityState() { + return artifactUploadState; + } + + @Override + protected void publishEntityAfterValueChange(final SoftwareModule lastSoftwareModule) { + artifactUploadState.setSelectedBaseSoftwareModule(lastSoftwareModule); + eventBus.publish(this, new SoftwareModuleEvent(BaseEntityEventType.SELECTED_ENTITY, lastSoftwareModule)); } @EventBusListenerMethod(scope = EventScope.SESSION) void onEvent(final SoftwareModuleEvent event) { - if (event.getSoftwareModuleEventType() == SoftwareModuleEventType.MINIMIZED) { - UI.getCurrent().access(() -> applyMinTableSettings()); - } else if (event.getSoftwareModuleEventType() == SoftwareModuleEventType.MAXIMIZED) { - UI.getCurrent().access(() -> applyMaxTableSettings()); - } else if (event.getSoftwareModuleEventType() == SoftwareModuleEventType.NEW_SOFTWARE_MODULE) { - UI.getCurrent().access(() -> addSoftwareModule(event.getSoftwareModule())); - } + onBaseEntityEvent(event); } @EventBusListenerMethod(scope = EventScope.SESSION) @@ -227,55 +157,35 @@ public class SoftwareModuleTable extends AbstractTable { } } - /** - * Add new software module to table. - * - * @param swModule - * new software module - */ - @SuppressWarnings("unchecked") - private void addSoftwareModule(final SoftwareModule swModule) { - final Object addItem = addItem(); - final Item item = getItem(addItem); - final String swNameVersion = HawkbitCommonUtil.concatStrings(":", swModule.getName(), swModule.getVersion()); - item.getItemProperty(SPUILabelDefinitions.NAME_VERSION).setValue(swNameVersion); - item.getItemProperty("swId").setValue(swModule.getId()); - item.getItemProperty(SPUILabelDefinitions.VAR_ID).setValue(swModule.getId()); - item.getItemProperty(SPUILabelDefinitions.VAR_DESC).setValue(swModule.getDescription()); - item.getItemProperty(SPUILabelDefinitions.VAR_VERSION).setValue(swModule.getVersion()); - item.getItemProperty(SPUILabelDefinitions.VAR_NAME).setValue(swModule.getName()); - item.getItemProperty(SPUILabelDefinitions.VAR_VENDOR).setValue(swModule.getVendor()); - item.getItemProperty(SPUILabelDefinitions.VAR_CREATED_BY).setValue(swModule.getCreatedBy()); - item.getItemProperty(SPUILabelDefinitions.VAR_LAST_MODIFIED_BY).setValue(swModule.getLastModifiedBy()); - item.getItemProperty(SPUILabelDefinitions.VAR_CREATED_DATE) - .setValue(SPDateTimeUtil.getFormattedDate(swModule.getCreatedAt())); - item.getItemProperty(SPUILabelDefinitions.VAR_LAST_MODIFIED_DATE) - .setValue(SPDateTimeUtil.getFormattedDate(swModule.getLastModifiedAt())); + @Override + protected Item addEntity(final SoftwareModule baseEntity) { + final Item item = super.addEntity(baseEntity); if (!artifactUploadState.getSelectedSoftwareModules().isEmpty()) { - artifactUploadState.getSelectedSoftwareModules().stream().forEach(swmNameId -> unselect(swmNameId)); + artifactUploadState.getSelectedSoftwareModules().stream().forEach(this::unselect); } - select(swModule.getId()); + select(baseEntity.getId()); + return item; + + } + + @SuppressWarnings("unchecked") + @Override + protected void updateEntity(final SoftwareModule baseEntity, final Item item) { + final String swNameVersion = HawkbitCommonUtil.concatStrings(":", baseEntity.getName(), + baseEntity.getVersion()); + item.getItemProperty(SPUILabelDefinitions.NAME_VERSION).setValue(swNameVersion); + item.getItemProperty("swId").setValue(baseEntity.getId()); + item.getItemProperty(SPUILabelDefinitions.VAR_VENDOR).setValue(baseEntity.getVendor()); + super.updateEntity(baseEntity, item); } @Override protected List getTableVisibleColumns() { - final List columnList = new ArrayList<>(); - if (isMaximized()) { - columnList.add(new TableColumn(SPUILabelDefinitions.VAR_NAME, i18n.get("header.name"), 0.2F)); - columnList.add(new TableColumn(SPUILabelDefinitions.VAR_VERSION, i18n.get("header.version"), 0.1F)); - columnList.add(new TableColumn(SPUILabelDefinitions.VAR_VENDOR, i18n.get("header.vendor"), 0.1F)); - columnList.add(new TableColumn(SPUILabelDefinitions.VAR_CREATED_BY, i18n.get("header.createdBy"), 0.1F)); - columnList - .add(new TableColumn(SPUILabelDefinitions.VAR_CREATED_DATE, i18n.get("header.createdDate"), 0.1F)); - columnList.add( - new TableColumn(SPUILabelDefinitions.VAR_LAST_MODIFIED_BY, i18n.get("header.modifiedBy"), 0.1F)); - columnList.add(new TableColumn(SPUILabelDefinitions.VAR_LAST_MODIFIED_DATE, i18n.get("header.modifiedDate"), - 0.1F)); - columnList.add(new TableColumn(SPUILabelDefinitions.VAR_DESC, i18n.get("header.description"), 0.2F)); - } else { - columnList.add(new TableColumn(SPUILabelDefinitions.VAR_NAME, i18n.get("header.name"), 0.8F)); - columnList.add(new TableColumn(SPUILabelDefinitions.VAR_VERSION, i18n.get("header.version"), 0.2F)); + final List columnList = super.getTableVisibleColumns(); + if (!isMaximized()) { + return columnList; } + columnList.add(new TableColumn(SPUILabelDefinitions.VAR_VENDOR, i18n.get("header.vendor"), 0.1F)); return columnList; } @@ -297,12 +207,8 @@ public class SoftwareModuleTable extends AbstractTable { }; } - private void setNoDataAvailable() { - final int containerSize = getContainerDataSource().size(); - if (containerSize == 0) { - artifactUploadState.setNoDataAvilableSoftwareModule(true); - } else { - artifactUploadState.setNoDataAvilableSoftwareModule(false); - } + @Override + protected void setDataAvailable(final boolean available) { + artifactUploadState.setNoDataAvilableSoftwareModule(!available); } } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtable/SoftwareModuleTableHeader.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtable/SoftwareModuleTableHeader.java index 71605ec9f..16ef3154c 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtable/SoftwareModuleTableHeader.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtable/SoftwareModuleTableHeader.java @@ -8,20 +8,14 @@ */ package org.eclipse.hawkbit.ui.artifacts.smtable; -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; - -import org.eclipse.hawkbit.repository.SpPermissionChecker; import org.eclipse.hawkbit.ui.artifacts.event.SMFilterEvent; import org.eclipse.hawkbit.ui.artifacts.event.SoftwareModuleEvent; -import org.eclipse.hawkbit.ui.artifacts.event.SoftwareModuleEvent.SoftwareModuleEventType; import org.eclipse.hawkbit.ui.artifacts.event.UploadArtifactUIEvent; import org.eclipse.hawkbit.ui.artifacts.state.ArtifactUploadState; import org.eclipse.hawkbit.ui.common.table.AbstractTableHeader; -import org.eclipse.hawkbit.ui.utils.I18N; +import org.eclipse.hawkbit.ui.common.table.BaseEntityEventType; import org.eclipse.hawkbit.ui.utils.SPUIComponetIdProvider; import org.springframework.beans.factory.annotation.Autowired; -import org.vaadin.spring.events.EventBus; import org.vaadin.spring.events.EventScope; import org.vaadin.spring.events.annotation.EventBusListenerMethod; @@ -44,31 +38,12 @@ public class SoftwareModuleTableHeader extends AbstractTableHeader { private static final long serialVersionUID = 242961845006626297L; - @Autowired - private I18N i18n; - - @Autowired - private SpPermissionChecker permChecker; - - @Autowired - private transient EventBus.SessionEventBus eventbus; - @Autowired private ArtifactUploadState artifactUploadState; @Autowired private SoftwareModuleAddUpdateWindow softwareModuleAddUpdateWindow; - /** - * Initialize the components. - */ - @Override - @PostConstruct - protected void init() { - super.init(); - eventbus.subscribe(this); - } - @EventBusListenerMethod(scope = EventScope.SESSION) void onEvent(final UploadArtifactUIEvent event) { if (event == UploadArtifactUIEvent.HIDE_FILTER_BY_TYPE) { @@ -76,15 +51,6 @@ public class SoftwareModuleTableHeader extends AbstractTableHeader { } } - @PreDestroy - void destroy() { - /* - * It's good manners to do this, even though vaadin-spring will - * automatically unsubscribe when this UI is garbage collected. - */ - eventbus.unsubscribe(this); - } - @Override protected String getHeaderCaption() { return i18n.get("upload.swModuleTable.header"); @@ -164,14 +130,14 @@ public class SoftwareModuleTableHeader extends AbstractTableHeader { @Override public void maximizeTable() { artifactUploadState.setSwModuleTableMaximized(Boolean.TRUE); - eventbus.publish(this, new SoftwareModuleEvent(SoftwareModuleEventType.MAXIMIZED, null)); + eventbus.publish(this, new SoftwareModuleEvent(BaseEntityEventType.MAXIMIZED, null)); } @Override public void minimizeTable() { artifactUploadState.setSwModuleTableMaximized(Boolean.FALSE); - eventbus.publish(this, new SoftwareModuleEvent(SoftwareModuleEventType.MINIMIZED, null)); + eventbus.publish(this, new SoftwareModuleEvent(BaseEntityEventType.MINIMIZED, null)); } @Override diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtype/CreateUpdateSoftwareTypeLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtype/CreateUpdateSoftwareTypeLayout.java index dc6d1081e..f2e43c1fb 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtype/CreateUpdateSoftwareTypeLayout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtype/CreateUpdateSoftwareTypeLayout.java @@ -257,6 +257,7 @@ public class CreateUpdateSoftwareTypeLayout extends CustomComponent implements C mainLayout = new HorizontalLayout(); mainLayout.addComponent(fieldButtonLayout); setCompositionRoot(mainLayout); + typeName.focus(); } private void addListeners() { @@ -553,7 +554,7 @@ public class CreateUpdateSoftwareTypeLayout extends CustomComponent implements C .findSoftwareModuleTypeByName(typeName.getValue()); if (createOptiongroup.getValue().equals(createTypeStr)) { if (!checkIsKeyDuplicate(typeKey.getValue()) && !checkIsDuplicate(existingType)) { - crateNewSWModuleType(); + createNewSWModuleType(); } } else { @@ -610,9 +611,9 @@ public class CreateUpdateSoftwareTypeLayout extends CustomComponent implements C /** * Create new tag. */ - private void crateNewSWModuleType() { + private void createNewSWModuleType() { int assignNumber = 0; - final String colorPicked = getColorPickedSting(); + final String colorPicked = getColorPickedString(); final String typeNameValue = HawkbitCommonUtil.trimAndNullIfEmpty(typeName.getValue()); final String typeKeyValue = HawkbitCommonUtil.trimAndNullIfEmpty(typeKey.getValue()); final String typeDescValue = HawkbitCommonUtil.trimAndNullIfEmpty(typeDesc.getValue()); @@ -649,7 +650,7 @@ public class CreateUpdateSoftwareTypeLayout extends CustomComponent implements C * * @return String of color picked value. */ - private String getColorPickedSting() { + private String getColorPickedString() { return "rgb(" + getSelPreview().getColor().getRed() + "," + getSelPreview().getColor().getGreen() + "," + getSelPreview().getColor().getBlue() + ")"; } @@ -675,7 +676,7 @@ public class CreateUpdateSoftwareTypeLayout extends CustomComponent implements C existingType.setDescription(null != typeDescValue ? typeDescValue : null); - existingType.setColour(getColorPickedSting()); + existingType.setColour(getColorPickedString()); swTypeManagementService.updateSoftwareModuleType(existingType); uiNotification.displaySuccess(i18n.get("message.update.success", new Object[] { existingType.getName() })); closeWindow(); diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtype/SMTypeFilterButtons.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtype/SMTypeFilterButtons.java index 9f2aa9602..5a1736b04 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtype/SMTypeFilterButtons.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtype/SMTypeFilterButtons.java @@ -8,21 +8,17 @@ */ package org.eclipse.hawkbit.ui.artifacts.smtype; -import javax.annotation.PreDestroy; - import org.eclipse.hawkbit.ui.artifacts.event.SoftwareModuleTypeEvent; import org.eclipse.hawkbit.ui.artifacts.event.UploadArtifactUIEvent; import org.eclipse.hawkbit.ui.artifacts.event.UploadViewAcceptCriteria; import org.eclipse.hawkbit.ui.artifacts.state.ArtifactUploadState; import org.eclipse.hawkbit.ui.common.SoftwareModuleTypeBeanQuery; -import org.eclipse.hawkbit.ui.common.filterlayout.AbstractFilterButtonClickBehaviour; import org.eclipse.hawkbit.ui.common.filterlayout.AbstractFilterButtons; import org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil; import org.eclipse.hawkbit.ui.utils.SPUIComponetIdProvider; import org.springframework.beans.factory.annotation.Autowired; import org.vaadin.addons.lazyquerycontainer.BeanQueryFactory; import org.vaadin.addons.lazyquerycontainer.LazyQueryContainer; -import org.vaadin.spring.events.EventBus; import org.vaadin.spring.events.EventScope; import org.vaadin.spring.events.annotation.EventBusListenerMethod; @@ -48,26 +44,6 @@ public class SMTypeFilterButtons extends AbstractFilterButtons { @Autowired private UploadViewAcceptCriteria uploadViewAcceptCriteria; - @Autowired - private transient EventBus.SessionEventBus eventBus; - - /** - * Initialize component. - * - * @param filterButtonClickBehaviour - * the clickable behaviour. - */ - @Override - public void init(final AbstractFilterButtonClickBehaviour filterButtonClickBehaviour) { - super.init(filterButtonClickBehaviour); - eventBus.subscribe(this); - } - - @PreDestroy - void destroy() { - eventBus.unsubscribe(this); - } - @EventBusListenerMethod(scope = EventScope.SESSION) void onEvent(final SoftwareModuleTypeEvent event) { if (event.getSoftwareModuleTypeEnum() == SoftwareModuleTypeEvent.SoftwareModuleTypeEnum.ADD_SOFTWARE_MODULE_TYPE @@ -97,9 +73,9 @@ public class SMTypeFilterButtons extends AbstractFilterButtons { } @Override - protected boolean isClickedByDefault(final Long buttonId) { + protected boolean isClickedByDefault(final String typeName) { return artifactUploadState.getSoftwareModuleFilters().getSoftwareModuleType().isPresent() && artifactUploadState - .getSoftwareModuleFilters().getSoftwareModuleType().get().getId().equals(buttonId); + .getSoftwareModuleFilters().getSoftwareModuleType().get().getName().equals(typeName); } @Override diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtype/SMTypeFilterHeader.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtype/SMTypeFilterHeader.java index b79ecb742..a12517b31 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtype/SMTypeFilterHeader.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/smtype/SMTypeFilterHeader.java @@ -10,7 +10,6 @@ package org.eclipse.hawkbit.ui.artifacts.smtype; import javax.annotation.PostConstruct; -import org.eclipse.hawkbit.repository.SpPermissionChecker; import org.eclipse.hawkbit.ui.artifacts.event.UploadArtifactUIEvent; import org.eclipse.hawkbit.ui.artifacts.state.ArtifactUploadState; import org.eclipse.hawkbit.ui.common.filterlayout.AbstractFilterHeader; @@ -18,7 +17,6 @@ import org.eclipse.hawkbit.ui.utils.SPUIComponetIdProvider; import org.eclipse.hawkbit.ui.utils.SPUIDefinitions; import org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions; import org.springframework.beans.factory.annotation.Autowired; -import org.vaadin.spring.events.EventBus; import com.vaadin.spring.annotation.SpringComponent; import com.vaadin.spring.annotation.ViewScope; @@ -35,12 +33,6 @@ public class SMTypeFilterHeader extends AbstractFilterHeader { private static final long serialVersionUID = -4855810338059032342L; - @Autowired - private SpPermissionChecker permChecker; - - @Autowired - private transient EventBus.SessionEventBus eventbus; - @Autowired private ArtifactUploadState artifactUploadState; @@ -84,7 +76,7 @@ public class SMTypeFilterHeader extends AbstractFilterHeader { @Override protected void hideFilterButtonLayout() { artifactUploadState.setSwTypeFilterClosed(true); - eventbus.publish(this, UploadArtifactUIEvent.HIDE_FILTER_BY_TYPE); + eventBus.publish(this, UploadArtifactUIEvent.HIDE_FILTER_BY_TYPE); } @Override diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/state/ArtifactUploadState.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/state/ArtifactUploadState.java index a502b341c..f82ce9ccf 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/state/ArtifactUploadState.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/state/ArtifactUploadState.java @@ -17,6 +17,7 @@ import java.util.Optional; import java.util.Set; import org.eclipse.hawkbit.repository.model.SoftwareModule; +import org.eclipse.hawkbit.ui.common.ManagmentEntityState; import org.springframework.beans.factory.annotation.Autowired; import com.vaadin.spring.annotation.SpringComponent; @@ -29,7 +30,7 @@ import com.vaadin.spring.annotation.VaadinSessionScope; */ @VaadinSessionScope @SpringComponent -public class ArtifactUploadState implements Serializable { +public class ArtifactUploadState implements ManagmentEntityState, Serializable { private static final long serialVersionUID = 8273440375917450859L; @@ -85,30 +86,7 @@ public class ArtifactUploadState implements Serializable { * @return the selectedBaseSwModuleId */ public Optional getSelectedBaseSwModuleId() { - return selectedBaseSwModuleId != null ? Optional.of(selectedBaseSwModuleId) : Optional.empty(); - } - - /** - * @param selectedBaseSwModuleId - * the selectedBaseSwModuleId to set - */ - public void setSelectedBaseSwModuleId(final Long selectedBaseSwModuleId) { - this.selectedBaseSwModuleId = selectedBaseSwModuleId; - } - - /** - * @return the selectedBaseSoftwareModule - */ - public Optional getSelectedBaseSoftwareModule() { - return selectedBaseSoftwareModule == null ? Optional.empty() : Optional.of(selectedBaseSoftwareModule); - } - - /** - * @param selectedBaseSoftwareModule - * the selectedBaseSoftwareModule to set - */ - public void setSelectedBaseSoftwareModule(final SoftwareModule selectedBaseSoftwareModule) { - this.selectedBaseSoftwareModule = selectedBaseSoftwareModule; + return Optional.ofNullable(selectedBaseSwModuleId); } /** @@ -125,12 +103,15 @@ public class ArtifactUploadState implements Serializable { return selectedSoftwareModules; } - /** - * @param selectedSoftwareModules - * the selectedSoftwareModules to set - */ - public void setSelectedSoftwareModules(final Set selectedSoftwareModules) { - this.selectedSoftwareModules = selectedSoftwareModules; + @Override + public void setLastSelectedEntity(final Long value) { + this.selectedBaseSwModuleId = value; + + } + + @Override + public void setSelectedEnitities(final Set values) { + this.selectedSoftwareModules = values; } /** @@ -197,4 +178,11 @@ public class ArtifactUploadState implements Serializable { this.noDataAvilableSoftwareModule = noDataAvilableSoftwareModule; } + public Optional getSelectedBaseSoftwareModule() { + return Optional.ofNullable(selectedBaseSoftwareModule); + } + + public void setSelectedBaseSoftwareModule(final SoftwareModule selectedBaseSoftwareModule) { + this.selectedBaseSoftwareModule = selectedBaseSoftwareModule; + } } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/upload/UploadHandler.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/upload/UploadHandler.java index 8c1feeb33..d5c6759b5 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/upload/UploadHandler.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/artifacts/upload/UploadHandler.java @@ -37,20 +37,12 @@ import com.vaadin.ui.Upload.SucceededListener; * {@link StreamVariable} upload variants. * * The handler manages the output to the user and at the same time ensures that - * the upload does not exceed the configued max file size. - * - * - * - * - * + * the upload does not exceed the configured max file size. * */ public class UploadHandler implements StreamVariable, Receiver, SucceededListener, FailedListener, FinishedListener, ProgressListener, StartedListener { - /** - * - */ private static final long serialVersionUID = 1L; private static final Logger LOG = LoggerFactory.getLogger(UploadHandler.class); @@ -108,7 +100,7 @@ public class UploadHandler implements StreamVariable, Receiver, SucceededListene public OutputStream receiveUpload(final String fileName, final String mimeType) { this.fileName = fileName; this.mimeType = mimeType; - //reset has directory flag before upload + // reset has directory flag before upload view.setHasDirectory(false); try { if (view.checkIfSoftwareModuleIsSelected()) { @@ -343,35 +335,30 @@ public class UploadHandler implements StreamVariable, Receiver, SucceededListene } } - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ @Override public int hashCode() { final int prime = 31; int result = 1; - result = prime * result + (fileName == null ? 0 : fileName.hashCode()); + result = prime * result + ((fileName == null) ? 0 : fileName.hashCode()); return result; } - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ @Override public boolean equals(final Object obj) { if (this == obj) { return true; } - if (!(obj instanceof UploadHandler)) { + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { return false; } final UploadHandler other = (UploadHandler) obj; - if (fileName == null && other.fileName != null) { - return false; + if (fileName == null) { + if (other.fileName != null) { + return false; + } } else if (!fileName.equals(other.fileName)) { return false; } 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..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 @@ -215,13 +215,15 @@ 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) { + return Strings.isNullOrEmpty(file.getType()) && file.getFileSize() % 4096 == 0; } - return false; } private void displayCompositeMessage() { @@ -282,11 +284,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 +346,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 +445,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 +652,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/AbstractAcceptCriteria.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/AbstractAcceptCriteria.java index a6df4f557..2fa2900d5 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/AbstractAcceptCriteria.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/AbstractAcceptCriteria.java @@ -13,8 +13,13 @@ import java.util.List; import java.util.Map; import java.util.Set; +import org.eclipse.hawkbit.ui.management.event.DragEvent; import org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil; import org.eclipse.hawkbit.ui.utils.SPUIDefinitions; +import org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions; +import org.eclipse.hawkbit.ui.utils.UINotification; +import org.springframework.beans.factory.annotation.Autowired; +import org.vaadin.spring.events.EventBus; import com.vaadin.event.dd.DragAndDropEvent; import com.vaadin.event.dd.acceptcriteria.ServerSideCriterion; @@ -27,9 +32,6 @@ import com.vaadin.ui.Table; /** * Abstract class for Accept criteria. * - * - * - * */ public abstract class AbstractAcceptCriteria extends ServerSideCriterion { @@ -37,13 +39,12 @@ public abstract class AbstractAcceptCriteria extends ServerSideCriterion { private int previousRowCount; - /* - * (non-Javadoc) - * - * @see - * com.vaadin.event.dd.acceptcriteria.AcceptCriterion#accept(com.vaadin. - * event.dd.DragAndDropEvent ) - */ + @Autowired + protected transient UINotification uiNotification; + + @Autowired + protected transient EventBus.SessionEventBus eventBus; + @Override public boolean accept(final DragAndDropEvent dragEvent) { final Component compsource = dragEvent.getTransferable().getSourceComponent(); @@ -129,7 +130,7 @@ public abstract class AbstractAcceptCriteria extends ServerSideCriterion { protected void analyseDragComponent(final Component compsource) { final String sourceID = getComponentId(compsource); final Object event = getDropHintConfigurations().get(sourceID); - publishDragStartEvent(event); + eventBus.publish(this, event); } /** @@ -159,23 +160,19 @@ public abstract class AbstractAcceptCriteria extends ServerSideCriterion { */ protected abstract String getComponentId(final Component component); - /** - * publish the given event into eventBus. - * - * @param event - * to be published in eventBus. - */ - protected abstract void publishDragStartEvent(Object event); - /** * Hide the drop hints. Dragging is stopped. */ - protected abstract void hideDropHints(); + protected void hideDropHints() { + eventBus.publish(this, DragEvent.HIDE_DROP_HINT); + } /** * Display invalid drop message. */ - protected abstract void invalidDrop(); + protected void invalidDrop() { + uiNotification.displayValidationError(SPUILabelDefinitions.ACTION_NOT_ALLOWED); + } /** * @return diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/ManagmentEntityState.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/ManagmentEntityState.java new file mode 100644 index 000000000..ecc378ad7 --- /dev/null +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/ManagmentEntityState.java @@ -0,0 +1,35 @@ +/** + * Copyright (c) 2015 Bosch Software Innovations GmbH and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + */ +package org.eclipse.hawkbit.ui.common; + +import java.util.Set; + +/** + * Interface for all entity states UI to show the details to a entity. + */ +public interface ManagmentEntityState { + + /** + * The selected entities for the detail. + * + * @param values + * the selected entities. + * + */ + void setSelectedEnitities(Set values); + + /** + * The last selected value. + * + * @param value + * the value + */ + void setLastSelectedEntity(T value); + +} diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/UserDetailsFormatter.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/UserDetailsFormatter.java new file mode 100644 index 000000000..8fb5a8b42 --- /dev/null +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/UserDetailsFormatter.java @@ -0,0 +1,187 @@ +/** + * 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.common; + +import java.util.Collections; + +import org.apache.commons.lang3.StringUtils; +import org.eclipse.hawkbit.im.authentication.UserPrincipal; +import org.eclipse.hawkbit.repository.model.BaseEntity; +import org.eclipse.hawkbit.ui.utils.SpringContextHelper; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.security.web.context.HttpSessionSecurityContextRepository; + +import com.vaadin.server.VaadinService; + +/** + * A Utility class to user details e.g. username + */ +public final class UserDetailsFormatter { + + private static final String TRIM_APPENDIX = "..."; + private static final String DETAIL_SEPERATOR = ", "; + + private UserDetailsFormatter() { + } + + /** + * Load user details by the user name and format the user name to max 100 + * characters. + * + * @see {@link UserDetailsFormatter#loadAndFormatUsername(String, int)} + * + * @param username + * the user name + * @return the formatted user name (max 100 characters) cannot be + */ + public static String loadAndFormatUsername(final String username) { + return loadAndFormatUsername(username, 100); + } + + /** + * Load user details by {@link BaseEntity#getCreatedBy()} and format the + * user name. Use {@link UserDetailsFormatter#loadAndFormatUsername(String)} + * + * @param baseEntity + * the entity + * @return the formatted 'created at user name' (max 100 characters) cannot + * be + */ + public static String loadAndFormatCreatedBy(final BaseEntity baseEntity) { + if (baseEntity == null || baseEntity.getCreatedBy() == null) { + return StringUtils.EMPTY; + } + + return loadAndFormatUsername(baseEntity.getCreatedBy()); + } + + /** + * Load user details by {@link BaseEntity#getLastModifiedBy()} and format + * the user name. Use + * {@link UserDetailsFormatter#loadAndFormatUsername(String)} + * + * @param baseEntity + * the entity + * @return the formatted 'last modefied by user name' (max 100 characters) + * cannot be + */ + public static String loadAndFormatLastModifiedBy(final BaseEntity baseEntity) { + if (baseEntity == null || baseEntity.getLastModifiedBy() == null) { + return StringUtils.EMPTY; + } + + return loadAndFormatUsername(baseEntity.getLastModifiedBy()); + } + + /** + * Load user details by the current session information and format the user + * name to max 12 characters. @see + * {@link UserDetailsFormatter#loadAndFormatUsername(String, int)} + * + * @return the formatted user name (max 12 characters) cannot be + */ + public static String formatCurrentUsername() { + return loadAndFormatUsername(getCurrentUser().getUsername(), 5); + } + + /** + * Load user details by the user name and format the user name. If the + * loaded {@link UserDetails} is not an instance of a {@link UserPrincipal}, + * then just the {@link UserDetails#getUsername()} will return. + * + * If first and last name available, they will combined. Otherwise the + * {@link UserPrincipal#getLoginname()} will formatted. The formatted name + * is reduced to 100 characters. + * + * @param username + * the user name + * @param expectedNameLength + * the name size of each name part + * @return the formatted user name (max expectedNameLength characters) + * cannot be + */ + public static String loadAndFormatUsername(final String username, final int expectedNameLength) { + final UserDetails userDetails = loadUserByUsername(username); + return formatUserName(expectedNameLength, userDetails); + } + + private static String formatUserName(final int expectedNameLength, final UserDetails userDetails) { + if (!(userDetails instanceof UserPrincipal)) { + return userDetails.getUsername(); + } + + final UserPrincipal userPrincipal = (UserPrincipal) userDetails; + + String firstname = StringUtils.defaultIfEmpty(userPrincipal.getFirstname(), StringUtils.EMPTY); + + if (!StringUtils.isEmpty(firstname)) { + firstname += DETAIL_SEPERATOR; + } + + final String firstAndLastname = firstname + + StringUtils.defaultIfEmpty(userPrincipal.getLastname(), StringUtils.EMPTY); + + final String trimmedUsername = trimAndFormatDetail(firstAndLastname, expectedNameLength); + + if (StringUtils.isEmpty(trimmedUsername)) { + return trimAndFormatDetail(userPrincipal.getLoginname(), expectedNameLength); + } + return trimmedUsername; + } + + /** + * Format the current tenant. The information is loaded by the current + * session information. + * + * @return the formatted user name (max 8 characters) can be + */ + public static String formatCurrentTenant() { + final UserDetails userDetails = getCurrentUser(); + if (!(userDetails instanceof UserPrincipal)) { + return null; + } + + final UserPrincipal userPrincipal = (UserPrincipal) userDetails; + return trimAndFormatDetail(userPrincipal.getTenant(), 8); + } + + private static UserDetails getCurrentUser() { + final SecurityContext context = (SecurityContext) VaadinService.getCurrentRequest().getWrappedSession() + .getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY); + return (UserDetails) context.getAuthentication().getPrincipal(); + } + + private static String trimAndFormatDetail(final String formatString, final int expectedDetailLength) { + final String detail = StringUtils.defaultIfEmpty(formatString, StringUtils.EMPTY); + final String trimmedDetail = StringUtils.substring(detail, 0, expectedDetailLength); + if (StringUtils.length(detail) > expectedDetailLength) { + return trimmedDetail + TRIM_APPENDIX; + } + return trimmedDetail; + } + + // Exception squid:S1166 - exception has to be hidden + @SuppressWarnings({ "squid:S1166" }) + private static UserDetails loadUserByUsername(final String username) { + final UserDetailsService userDetailsService = SpringContextHelper.getBean(UserDetailsService.class); + try { + final UserDetails loadUserByUsername = userDetailsService.loadUserByUsername(username); + if (loadUserByUsername == null) { + throw new UsernameNotFoundException("User not found " + username); + } + return loadUserByUsername; + } catch (final UsernameNotFoundException e) { + return new User(username, "", Collections.emptyList()); + } + } +} diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/confirmwindow/layout/AbstractConfirmationWindowLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/confirmwindow/layout/AbstractConfirmationWindowLayout.java index 8a89ee821..f4fe21425 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/confirmwindow/layout/AbstractConfirmationWindowLayout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/confirmwindow/layout/AbstractConfirmationWindowLayout.java @@ -11,21 +11,29 @@ package org.eclipse.hawkbit.ui.common.confirmwindow.layout; import java.util.Map; import java.util.Map.Entry; -import org.eclipse.hawkbit.ui.components.SPUIComponentProvider; -import org.eclipse.hawkbit.ui.utils.SPUIComponetIdProvider; -import org.eclipse.hawkbit.ui.utils.SPUIStyleDefinitions; +import javax.annotation.PostConstruct; +import org.eclipse.hawkbit.ui.components.SPUIComponentProvider; +import org.eclipse.hawkbit.ui.decorators.SPUIButtonStyleSmallNoBorder; +import org.eclipse.hawkbit.ui.utils.I18N; +import org.eclipse.hawkbit.ui.utils.SPUIComponetIdProvider; +import org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions; +import org.eclipse.hawkbit.ui.utils.SPUIStyleDefinitions; +import org.springframework.beans.factory.annotation.Autowired; +import org.vaadin.spring.events.EventBus; + +import com.vaadin.server.FontAwesome; import com.vaadin.ui.Accordion; import com.vaadin.ui.Alignment; +import com.vaadin.ui.Button; +import com.vaadin.ui.Button.ClickListener; import com.vaadin.ui.Label; import com.vaadin.ui.VerticalLayout; +import com.vaadin.ui.themes.ValoTheme; /** * Abstract layout of confirm actions window. * - * - * - * */ public abstract class AbstractConfirmationWindowLayout extends VerticalLayout { @@ -37,33 +45,25 @@ public abstract class AbstractConfirmationWindowLayout extends VerticalLayout { private String consolidatedMessage; - protected void inittialize() { - // Remove all components + @Autowired + protected I18N i18n; + + @Autowired + protected transient EventBus.SessionEventBus eventBus; + + @PostConstruct + public void initialize() { removeAllComponents(); consolidatedMessage = ""; - - // create components again createComponents(); - - // Build layout. buildLayout(); } - /** - * Create accordion and add respective tabs. - */ private void createComponents() { - // create accordion createAccordian(); - - // create action message label createActionMessgaeLabel(); } - /** - * Create a message label to show the results of any actions which user does - * in the confirmation window. - */ private void createActionMessgaeLabel() { actionMessage = SPUIComponentProvider.getLabel("", null); actionMessage.addStyleName(SPUIStyleDefinitions.CONFIRM_WINDOW_INFO_BOX); @@ -138,4 +138,14 @@ public abstract class AbstractConfirmationWindowLayout extends VerticalLayout { public String getConsolidatedMessage() { return consolidatedMessage; } + + protected Button createDiscardButton(final Object itemId, final ClickListener clickListener) { + final Button deletesDsIcon = SPUIComponentProvider.getButton("", "", SPUILabelDefinitions.DISCARD, + ValoTheme.BUTTON_TINY + " " + SPUIStyleDefinitions.REDICON, true, FontAwesome.REPLY, + SPUIButtonStyleSmallNoBorder.class); + deletesDsIcon.setData(itemId); + deletesDsIcon.setImmediate(true); + deletesDsIcon.addClickListener(clickListener); + return deletesDsIcon; + } } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/detailslayout/AbstractNamedVersionedEntityTableDetailsLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/detailslayout/AbstractNamedVersionedEntityTableDetailsLayout.java new file mode 100644 index 000000000..3ccbb8ad7 --- /dev/null +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/detailslayout/AbstractNamedVersionedEntityTableDetailsLayout.java @@ -0,0 +1,28 @@ +/** + * 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.common.detailslayout; + +import org.eclipse.hawkbit.repository.model.NamedVersionedEntity; +import org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil; + +/** + * + * + */ +public abstract class AbstractNamedVersionedEntityTableDetailsLayout + extends AbstractTableDetailsLayout { + + private static final long serialVersionUID = 1L; + + @Override + protected String getName() { + return HawkbitCommonUtil.getFormattedNameVersion(getSelectedBaseEntity().getName(), + getSelectedBaseEntity().getVersion()); + } +} diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/detailslayout/AbstractTableDetailsLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/detailslayout/AbstractTableDetailsLayout.java index a6ab09659..33fcf5af9 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/detailslayout/AbstractTableDetailsLayout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/detailslayout/AbstractTableDetailsLayout.java @@ -10,7 +10,15 @@ package org.eclipse.hawkbit.ui.common.detailslayout; import java.util.Map; +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; + +import org.apache.commons.lang3.StringUtils; +import org.eclipse.hawkbit.repository.SpPermissionChecker; +import org.eclipse.hawkbit.repository.model.NamedEntity; import org.eclipse.hawkbit.repository.model.Target; +import org.eclipse.hawkbit.ui.common.table.BaseEntityEvent; +import org.eclipse.hawkbit.ui.common.table.BaseEntityEventType; import org.eclipse.hawkbit.ui.components.SPUIComponentProvider; import org.eclipse.hawkbit.ui.decorators.SPUIButtonStyleSmallNoBorder; import org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil; @@ -19,6 +27,8 @@ import org.eclipse.hawkbit.ui.utils.SPDateTimeUtil; import org.eclipse.hawkbit.ui.utils.SPUIComponetIdProvider; import org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions; import org.eclipse.hawkbit.ui.utils.SPUIStyleDefinitions; +import org.springframework.beans.factory.annotation.Autowired; +import org.vaadin.spring.events.EventBus; import com.vaadin.server.FontAwesome; import com.vaadin.shared.ui.label.ContentMode; @@ -27,16 +37,28 @@ import com.vaadin.ui.Button; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.Label; import com.vaadin.ui.TabSheet; +import com.vaadin.ui.UI; import com.vaadin.ui.VerticalLayout; /** - * + * Abstract Layout to show the entity details. * */ -public abstract class AbstractTableDetailsLayout extends VerticalLayout { +public abstract class AbstractTableDetailsLayout extends VerticalLayout { private static final long serialVersionUID = 4862529368471627190L; + @Autowired + private I18N i18n; + + @Autowired + private transient EventBus.SessionEventBus eventBus; + + @Autowired + private SpPermissionChecker permissionChecker; + + private T selectedBaseEntity; + private Label caption; private Button editButton; @@ -54,20 +76,57 @@ public abstract class AbstractTableDetailsLayout extends VerticalLayout { /** * Initialize components. */ + @PostConstruct protected void init() { createComponents(); buildLayout(); - /** - * On load of UI/Refresh details will be loaded based on the row - * selected in table. - */ restoreState(); + eventBus.subscribe(this); + } + + @PreDestroy + void destroy() { + eventBus.unsubscribe(this); + } + + protected SpPermissionChecker getPermissionChecker() { + return permissionChecker; + } + + protected EventBus.SessionEventBus getEventBus() { + return eventBus; + } + + protected I18N getI18n() { + return i18n; + } + + protected T getSelectedBaseEntity() { + return selectedBaseEntity; + } + + public void setSelectedBaseEntity(final T selectedBaseEntity) { + this.selectedBaseEntity = selectedBaseEntity; + } + + /** + * Default implementation to handle an entity event. + * + * @param baseEntityEvent + * the event + */ + protected void onBaseEntityEvent(final BaseEntityEvent baseEntityEvent) { + final BaseEntityEventType eventType = baseEntityEvent.getEventType(); + if (BaseEntityEventType.SELECTED_ENTITY == eventType || BaseEntityEventType.UPDATED_ENTITY == eventType) { + UI.getCurrent().access(() -> populateData(baseEntityEvent.getEntity())); + } else if (BaseEntityEventType.MINIMIZED == eventType) { + UI.getCurrent().access(() -> setVisible(true)); + } else if (BaseEntityEventType.MAXIMIZED == eventType) { + UI.getCurrent().access(() -> setVisible(false)); + } } private void createComponents() { - /** - * Default caption is set.Reset on selecting table row. - */ caption = createHeaderCaption(); caption.setImmediate(true); caption.setContentMode(ContentMode.HTML); @@ -76,7 +135,7 @@ public abstract class AbstractTableDetailsLayout extends VerticalLayout { editButton = SPUIComponentProvider.getButton("", "", "", null, false, FontAwesome.PENCIL_SQUARE_O, SPUIButtonStyleSmallNoBorder.class); editButton.setId(getEditButtonId()); - editButton.addClickListener(event -> onEdit(event)); + editButton.addClickListener(this::onEdit); editButton.setEnabled(false); @@ -90,22 +149,21 @@ public abstract class AbstractTableDetailsLayout extends VerticalLayout { } private void buildLayout() { - final HorizontalLayout nameEditLayout = new HorizontalLayout(); - nameEditLayout.setWidth(100.0f, Unit.PERCENTAGE); + nameEditLayout.setWidth(100.0F, Unit.PERCENTAGE); nameEditLayout.addComponent(caption); - nameEditLayout.setComponentAlignment(caption, Alignment.MIDDLE_LEFT); + nameEditLayout.setComponentAlignment(caption, Alignment.TOP_LEFT); if (hasEditPermission()) { nameEditLayout.addComponent(editButton); - nameEditLayout.setComponentAlignment(editButton, Alignment.MIDDLE_RIGHT); + nameEditLayout.setComponentAlignment(editButton, Alignment.TOP_RIGHT); } - nameEditLayout.setExpandRatio(caption, 1.0f); + nameEditLayout.setExpandRatio(caption, 1.0F); nameEditLayout.addStyleName(SPUIStyleDefinitions.WIDGET_TITLE); addComponent(nameEditLayout); - setComponentAlignment(nameEditLayout, Alignment.MIDDLE_CENTER); + setComponentAlignment(nameEditLayout, Alignment.TOP_CENTER); addComponent(detailsTab); - setComponentAlignment(nameEditLayout, Alignment.MIDDLE_CENTER); + setComponentAlignment(nameEditLayout, Alignment.TOP_CENTER); setSizeFull(); setHeightUndefined(); @@ -113,9 +171,7 @@ public abstract class AbstractTableDetailsLayout extends VerticalLayout { } private Label createHeaderCaption() { - final Label captionLabel = SPUIComponentProvider.getLabel(getDefaultCaption(), - SPUILabelDefinitions.SP_WIDGET_CAPTION); - return captionLabel; + return SPUIComponentProvider.getLabel(getDefaultCaption(), SPUILabelDefinitions.SP_WIDGET_CAPTION); } protected VerticalLayout getTabLayout() { @@ -130,62 +186,47 @@ public abstract class AbstractTableDetailsLayout extends VerticalLayout { private void restoreState() { if (onLoadIsTableRowSelected()) { - populateData(true); + populateData(null); + editButton.setEnabled(true); } if (onLoadIsTableMaximized()) { - /** - * If table is maximized hide details layout. - */ - hideLayout(); + setVisible(false); } } - protected void showLayout() { - setVisible(true); - } - - protected void hideLayout() { - setVisible(false); - } - /** * If no data in table (i,e no row selected),then disable the edit button. * If row is selected ,enable edit button. */ - protected void populateData(final Boolean isRowSelected) { - if (isRowSelected) { - populateDetailsWidget(); - enableEditButton(); + private void populateData(final T selectedBaseEntity) { + this.selectedBaseEntity = selectedBaseEntity; + editButton.setEnabled(selectedBaseEntity != null); + if (selectedBaseEntity == null) { + setName(getDefaultCaption(), StringUtils.EMPTY); } else { - disableEditButton(); - clearDetails(); + setName(getDefaultCaption(), getName()); } + populateLog(); + populateDescription(); + populateDetailsWidget(); } - protected void enableEditButton() { - editButton.setEnabled(true); - } + protected void populateLog() { + logLayout.removeAllComponents(); - protected void disableEditButton() { - editButton.setEnabled(false); - } + logLayout.addComponent(SPUIComponentProvider.createNameValueLabel(i18n.get("label.created.at"), + SPDateTimeUtil.formatCreatedAt(selectedBaseEntity))); - protected void updateLogLayout(final VerticalLayout changeLogLayout, final Long lastModifiedAt, - final String lastModifiedBy, final Long createdAt, final String createdBy, final I18N i18n) { - changeLogLayout.removeAllComponents(); - changeLogLayout.addComponent(SPUIComponentProvider.createNameValueLabel(i18n.get("label.created.at"), - createdAt == null ? "" : SPDateTimeUtil.getFormattedDate(createdAt))); + logLayout.addComponent(SPUIComponentProvider.createCreatedByLabel(i18n, selectedBaseEntity)); - changeLogLayout.addComponent(SPUIComponentProvider.createNameValueLabel(i18n.get("label.created.by"), - createdBy == null ? "" : HawkbitCommonUtil.getIMUser(createdBy))); - - if (null != lastModifiedAt) { - changeLogLayout.addComponent(SPUIComponentProvider.createNameValueLabel(i18n.get("label.modified.date"), - SPDateTimeUtil.getFormattedDate(lastModifiedAt))); - - changeLogLayout.addComponent(SPUIComponentProvider.createNameValueLabel(i18n.get("label.modified.by"), - lastModifiedBy == null ? "" : HawkbitCommonUtil.getIMUser(lastModifiedBy))); + if (selectedBaseEntity == null || selectedBaseEntity.getLastModifiedAt() == null) { + return; } + + logLayout.addComponent(SPUIComponentProvider.createNameValueLabel(i18n.get("label.modified.date"), + SPDateTimeUtil.formatLastModifiedAt(selectedBaseEntity))); + + logLayout.addComponent(SPUIComponentProvider.createLastModifiedByLabel(i18n, selectedBaseEntity)); } protected void updateDescriptionLayout(final String descriptionLabel, final String description) { @@ -271,23 +312,28 @@ public abstract class AbstractTableDetailsLayout extends VerticalLayout { protected abstract String getTabSheetId(); - /** - * Populate details layout. - */ - protected abstract void populateDetailsWidget(); - - protected abstract void clearDetails(); - protected abstract Boolean hasEditPermission(); public VerticalLayout getDetailsLayout() { return detailsLayout; } - public VerticalLayout getLogLayout() { - return logLayout; + private void populateDescription() { + if (selectedBaseEntity != null) { + updateDescriptionLayout(i18n.get("label.description"), selectedBaseEntity.getDescription()); + } else { + updateDescriptionLayout(i18n.get("label.description"), null); + } + } + + protected abstract void populateDetailsWidget(); + + protected Long getSelectedBaseEntityId() { + return selectedBaseEntity == null ? null : selectedBaseEntity.getId(); } protected abstract String getDetailsHeaderCaptionId(); + protected abstract String getName(); + } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/detailslayout/SoftwareModuleDetailsTable.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/detailslayout/SoftwareModuleDetailsTable.java index 8def18034..c0ecf9869 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/detailslayout/SoftwareModuleDetailsTable.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/detailslayout/SoftwareModuleDetailsTable.java @@ -16,12 +16,12 @@ import org.eclipse.hawkbit.repository.exception.EntityLockedException; import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.repository.model.SoftwareModuleType; +import org.eclipse.hawkbit.ui.common.table.BaseEntityEventType; import org.eclipse.hawkbit.ui.components.SPUIComponentProvider; import org.eclipse.hawkbit.ui.decorators.SPUIButtonStyleSmallNoBorder; import org.eclipse.hawkbit.ui.distributions.event.DistributionsUIEvent; import org.eclipse.hawkbit.ui.distributions.state.ManageDistUIState; import org.eclipse.hawkbit.ui.management.event.DistributionTableEvent; -import org.eclipse.hawkbit.ui.management.event.DistributionTableEvent.DistributionComponentEvent; import org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil; import org.eclipse.hawkbit.ui.utils.I18N; import org.eclipse.hawkbit.ui.utils.SPUIStyleDefinitions; @@ -161,7 +161,6 @@ public class SoftwareModuleDetailsTable extends Table { if (null != distributionSet) { if (isUnassignSoftModAllowed && permissionChecker.hasUpdateDistributionPermission()) { try { - distributionSetManagement.checkDistributionSetAlreadyUse(distributionSet); isTargetAssigned = false; } catch (final EntityLockedException exception) { isTargetAssigned = true; @@ -215,9 +214,8 @@ public class SoftwareModuleDetailsTable extends Table { .getItem(event.getButton().getId()).getItemProperty(SOFT_MODULE).getValue(), alreadyAssignedSwModules); final DistributionSet newDistributionSet = distributionSetManagement.unassignSoftwareModule(distributionSet, unAssignedSw); - manageDistUIState.setLastSelectedDistribution(newDistributionSet.getDistributionSetIdName()); - eventBus.publish(this, - new DistributionTableEvent(DistributionComponentEvent.ON_VALUE_CHANGE, newDistributionSet)); + manageDistUIState.setLastSelectedEntity(newDistributionSet.getDistributionSetIdName()); + eventBus.publish(this, new DistributionTableEvent(BaseEntityEventType.SELECTED_ENTITY, newDistributionSet)); eventBus.publish(this, DistributionsUIEvent.ORDER_BY_DISTRIBUTION); uiNotification.displaySuccess(i18n.get("message.sw.unassigned", unAssignedSw.getName())); } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/filterlayout/AbstractFilterButtons.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/filterlayout/AbstractFilterButtons.java index 6ed10166f..b64578782 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/filterlayout/AbstractFilterButtons.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/filterlayout/AbstractFilterButtons.java @@ -11,13 +11,17 @@ package org.eclipse.hawkbit.ui.common.filterlayout; import java.util.ArrayList; import java.util.List; +import javax.annotation.PreDestroy; + import org.eclipse.hawkbit.ui.components.SPUIComponentProvider; import org.eclipse.hawkbit.ui.decorators.SPUITagButtonStyle; import org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil; import org.eclipse.hawkbit.ui.utils.SPUIDefinitions; import org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions; import org.eclipse.hawkbit.ui.utils.SPUIStyleDefinitions; +import org.springframework.beans.factory.annotation.Autowired; import org.vaadin.addons.lazyquerycontainer.LazyQueryContainer; +import org.vaadin.spring.events.EventBus; import com.vaadin.data.Item; import com.vaadin.event.dd.DropHandler; @@ -38,10 +42,13 @@ import com.vaadin.ui.themes.ValoTheme; public abstract class AbstractFilterButtons extends Table { private static final long serialVersionUID = 7783305719009746375L; - + private static final String DEFAULT_GREEN = "rgb(44,151,32)"; protected static final String FILTER_BUTTON_COLUMN = "filterButton"; + + @Autowired + protected transient EventBus.SessionEventBus eventBus; private AbstractFilterButtonClickBehaviour filterButtonClickBehaviour; @@ -54,6 +61,12 @@ public abstract class AbstractFilterButtons extends Table { public void init(final AbstractFilterButtonClickBehaviour filterButtonClickBehaviour) { this.filterButtonClickBehaviour = filterButtonClickBehaviour; createTable(); + eventBus.subscribe(this); + } + + @PreDestroy + void destroy() { + eventBus.unsubscribe(this); } private void createTable() { @@ -88,12 +101,7 @@ public abstract class AbstractFilterButtons extends Table { @SuppressWarnings("serial") protected void addColumn() { - addGeneratedColumn(FILTER_BUTTON_COLUMN, new ColumnGenerator() { - @Override - public Object generateCell(final Table source, final Object itemId, final Object columnId) { - return addGeneratedCell(itemId); - } - }); + addGeneratedColumn(FILTER_BUTTON_COLUMN, (source, itemId, columnId) -> addGeneratedCell(itemId)); } /** @@ -114,7 +122,7 @@ public abstract class AbstractFilterButtons extends Table { typeButton.addClickListener(event -> filterButtonClickBehaviour.processFilterButtonClick(event)); if (typeButton.getData().equals(SPUIDefinitions.NO_TAG_BUTTON_ID) && isNoTagSateSelected()) { filterButtonClickBehaviour.setDefaultClickedButton(typeButton); - } else if (id != null && isClickedByDefault(id)) { + } else if (id != null && isClickedByDefault(name)) { filterButtonClickBehaviour.setDefaultClickedButton(typeButton); } final DragAndDropWrapper wrapper = createDragAndDropWrapper(typeButton, name, id); @@ -205,10 +213,11 @@ public abstract class AbstractFilterButtons extends Table { /** * Check if button should be displayed as clicked by default. * - * @param id - * @return + * @param buttonCaption + * button caption + * @return true if button is clicked */ - protected abstract boolean isClickedByDefault(final Long buttonId); + protected abstract boolean isClickedByDefault(final String buttonCaption); /** * Get filter button Id. diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/filterlayout/AbstractFilterHeader.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/filterlayout/AbstractFilterHeader.java index 95ac7bb35..ddc2d9889 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/filterlayout/AbstractFilterHeader.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/filterlayout/AbstractFilterHeader.java @@ -8,10 +8,13 @@ */ package org.eclipse.hawkbit.ui.common.filterlayout; +import org.eclipse.hawkbit.repository.SpPermissionChecker; import org.eclipse.hawkbit.ui.components.SPUIComponentProvider; import org.eclipse.hawkbit.ui.decorators.SPUIButtonStyleSmallNoBorder; import org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions; import org.eclipse.hawkbit.ui.utils.SPUIStyleDefinitions; +import org.springframework.beans.factory.annotation.Autowired; +import org.vaadin.spring.events.EventBus; import com.vaadin.server.FontAwesome; import com.vaadin.ui.Alignment; @@ -31,6 +34,13 @@ public abstract class AbstractFilterHeader extends VerticalLayout { private static final long serialVersionUID = -1388340600522323332L; + + @Autowired + protected SpPermissionChecker permChecker; + + @Autowired + protected transient EventBus.SessionEventBus eventBus; + private Label title; private Button config; diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/footer/AbstractDeleteActionsLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/footer/AbstractDeleteActionsLayout.java index 5b9bd162c..75bd43447 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/footer/AbstractDeleteActionsLayout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/footer/AbstractDeleteActionsLayout.java @@ -8,12 +8,20 @@ */ package org.eclipse.hawkbit.ui.common.footer; +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; + +import org.eclipse.hawkbit.repository.SpPermissionChecker; import org.eclipse.hawkbit.ui.components.SPUIComponentProvider; import org.eclipse.hawkbit.ui.decorators.SPUIButtonStyleSmall; import org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil; +import org.eclipse.hawkbit.ui.utils.I18N; import org.eclipse.hawkbit.ui.utils.SPUIComponetIdProvider; import org.eclipse.hawkbit.ui.utils.SPUIDefinitions; import org.eclipse.hawkbit.ui.utils.SPUIStyleDefinitions; +import org.eclipse.hawkbit.ui.utils.UINotification; +import org.springframework.beans.factory.annotation.Autowired; +import org.vaadin.spring.events.EventBus; import com.vaadin.event.dd.DragAndDropEvent; import com.vaadin.event.dd.DropHandler; @@ -34,14 +42,23 @@ import com.vaadin.ui.themes.ValoTheme; /** * Parent class for footer layout. * - * - * - * */ public abstract class AbstractDeleteActionsLayout extends VerticalLayout implements DropHandler { private static final long serialVersionUID = -6047975388519155509L; + @Autowired + protected I18N i18n; + + @Autowired + protected SpPermissionChecker permChecker; + + @Autowired + protected transient EventBus.SessionEventBus eventBus; + + @Autowired + protected transient UINotification notification; + private DragAndDropWrapper deleteWrapper; private Button noActionBtn; @@ -53,12 +70,19 @@ public abstract class AbstractDeleteActionsLayout extends VerticalLayout impleme /** * Initialize. */ + @PostConstruct protected void init() { if (hasCountMessage() || hasDeletePermission() || hasUpdatePermission() || hasBulkUploadPermission()) { createComponents(); buildLayout(); reload(); } + eventBus.subscribe(this); + } + + @PreDestroy + void destroy() { + eventBus.unsubscribe(this); } private void reload() { @@ -158,40 +182,45 @@ public abstract class AbstractDeleteActionsLayout extends VerticalLayout impleme } protected void setUploadStatusButtonCaption(final Long count) { - if (null != bulkUploadStatusButton) { - bulkUploadStatusButton.setCaption("
    " + count + "
    "); + if (bulkUploadStatusButton == null) { + return; } + bulkUploadStatusButton.setCaption("
    " + count + "
    "); } protected void enableBulkUploadStatusButton() { - if (null != bulkUploadStatusButton) { - bulkUploadStatusButton.setVisible(true); + if (bulkUploadStatusButton == null) { + return; } + bulkUploadStatusButton.setVisible(true); } protected void updateUploadBtnIconToComplete() { - if (null != bulkUploadStatusButton) { - bulkUploadStatusButton.removeStyleName(SPUIStyleDefinitions.BULK_UPLOAD_PROGRESS_INDICATOR_STYLE); - bulkUploadStatusButton.setIcon(FontAwesome.UPLOAD); + if (bulkUploadStatusButton == null) { + return; } + bulkUploadStatusButton.removeStyleName(SPUIStyleDefinitions.BULK_UPLOAD_PROGRESS_INDICATOR_STYLE); + bulkUploadStatusButton.setIcon(FontAwesome.UPLOAD); } protected void updateUploadBtnIconToProgressIndicator() { - if (null != bulkUploadStatusButton) { - bulkUploadStatusButton.addStyleName(SPUIStyleDefinitions.BULK_UPLOAD_PROGRESS_INDICATOR_STYLE); - bulkUploadStatusButton.setIcon(null); + if (bulkUploadStatusButton == null) { + return; } + bulkUploadStatusButton.addStyleName(SPUIStyleDefinitions.BULK_UPLOAD_PROGRESS_INDICATOR_STYLE); + bulkUploadStatusButton.setIcon(null); } protected void actionButtonClicked() { - if (hasUnsavedActions()) { - unsavedActionsWindow = SPUIComponentProvider.getWindow(getUnsavedActionsWindowCaption(), - SPUIComponetIdProvider.SAVE_ACTIONS_POPUP, SPUIDefinitions.CONFIRMATION_WINDOW); - unsavedActionsWindow.addCloseListener(event -> unsavedActionsWindowClosed()); - unsavedActionsWindow.setContent(getUnsavedActionsWindowContent()); - unsavedActionsWindow.setId(SPUIComponetIdProvider.CONFIRMATION_POPUP_ID); - UI.getCurrent().addWindow(unsavedActionsWindow); + if (!hasUnsavedActions()) { + return; } + unsavedActionsWindow = SPUIComponentProvider.getWindow(getUnsavedActionsWindowCaption(), + SPUIComponetIdProvider.SAVE_ACTIONS_POPUP, SPUIDefinitions.CONFIRMATION_WINDOW); + unsavedActionsWindow.addCloseListener(event -> unsavedActionsWindowClosed()); + unsavedActionsWindow.setContent(getUnsavedActionsWindowContent()); + unsavedActionsWindow.setId(SPUIComponetIdProvider.CONFIRMATION_POPUP_ID); + UI.getCurrent().addWindow(unsavedActionsWindow); } /** @@ -201,22 +230,11 @@ public abstract class AbstractDeleteActionsLayout extends VerticalLayout impleme UI.getCurrent().removeWindow(unsavedActionsWindow); } - /* - * (non-Javadoc) - * - * @see com.vaadin.event.dd.DropHandler#getAcceptCriterion() - */ @Override public AcceptCriterion getAcceptCriterion() { return getDeleteLayoutAcceptCriteria(); } - /* - * (non-Javadoc) - * - * @see com.vaadin.event.dd.DropHandler#drop(com.vaadin.event.dd. - * DragAndDropEvent) - */ @Override public void drop(final DragAndDropEvent event) { processDroppedComponent(event); @@ -263,6 +281,42 @@ public abstract class AbstractDeleteActionsLayout extends VerticalLayout impleme } } + /** + * + * @return true if the count label is displayed false is not displayed + */ + protected boolean hasCountMessage() { + return false; + } + + /** + * + * @return the count message label + */ + protected Label getCountMessageLabel() { + return null; + } + + /** + * @return true if bulk upload is allowed and has required create + * permissions. + */ + protected boolean hasBulkUploadPermission() { + // can be overriden + return false; + } + + protected void showBulkUploadWindow() { + // can be overriden + } + + /** + * restore the upload status count. + */ + protected void restoreBulkUploadStatusCount() { + // can be overriden + } + /** * Check user has delete permission. * @@ -311,31 +365,32 @@ public abstract class AbstractDeleteActionsLayout extends VerticalLayout impleme * * @return the no actions label. */ - protected abstract String getNoActionsButtonLabel(); + protected String getNoActionsButtonLabel() { + return i18n.get("button.no.actions"); + } /** * Get the pending actions button label. * * @return the actions label. */ - protected abstract String getActionsButtonLabel(); - - /** - * reload the count value. - */ - protected abstract void restoreActionCount(); - - /** - * restore the upload status count. - */ - protected abstract void restoreBulkUploadStatusCount(); + protected String getActionsButtonLabel() { + return i18n.get("button.actions"); + } /** * Get caption of unsaved actions window. * * @return caption of the window. */ - protected abstract String getUnsavedActionsWindowCaption(); + protected String getUnsavedActionsWindowCaption() { + return i18n.get("caption.save.window"); + } + + /** + * reload the count value. + */ + protected abstract void restoreActionCount(); /** * This method will be called when unsaved actions window is closed. @@ -357,21 +412,4 @@ public abstract class AbstractDeleteActionsLayout extends VerticalLayout impleme */ protected abstract boolean hasUnsavedActions(); - /** - * Only in deployment view count message is displayed. - * - * @return - */ - protected abstract boolean hasCountMessage(); - - protected abstract Label getCountMessageLabel(); - - /** - * @return true if bulk upload is allowed and has required create - * permissions. - */ - protected abstract boolean hasBulkUploadPermission(); - - protected abstract void showBulkUploadWindow(); - } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/grid/AbstractGrid.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/grid/AbstractGrid.java index 7cd276258..be16498e9 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/grid/AbstractGrid.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/grid/AbstractGrid.java @@ -8,14 +8,17 @@ */ package org.eclipse.hawkbit.ui.common.grid; +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; + +import org.eclipse.hawkbit.ui.utils.I18N; import org.eclipse.hawkbit.ui.utils.SPUIDefinitions; +import org.springframework.beans.factory.annotation.Autowired; +import org.vaadin.spring.events.EventBus; import com.vaadin.data.Container; import com.vaadin.data.Container.Indexed; -import com.vaadin.shared.ui.grid.HeightMode; import com.vaadin.ui.Grid; -import com.vaadin.ui.Label; -import com.vaadin.ui.themes.ValoTheme; /** * Abstract table class. @@ -24,10 +27,18 @@ import com.vaadin.ui.themes.ValoTheme; public abstract class AbstractGrid extends Grid { private static final long serialVersionUID = 4856562746502217630L; + + @Autowired + protected I18N i18n; + + @Autowired + protected transient EventBus.SessionEventBus eventBus; + /** * Initialize the components. */ + @PostConstruct protected void init() { setSizeFull(); setImmediate(true); @@ -35,6 +46,12 @@ public abstract class AbstractGrid extends Grid { setSelectionMode(SelectionMode.NONE); setColumnReorderingAllowed(true); addNewContainerDS(); + eventBus.subscribe(this); + } + + @PreDestroy + void destroy() { + eventBus.unsubscribe(this); } public void addNewContainerDS() { @@ -46,13 +63,13 @@ public abstract class AbstractGrid extends Grid { setColumnHeaderNames(); addColumnRenderes(); - CellDescriptionGenerator cellDescriptionGenerator = getDescriptionGenerator(); + final CellDescriptionGenerator cellDescriptionGenerator = getDescriptionGenerator(); if (getDescriptionGenerator() != null) { setCellDescriptionGenerator(cellDescriptionGenerator); } // Allow column hiding - for (Column c : getColumns()) { + for (final Column c : getColumns()) { c.setHidable(true); } setHiddenColumns(); diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/table/AbstractNamedVersionTable.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/table/AbstractNamedVersionTable.java new file mode 100644 index 000000000..3e215f77c --- /dev/null +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/table/AbstractNamedVersionTable.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.ui.common.table; + +import java.util.List; + +import org.eclipse.hawkbit.repository.model.NamedVersionedEntity; +import org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions; +import org.eclipse.hawkbit.ui.utils.TableColumn; + +import com.vaadin.data.Item; + +/** + * Abstract table to handling {@link NamedVersionedEntity} + * + * @param + * e is the entity class + * @param + * i is the id of the table + */ +public abstract class AbstractNamedVersionTable extends AbstractTable { + + private static final long serialVersionUID = 780050712209750719L; + + @Override + protected List getTableVisibleColumns() { + final List columnList = super.getTableVisibleColumns(); + final float versionColumnSize = isMaximized() ? 0.1F : 0.2F; + columnList + .add(new TableColumn(SPUILabelDefinitions.VAR_VERSION, i18n.get("header.version"), versionColumnSize)); + return columnList; + } + + @SuppressWarnings("unchecked") + @Override + protected void updateEntity(final E baseEntity, final Item item) { + super.updateEntity(baseEntity, item); + item.getItemProperty(SPUILabelDefinitions.VAR_VERSION).setValue(baseEntity.getVersion()); + } + +} diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/table/AbstractTable.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/table/AbstractTable.java index ae6811ddb..1808cf070 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/table/AbstractTable.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/table/AbstractTable.java @@ -9,34 +9,65 @@ package org.eclipse.hawkbit.ui.common.table; import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; import java.util.List; +import java.util.Set; +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; + +import org.eclipse.hawkbit.repository.model.NamedEntity; +import org.eclipse.hawkbit.ui.artifacts.event.UploadArtifactUIEvent; +import org.eclipse.hawkbit.ui.common.ManagmentEntityState; +import org.eclipse.hawkbit.ui.common.UserDetailsFormatter; +import org.eclipse.hawkbit.ui.utils.I18N; +import org.eclipse.hawkbit.ui.utils.SPDateTimeUtil; import org.eclipse.hawkbit.ui.utils.SPUIDefinitions; +import org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions; import org.eclipse.hawkbit.ui.utils.TableColumn; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.vaadin.spring.events.EventBus; +import com.google.gwt.thirdparty.guava.common.collect.Iterables; import com.vaadin.data.Container; +import com.vaadin.data.Item; import com.vaadin.event.dd.DropHandler; import com.vaadin.ui.Table; +import com.vaadin.ui.UI; import com.vaadin.ui.themes.ValoTheme; /** - * Parent class for table. - * - * + * Abstract table to handling entity * + * @param + * e is the entity class + * @param + * i is the id of the table */ -public abstract class AbstractTable extends Table { +public abstract class AbstractTable extends Table { private static final long serialVersionUID = 4856562746502217630L; + private static final Logger LOG = LoggerFactory.getLogger(AbstractTable.class); + + @Autowired + protected transient EventBus.SessionEventBus eventBus; + + @Autowired + protected I18N i18n; + /** * Initialize the components. */ + @PostConstruct protected void init() { setStyleName("sp-table"); setSizeFull(); setImmediate(true); - setHeight(100.0f, Unit.PERCENTAGE); + setHeight(100.0F, Unit.PERCENTAGE); addStyleName(ValoTheme.TABLE_NO_VERTICAL_LINES); addStyleName(ValoTheme.TABLE_SMALL); setSortEnabled(false); @@ -48,6 +79,50 @@ public abstract class AbstractTable extends Table { addValueChangeListener(event -> onValueChange()); selectRow(); setPageLength(SPUIDefinitions.PAGE_SIZE); + + setDataAvailable(getContainerDataSource().size() != 0); + eventBus.subscribe(this); + } + + @PreDestroy + protected void destroy() { + eventBus.unsubscribe(this); + } + + public static Set getTableValue(final Table table) { + @SuppressWarnings("unchecked") + Set values = (Set) table.getValue(); + if (values == null) { + values = Collections.emptySet(); + } + if (values.contains(null)) { + LOG.warn("Null values in table content. How could this happen?"); + } + return values; + } + + private void onValueChange() { + eventBus.publish(this, UploadArtifactUIEvent.HIDE_DROP_HINTS); + + final Set values = getTableValue(this); + + E entity = null; + I lastId = null; + if (!values.isEmpty()) { + lastId = Iterables.getLast(values); + entity = findEntityByTableValue(lastId); + } + setManagementEntitiyStateValues(values, lastId); + publishEntityAfterValueChange(entity); + } + + protected void setManagementEntitiyStateValues(final Set values, final I lastId) { + final ManagmentEntityState managmentEntityState = getManagmentEntityState(); + if (managmentEntityState == null) { + return; + } + managmentEntityState.setLastSelectedEntity(lastId); + managmentEntityState.setSelectedEnitities(values); } private void setDefault() { @@ -118,6 +193,75 @@ public abstract class AbstractTable extends Table { selectRow(); } + /** + * Add new software module to table. + * + * @param baseEntity + * new software module + */ + protected Item addEntity(final E baseEntity) { + final Object addItem = addItem(); + final Item item = getItem(addItem); + updateEntity(baseEntity, item); + return item; + } + + @SuppressWarnings("unchecked") + protected void updateEntity(final E baseEntity, final Item item) { + item.getItemProperty(SPUILabelDefinitions.VAR_NAME).setValue(baseEntity.getName()); + item.getItemProperty(SPUILabelDefinitions.VAR_ID).setValue(baseEntity.getId()); + item.getItemProperty(SPUILabelDefinitions.VAR_DESC).setValue(baseEntity.getDescription()); + item.getItemProperty(SPUILabelDefinitions.VAR_CREATED_BY) + .setValue(UserDetailsFormatter.loadAndFormatCreatedBy(baseEntity)); + item.getItemProperty(SPUILabelDefinitions.VAR_LAST_MODIFIED_BY) + .setValue(UserDetailsFormatter.loadAndFormatLastModifiedBy(baseEntity)); + item.getItemProperty(SPUILabelDefinitions.VAR_CREATED_DATE) + .setValue(SPDateTimeUtil.getFormattedDate(baseEntity.getCreatedAt())); + item.getItemProperty(SPUILabelDefinitions.VAR_LAST_MODIFIED_DATE) + .setValue(SPDateTimeUtil.getFormattedDate(baseEntity.getLastModifiedAt())); + + } + + protected void onBaseEntityEvent(final BaseEntityEvent event) { + if (BaseEntityEventType.MINIMIZED == event.getEventType()) { + UI.getCurrent().access(() -> applyMinTableSettings()); + } else if (BaseEntityEventType.MAXIMIZED == event.getEventType()) { + UI.getCurrent().access(() -> applyMaxTableSettings()); + } else if (BaseEntityEventType.NEW_ENTITY == event.getEventType()) { + UI.getCurrent().access(() -> addEntity(event.getEntity())); + } + } + + /** + * Return the entity which should be deleted by a transferable + * + * @param transferable + * the table transferable + * @return set of entities id which will deleted + */ + @SuppressWarnings("unchecked") + public Set getDeletedEntityByTransferable(final TableTransferable transferable) { + final Set selectedEntities = (Set) getTableValue(this); + final Set ids = new HashSet<>(); + final Object tranferableData = transferable.getData(SPUIDefinitions.ITEMID); + if (tranferableData == null) { + return ids; + } + + if (!selectedEntities.contains(tranferableData)) { + ids.add((I) tranferableData); + } else { + ids.addAll(selectedEntities); + } + return ids; + } + + protected abstract E findEntityByTableValue(I lastSelectedId); + + protected abstract void publishEntityAfterValueChange(E selectedLastEntity); + + protected abstract ManagmentEntityState getManagmentEntityState(); + /** * Get Id of the table. * @@ -141,7 +285,9 @@ public abstract class AbstractTable extends Table { /** * Add any generated columns if required. */ - protected abstract void addCustomGeneratedColumns(); + protected void addCustomGeneratedColumns() { + // can be overriden + } /** * Check if first row should be selected by default on load. @@ -157,11 +303,6 @@ public abstract class AbstractTable extends Table { */ protected abstract Object getItemIdToSelect(); - /** - * On select of row. - */ - protected abstract void onValueChange(); - /** * Check if the table is maximized or minimized. * @@ -174,7 +315,37 @@ public abstract class AbstractTable extends Table { * * @return List list of visible columns */ - protected abstract List getTableVisibleColumns(); + protected List getTableVisibleColumns() { + final List columnList = new ArrayList<>(); + if (!isMaximized()) { + columnList.add(new TableColumn(SPUILabelDefinitions.VAR_NAME, i18n.get("header.name"), + getColumnNameMinimizedSize())); + return columnList; + } + columnList.add(new TableColumn(SPUILabelDefinitions.VAR_NAME, i18n.get("header.name"), 0.2F)); + columnList.add(new TableColumn(SPUILabelDefinitions.VAR_CREATED_BY, i18n.get("header.createdBy"), 0.1F)); + columnList.add(new TableColumn(SPUILabelDefinitions.VAR_CREATED_DATE, i18n.get("header.createdDate"), 0.1F)); + columnList.add(new TableColumn(SPUILabelDefinitions.VAR_LAST_MODIFIED_BY, i18n.get("header.modifiedBy"), 0.1F)); + columnList.add( + new TableColumn(SPUILabelDefinitions.VAR_LAST_MODIFIED_DATE, i18n.get("header.modifiedDate"), 0.1F)); + columnList.add(new TableColumn(SPUILabelDefinitions.VAR_DESC, i18n.get("header.description"), 0.2F)); + setItemDescriptionGenerator((source, itemId, propertyId) -> { + + if (SPUILabelDefinitions.VAR_CREATED_BY.equals(propertyId)) { + return getItem(itemId).getItemProperty(SPUILabelDefinitions.VAR_CREATED_BY).getValue().toString(); + } + if (SPUILabelDefinitions.VAR_LAST_MODIFIED_BY.equals(propertyId)) { + return getItem(itemId).getItemProperty(SPUILabelDefinitions.VAR_LAST_MODIFIED_BY).getValue().toString(); + } + return null; + }); + + return columnList; + } + + protected float getColumnNameMinimizedSize() { + return 0.8F; + } /** * Get drop handler for the table. @@ -183,4 +354,6 @@ public abstract class AbstractTable extends Table { */ protected abstract DropHandler getTableDropHandler(); + protected abstract void setDataAvailable(boolean available); + } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/table/AbstractTableHeader.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/table/AbstractTableHeader.java index 0845f2c55..b137594f8 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/table/AbstractTableHeader.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/table/AbstractTableHeader.java @@ -8,13 +8,20 @@ */ package org.eclipse.hawkbit.ui.common.table; +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; + +import org.eclipse.hawkbit.repository.SpPermissionChecker; import org.eclipse.hawkbit.ui.components.SPUIButton; import org.eclipse.hawkbit.ui.components.SPUIComponentProvider; import org.eclipse.hawkbit.ui.decorators.SPUIButtonStyleSmallNoBorder; import org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil; +import org.eclipse.hawkbit.ui.utils.I18N; import org.eclipse.hawkbit.ui.utils.SPUIDefinitions; import org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions; import org.eclipse.hawkbit.ui.utils.SPUIStyleDefinitions; +import org.springframework.beans.factory.annotation.Autowired; +import org.vaadin.spring.events.EventBus; import com.vaadin.event.dd.DropHandler; import com.vaadin.server.FontAwesome; @@ -38,6 +45,15 @@ public abstract class AbstractTableHeader extends VerticalLayout { private static final long serialVersionUID = 4881626370291837175L; + @Autowired + protected I18N i18n; + + @Autowired + protected SpPermissionChecker permChecker; + + @Autowired + protected transient EventBus.SessionEventBus eventbus; + private Label headerCaption; private TextField searchField; @@ -59,10 +75,17 @@ public abstract class AbstractTableHeader extends VerticalLayout { /** * Initialze components. */ + @PostConstruct protected void init() { createComponents(); buildLayout(); restoreState(); + eventbus.subscribe(this); + } + + @PreDestroy + void destroy() { + eventbus.unsubscribe(this); } private void createComponents() { @@ -147,8 +170,8 @@ public abstract class AbstractTableHeader extends VerticalLayout { } titleFilterIconsLayout.addComponent(maxMinIcon); titleFilterIconsLayout.setComponentAlignment(maxMinIcon, Alignment.TOP_RIGHT); - titleFilterIconsLayout.setExpandRatio(headerCaption, 0.4f); - titleFilterIconsLayout.setExpandRatio(searchField, 0.6f); + titleFilterIconsLayout.setExpandRatio(headerCaption, 0.4F); + titleFilterIconsLayout.setExpandRatio(searchField, 0.6F); addComponent(titleFilterIconsLayout); @@ -168,10 +191,10 @@ public abstract class AbstractTableHeader extends VerticalLayout { dropHintDropFilterLayout.addComponent(dropFilterLayout); dropHintDropFilterLayout.setComponentAlignment(dropFilterLayout, Alignment.TOP_CENTER); - dropHintDropFilterLayout.setExpandRatio(dropFilterLayout, 1.0f); + dropHintDropFilterLayout.setExpandRatio(dropFilterLayout, 1.0F); } addComponent(dropHintDropFilterLayout); - setComponentAlignment(dropHintDropFilterLayout, Alignment.MIDDLE_CENTER); + setComponentAlignment(dropHintDropFilterLayout, Alignment.TOP_CENTER); addStyleName("bordered-layout"); addStyleName("no-border-bottom"); } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/table/BaseEntityEvent.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/table/BaseEntityEvent.java new file mode 100644 index 000000000..b0b7551ac --- /dev/null +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/table/BaseEntityEvent.java @@ -0,0 +1,44 @@ +/** + * Copyright (c) 2015 Bosch Software Innovations GmbH and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + */ +package org.eclipse.hawkbit.ui.common.table; + +import org.eclipse.hawkbit.repository.model.BaseEntity; + +/** + * Event to represent add, update or delete. + * + */ +public class BaseEntityEvent { + + private final BaseEntityEventType eventType; + + private final T entity; + + /** + * Base entity event + * + * @param eventType + * the event type + * @param entity + * the entity reference + */ + public BaseEntityEvent(final BaseEntityEventType eventType, final T entity) { + this.eventType = eventType; + this.entity = entity; + } + + public T getEntity() { + return entity; + } + + public BaseEntityEventType getEventType() { + return eventType; + } + +} diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/table/BaseEntityEventType.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/table/BaseEntityEventType.java new file mode 100644 index 000000000..d9f7f544c --- /dev/null +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/table/BaseEntityEventType.java @@ -0,0 +1,17 @@ +/** + * 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.common.table; + +/** + * Types of the entity event. + * + */ +public enum BaseEntityEventType { + NEW_ENTITY, UPDATED_ENTITY, DELETE_ENTITY, SELECTED_ENTITY, MAXIMIZED, MINIMIZED; +} 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..8d9f5a902 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 @@ -13,10 +13,20 @@ import java.util.HashMap; import java.util.Map; import java.util.Optional; +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; + +import org.eclipse.hawkbit.repository.SpPermissionChecker; +import org.eclipse.hawkbit.repository.model.BaseEntity; +import org.eclipse.hawkbit.ui.common.table.BaseEntityEvent; +import org.eclipse.hawkbit.ui.common.table.BaseEntityEventType; import org.eclipse.hawkbit.ui.management.state.ManagementUIState; +import org.eclipse.hawkbit.ui.utils.I18N; import org.eclipse.hawkbit.ui.utils.SPUIDefinitions; import org.eclipse.hawkbit.ui.utils.SPUIStyleDefinitions; +import org.eclipse.hawkbit.ui.utils.UINotification; import org.springframework.beans.factory.annotation.Autowired; +import org.vaadin.spring.events.EventBus; import org.vaadin.tokenfield.TokenField; import org.vaadin.tokenfield.TokenField.InsertPosition; @@ -28,6 +38,7 @@ import com.vaadin.server.FontAwesome; import com.vaadin.shared.ui.combobox.FilteringMode; import com.vaadin.ui.Button; import com.vaadin.ui.CssLayout; +import com.vaadin.ui.UI; import com.vaadin.ui.themes.ValoTheme; /** @@ -37,7 +48,7 @@ import com.vaadin.ui.themes.ValoTheme; * * */ -public abstract class AbstractTagToken implements Serializable { +public abstract class AbstractTagToken implements Serializable { private static final String COLOR_PROPERTY = "color"; @@ -53,12 +64,46 @@ public abstract class AbstractTagToken implements Serializable { protected CssLayout tokenLayout = new CssLayout(); + @Autowired + protected SpPermissionChecker checker; + + @Autowired + protected I18N i18n; + + @Autowired + protected UINotification uinotification; + + @Autowired + protected transient EventBus.SessionEventBus eventBus; + @Autowired protected ManagementUIState managementUIState; + protected T selectedEntity; + + @PostConstruct protected void init() { createTokenField(); checkIfTagAssignedIsAllowed(); + eventBus.subscribe(this); + } + + @PreDestroy + protected void destroy() { + eventBus.unsubscribe(this); + } + + protected void onBaseEntityEvent(final BaseEntityEvent baseEntityEvent) { + if (BaseEntityEventType.SELECTED_ENTITY != baseEntityEvent.getEventType()) { + return; + } + UI.getCurrent().access(() -> { + final T entity = baseEntityEvent.getEntity(); + if (entity != null) { + selectedEntity = entity; + repopulateToken(); + } + }); } private void createTokenField() { @@ -151,18 +196,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 +236,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/common/tagdetails/AbstractTargetTagToken.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/tagdetails/AbstractTargetTagToken.java index efedbe3bc..ce9f101f3 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/tagdetails/AbstractTargetTagToken.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/tagdetails/AbstractTargetTagToken.java @@ -8,55 +8,25 @@ */ package org.eclipse.hawkbit.ui.common.tagdetails; -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; - import org.eclipse.hawkbit.eventbus.event.TargetTagCreatedBulkEvent; import org.eclipse.hawkbit.eventbus.event.TargetTagDeletedEvent; -import org.eclipse.hawkbit.repository.SpPermissionChecker; import org.eclipse.hawkbit.repository.TagManagement; +import org.eclipse.hawkbit.repository.model.BaseEntity; import org.eclipse.hawkbit.repository.model.TargetTag; -import org.eclipse.hawkbit.ui.utils.I18N; import org.springframework.beans.factory.annotation.Autowired; -import org.vaadin.spring.events.EventBus; import org.vaadin.spring.events.EventScope; import org.vaadin.spring.events.annotation.EventBusListenerMethod; -import com.vaadin.ui.UI; - /** * Abstract class for target tag token layout. */ -public abstract class AbstractTargetTagToken extends AbstractTagToken { +public abstract class AbstractTargetTagToken extends AbstractTagToken { private static final long serialVersionUID = 7772876588903171201L; - protected UI ui; - - @Autowired - protected transient EventBus.SessionEventBus eventBus; - - @Autowired - protected I18N i18n; @Autowired protected transient TagManagement tagManagement; - @Autowired - protected SpPermissionChecker checker; - - @Override - @PostConstruct - protected void init() { - super.init(); - ui = UI.getCurrent(); - eventBus.subscribe(this); - } - - @PreDestroy - void destroy() { - eventBus.unsubscribe(this); - } - @EventBusListenerMethod(scope = EventScope.SESSION) void onEventTargetTagCreated(final TargetTagCreatedBulkEvent event) { for (final TargetTag tag : event.getEntities()) { diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/tagdetails/DistributionTagToken.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/tagdetails/DistributionTagToken.java index c8824e455..178610c23 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/tagdetails/DistributionTagToken.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/tagdetails/DistributionTagToken.java @@ -14,34 +14,25 @@ import java.util.List; import java.util.Set; import java.util.stream.Collectors; -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; - import org.eclipse.hawkbit.eventbus.event.DistributionSetTagAssigmentResultEvent; import org.eclipse.hawkbit.eventbus.event.DistributionSetTagCreatedBulkEvent; import org.eclipse.hawkbit.eventbus.event.DistributionSetTagDeletedEvent; import org.eclipse.hawkbit.eventbus.event.DistributionSetTagUpdateEvent; import org.eclipse.hawkbit.repository.DistributionSetManagement; -import org.eclipse.hawkbit.repository.SpPermissionChecker; import org.eclipse.hawkbit.repository.TagManagement; import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.DistributionSetTag; -import org.eclipse.hawkbit.repository.model.DistributionSetTagAssigmentResult; +import org.eclipse.hawkbit.repository.model.DistributionSetTagAssignmentResult; import org.eclipse.hawkbit.ui.management.event.DistributionTableEvent; -import org.eclipse.hawkbit.ui.management.event.DistributionTableEvent.DistributionComponentEvent; import org.eclipse.hawkbit.ui.management.event.ManagementUIEvent; import org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil; -import org.eclipse.hawkbit.ui.utils.I18N; -import org.eclipse.hawkbit.ui.utils.UINotification; import org.springframework.beans.factory.annotation.Autowired; -import org.vaadin.spring.events.EventBus; import org.vaadin.spring.events.EventScope; import org.vaadin.spring.events.annotation.EventBusListenerMethod; import com.vaadin.data.Item; import com.vaadin.spring.annotation.SpringComponent; import com.vaadin.spring.annotation.ViewScope; -import com.vaadin.ui.UI; /** * Implementation of target/ds tag token layout. @@ -49,44 +40,18 @@ import com.vaadin.ui.UI; */ @SpringComponent @ViewScope -public class DistributionTagToken extends AbstractTagToken { +public class DistributionTagToken extends AbstractTagToken { private static final long serialVersionUID = -8022738301736043396L; - - @Autowired - private SpPermissionChecker spChecker; - - @Autowired - private I18N i18n; - - @Autowired - private UINotification uinotification; - - @Autowired - private transient EventBus.SessionEventBus eventBus; - @Autowired private transient TagManagement tagManagement; @Autowired private transient DistributionSetManagement distributionSetManagement; - private DistributionSet selectedDS; - - private UI ui; - // To Be Done : have to set this value based on view??? private static final Boolean NOTAGS_SELECTED = Boolean.FALSE; - @Override - @PostConstruct - protected void init() { - super.init(); - ui = UI.getCurrent(); - eventBus.subscribe(this); - - } - @Override protected String getTagStyleName() { return "distribution-tag-"; @@ -100,7 +65,7 @@ public class DistributionTagToken extends AbstractTagToken { @Override protected void assignTag(final String tagNameSelected) { if (tagNameSelected != null) { - final DistributionSetTagAssigmentResult result = toggleAssignment(tagNameSelected); + final DistributionSetTagAssignmentResult result = toggleAssignment(tagNameSelected); if (result.getAssigned() >= 1 && NOTAGS_SELECTED) { eventBus.publish(this, ManagementUIEvent.ASSIGN_DISTRIBUTION_TAG); } @@ -109,18 +74,18 @@ public class DistributionTagToken extends AbstractTagToken { } } - private DistributionSetTagAssigmentResult toggleAssignment(final String tagNameSelected) { + private DistributionSetTagAssignmentResult toggleAssignment(final String tagNameSelected) { final Set distributionList = new HashSet<>(); - distributionList.add(selectedDS.getId()); - final DistributionSetTagAssigmentResult result = distributionSetManagement.toggleTagAssignment(distributionList, - tagNameSelected); - uinotification.displaySuccess(HawkbitCommonUtil.getDistributionTagAssignmentMsg(tagNameSelected, result, i18n)); + distributionList.add(selectedEntity.getId()); + final DistributionSetTagAssignmentResult result = distributionSetManagement + .toggleTagAssignment(distributionList, tagNameSelected); + uinotification.displaySuccess(HawkbitCommonUtil.createAssignmentMessage(tagNameSelected, result, i18n)); return result; } @Override protected void unassignTag(final String tagName) { - final DistributionSetTagAssigmentResult result = toggleAssignment(tagName); + final DistributionSetTagAssignmentResult result = toggleAssignment(tagName); if (result.getUnassigned() >= 1 && (isClickedTagListEmpty() || getClickedTagList().contains(tagName))) { eventBus.publish(this, ManagementUIEvent.UNASSIGN_DISTRIBUTION_TAG); } @@ -140,14 +105,14 @@ public class DistributionTagToken extends AbstractTagToken { @Override protected Boolean isToggleTagAssignmentAllowed() { - return spChecker.hasUpdateDistributionPermission(); + return checker.hasUpdateDistributionPermission(); } @Override public void displayAlreadyAssignedTags() { removePreviouslyAddedTokens(); - if (selectedDS != null) { - for (final DistributionSetTag tag : selectedDS.getTags()) { + if (selectedEntity != null) { + for (final DistributionSetTag tag : selectedEntity.getTags()) { addNewToken(tag.getId()); } } @@ -163,18 +128,7 @@ public class DistributionTagToken extends AbstractTagToken { @EventBusListenerMethod(scope = EventScope.SESSION) void onEvent(final DistributionTableEvent distributionTableEvent) { - if (distributionTableEvent.getDistributionComponentEvent() == DistributionComponentEvent.ON_VALUE_CHANGE) { - ui.access(() -> { - /** - * distributionTableEvent.getDistributionSet() is null when - * table has no data. - */ - if (distributionTableEvent.getDistributionSet() != null) { - selectedDS = distributionTableEvent.getDistributionSet(); - repopulateToken(); - } - }); - } + onBaseEntityEvent(distributionTableEvent); } @EventBusListenerMethod(scope = EventScope.SESSION) @@ -202,7 +156,7 @@ public class DistributionTagToken extends AbstractTagToken { @EventBusListenerMethod(scope = EventScope.SESSION) void onTargetTagAssigmentResultEvent(final DistributionSetTagAssigmentResultEvent event) { - final DistributionSetTagAssigmentResult assignmentResult = event.getAssigmentResult(); + final DistributionSetTagAssignmentResult assignmentResult = event.getAssigmentResult(); final DistributionSetTag tag = assignmentResult.getDistributionSetTag(); if (isAssign(assignmentResult)) { addNewToken(tag.getId()); @@ -212,9 +166,9 @@ public class DistributionTagToken extends AbstractTagToken { } - protected boolean isAssign(final DistributionSetTagAssigmentResult assignmentResult) { + protected boolean isAssign(final DistributionSetTagAssignmentResult assignmentResult) { if (assignmentResult.getAssigned() > 0) { - final List assignedDsNames = assignmentResult.getAssignedDs().stream().map(t -> t.getId()) + final List assignedDsNames = assignmentResult.getAssignedEntity().stream().map(t -> t.getId()) .collect(Collectors.toList()); if (assignedDsNames.contains(managementUIState.getLastSelectedDsIdName().getId())) { return true; @@ -223,9 +177,9 @@ public class DistributionTagToken extends AbstractTagToken { return false; } - protected boolean isUnassign(final DistributionSetTagAssigmentResult assignmentResult) { + protected boolean isUnassign(final DistributionSetTagAssignmentResult assignmentResult) { if (assignmentResult.getUnassigned() > 0) { - final List assignedDsNames = assignmentResult.getUnassignedDs().stream().map(t -> t.getId()) + final List assignedDsNames = assignmentResult.getUnassignedEntity().stream().map(t -> t.getId()) .collect(Collectors.toList()); if (assignedDsNames.contains(managementUIState.getLastSelectedDsIdName().getId())) { return true; @@ -234,9 +188,4 @@ public class DistributionTagToken extends AbstractTagToken { return false; } - @PreDestroy - void destroy() { - eventBus.unsubscribe(this); - } - } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/tagdetails/TargetTagToken.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/tagdetails/TargetTagToken.java index 8982be759..6f03c5860 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/tagdetails/TargetTagToken.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/common/tagdetails/TargetTagToken.java @@ -19,10 +19,9 @@ import org.eclipse.hawkbit.eventbus.event.TargetTagUpdateEvent; import org.eclipse.hawkbit.repository.TargetManagement; import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.repository.model.TargetTag; -import org.eclipse.hawkbit.repository.model.TargetTagAssigmentResult; +import org.eclipse.hawkbit.repository.model.TargetTagAssignmentResult; import org.eclipse.hawkbit.ui.management.event.ManagementUIEvent; import org.eclipse.hawkbit.ui.management.event.TargetTableEvent; -import org.eclipse.hawkbit.ui.management.event.TargetTableEvent.TargetComponentEvent; import org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil; import org.eclipse.hawkbit.ui.utils.UINotification; import org.springframework.beans.factory.annotation.Autowired; @@ -40,7 +39,7 @@ import com.vaadin.spring.annotation.ViewScope; */ @SpringComponent @ViewScope -public class TargetTagToken extends AbstractTargetTagToken { +public class TargetTagToken extends AbstractTargetTagToken { private static final long serialVersionUID = 7124887018280196721L; @@ -53,8 +52,6 @@ public class TargetTagToken extends AbstractTargetTagToken { @Autowired private transient TargetManagement targetManagement; - private Target selectedTarget; - @Override protected String getTagStyleName() { return "target-tag-"; @@ -68,7 +65,7 @@ public class TargetTagToken extends AbstractTargetTagToken { @Override protected void assignTag(final String tagNameSelected) { if (tagNameSelected != null) { - final TargetTagAssigmentResult result = toggleAssignment(tagNameSelected); + final TargetTagAssignmentResult result = toggleAssignment(tagNameSelected); if (result.getAssigned() >= 1 && NOTAGS_SELECTED) { eventBus.publish(this, ManagementUIEvent.ASSIGN_TARGET_TAG); } @@ -77,17 +74,17 @@ public class TargetTagToken extends AbstractTargetTagToken { } } - private TargetTagAssigmentResult toggleAssignment(final String tagNameSelected) { + private TargetTagAssignmentResult toggleAssignment(final String tagNameSelected) { final Set targetList = new HashSet<>(); - targetList.add(selectedTarget.getControllerId()); - final TargetTagAssigmentResult result = targetManagement.toggleTagAssignment(targetList, tagNameSelected); - uinotification.displaySuccess(HawkbitCommonUtil.getTargetTagAssigmentMsg(tagNameSelected, result, i18n)); + targetList.add(selectedEntity.getControllerId()); + final TargetTagAssignmentResult result = targetManagement.toggleTagAssignment(targetList, tagNameSelected); + uinotification.displaySuccess(HawkbitCommonUtil.createAssignmentMessage(tagNameSelected, result, i18n)); return result; } @Override protected void unassignTag(final String tagName) { - final TargetTagAssigmentResult result = toggleAssignment(tagName); + final TargetTagAssignmentResult result = toggleAssignment(tagName); if (result.getUnassigned() >= 1 && (isClickedTagListEmpty() || getClickedTagList().contains(tagName))) { eventBus.publish(this, ManagementUIEvent.UNASSIGN_TARGET_TAG); } @@ -113,8 +110,8 @@ public class TargetTagToken extends AbstractTargetTagToken { @Override protected void displayAlreadyAssignedTags() { removePreviouslyAddedTokens(); - if (selectedTarget != null) { - for (final TargetTag tag : selectedTarget.getTags()) { + if (selectedEntity != null) { + for (final TargetTag tag : selectedEntity.getTags()) { addNewToken(tag.getId()); } } @@ -139,7 +136,7 @@ public class TargetTagToken extends AbstractTargetTagToken { @EventBusListenerMethod(scope = EventScope.SESSION) void onTargetTagAssigmentResultEvent(final TargetTagAssigmentResultEvent event) { - final TargetTagAssigmentResult assignmentResult = event.getAssigmentResult(); + final TargetTagAssignmentResult assignmentResult = event.getAssigmentResult(); final TargetTag targetTag = assignmentResult.getTargetTag(); if (isAssign(assignmentResult)) { addNewToken(targetTag.getId()); @@ -149,9 +146,9 @@ public class TargetTagToken extends AbstractTargetTagToken { } - protected boolean isAssign(final TargetTagAssigmentResult assignmentResult) { + protected boolean isAssign(final TargetTagAssignmentResult assignmentResult) { if (assignmentResult.getAssigned() > 0) { - final List assignedTargetNames = assignmentResult.getAssignedTargets().stream() + final List assignedTargetNames = assignmentResult.getAssignedEntity().stream() .map(t -> t.getControllerId()).collect(Collectors.toList()); if (assignedTargetNames.contains(managementUIState.getLastSelectedTargetIdName().getControllerId())) { return true; @@ -160,9 +157,9 @@ public class TargetTagToken extends AbstractTargetTagToken { return false; } - protected boolean isUnassign(final TargetTagAssigmentResult assignmentResult) { + protected boolean isUnassign(final TargetTagAssignmentResult assignmentResult) { if (assignmentResult.getUnassigned() > 0) { - final List unassignedTargetNamesList = assignmentResult.getUnassignedTargets().stream() + final List unassignedTargetNamesList = assignmentResult.getUnassignedEntity().stream() .map(t -> t.getControllerId()).collect(Collectors.toList()); if (unassignedTargetNamesList.contains(managementUIState.getLastSelectedTargetIdName().getControllerId())) { return true; @@ -173,16 +170,7 @@ public class TargetTagToken extends AbstractTargetTagToken { @EventBusListenerMethod(scope = EventScope.SESSION) void onEvent(final TargetTableEvent targetTableEvent) { - if (targetTableEvent.getTargetComponentEvent() == TargetComponentEvent.SELECTED_TARGET - && targetTableEvent.getTarget() != null) { - ui.access(() -> { - /** - * targetTableEvent.getTarget() is null when table has no data. - */ - selectedTarget = targetTableEvent.getTarget(); - repopulateToken(); - }); - } + onBaseEntityEvent(targetTableEvent); } } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/components/ProxyTarget.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/components/ProxyTarget.java index d85b2bc71..9ac39616d 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/components/ProxyTarget.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/components/ProxyTarget.java @@ -36,6 +36,8 @@ public class ProxyTarget extends Target { private DistributionSet installedDistributionSet; + private DistributionSet assignedDistributionSet; + private TargetIdName targetIdName; private String assignedDistNameVersion; @@ -249,6 +251,21 @@ public class ProxyTarget extends Target { this.installedDistributionSet = installedDistributionSet; } + /** + * @return the assignedDistributionSet + */ + public DistributionSet getAssignedDistributionSet() { + return assignedDistributionSet; + } + + /** + * @param assignedDistributionSet + * the assignedDistributionSet to set + */ + public void setAssignedDistributionSet(DistributionSet assignedDistributionSet) { + this.assignedDistributionSet = assignedDistributionSet; + } + /** * @return the targetIdName */ @@ -297,4 +314,5 @@ public class ProxyTarget extends Target { public void setStatus(final Status status) { this.status = status; } + } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/components/SPUIComponentProvider.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/components/SPUIComponentProvider.java index f5008eb31..d8e5e31d1 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/components/SPUIComponentProvider.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/components/SPUIComponentProvider.java @@ -12,7 +12,9 @@ import java.util.Arrays; import java.util.Map; import org.apache.commons.lang3.StringUtils; +import org.eclipse.hawkbit.repository.model.BaseEntity; import org.eclipse.hawkbit.repository.model.DistributionSet; +import org.eclipse.hawkbit.ui.common.UserDetailsFormatter; import org.eclipse.hawkbit.ui.decorators.SPUIButtonDecorator; import org.eclipse.hawkbit.ui.decorators.SPUIComboBoxDecorator; import org.eclipse.hawkbit.ui.decorators.SPUIHeaderLayoutDecorator; @@ -20,6 +22,7 @@ import org.eclipse.hawkbit.ui.decorators.SPUILabelDecorator; import org.eclipse.hawkbit.ui.decorators.SPUITextAreaDecorator; import org.eclipse.hawkbit.ui.decorators.SPUITextFieldDecorator; import org.eclipse.hawkbit.ui.decorators.SPUIWindowDecorator; +import org.eclipse.hawkbit.ui.utils.I18N; import org.eclipse.hawkbit.ui.utils.SPUIDefinitions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -328,6 +331,50 @@ public final class SPUIComponentProvider { return nameValueLabel; } + private static Label createUsernameLabel(final String label, final String username) { + String loadAndFormatUsername = StringUtils.EMPTY; + if (!StringUtils.isEmpty(username)) { + loadAndFormatUsername = UserDetailsFormatter.loadAndFormatUsername(username); + } + + final Label nameValueLabel = new Label(getBoldHTMLText(label) + loadAndFormatUsername, ContentMode.HTML); + nameValueLabel.setSizeFull(); + nameValueLabel.addStyleName(SPUIDefinitions.TEXT_STYLE); + nameValueLabel.addStyleName("label-style"); + nameValueLabel.setDescription(loadAndFormatUsername); + return nameValueLabel; + } + + /** + * Create label which represents the {@link BaseEntity#getCreatedBy()} by + * user name + * + * @param i18n + * the i18n + * @param baseEntity + * the entity + * @return the label + */ + public static Label createCreatedByLabel(final I18N i18n, final BaseEntity baseEntity) { + return createUsernameLabel(i18n.get("label.created.by"), + baseEntity == null ? StringUtils.EMPTY : baseEntity.getCreatedBy()); + } + + /** + * Create label which represents the + * {@link BaseEntity#getLastModifiedBy()()} by user name + * + * @param i18n + * the i18n + * @param baseEntity + * the entity + * @return the label + */ + public static Label createLastModifiedByLabel(final I18N i18n, final BaseEntity baseEntity) { + return createUsernameLabel(i18n.get("label.modified.by"), + baseEntity == null ? StringUtils.EMPTY : baseEntity.getLastModifiedBy()); + } + /** * Get Bold Text. * diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/customrenderers/client/LinkRendererConnector.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/customrenderers/client/LinkRendererConnector.java deleted file mode 100644 index bc48d64d7..000000000 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/customrenderers/client/LinkRendererConnector.java +++ /dev/null @@ -1,29 +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.ui.customrenderers.client; - -import org.eclipse.hawkbit.ui.customrenderers.renderers.LinkRenderer; - -import com.vaadin.client.connectors.ButtonRendererConnector; -import com.vaadin.shared.ui.Connect; - -/** - * - * A connector for {@link LinkRenderer}. - * - */ -@Connect(org.eclipse.hawkbit.ui.customrenderers.renderers.LinkRenderer.class) -public class LinkRendererConnector extends ButtonRendererConnector { - private static final long serialVersionUID = 7987417436367399331L; - - @Override - public org.eclipse.hawkbit.ui.customrenderers.client.renderers.LinkRenderer getRenderer() { - return (org.eclipse.hawkbit.ui.customrenderers.client.renderers.LinkRenderer) super.getRenderer(); - } -} diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/customrenderers/client/RolloutRendererConnector.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/customrenderers/client/RolloutRendererConnector.java new file mode 100644 index 000000000..2175dea29 --- /dev/null +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/customrenderers/client/RolloutRendererConnector.java @@ -0,0 +1,37 @@ +/** + * 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.customrenderers.client; + +import org.eclipse.hawkbit.ui.customrenderers.client.renderers.RolloutRendererData; + +import com.google.web.bindery.event.shared.HandlerRegistration; +import com.vaadin.client.connectors.ClickableRendererConnector; +import com.vaadin.client.renderers.ClickableRenderer.RendererClickHandler; +import com.vaadin.shared.ui.Connect; + +import elemental.json.JsonObject; +/** + * A connector for {@link CustomObjectRenderer }. + * + */ +@Connect(org.eclipse.hawkbit.ui.customrenderers.renderers.RolloutRenderer.class) +public class RolloutRendererConnector extends ClickableRendererConnector { + private static final long serialVersionUID = 7734682321931830566L; + + public org.eclipse.hawkbit.ui.customrenderers.client.renderers.RolloutRenderer getRenderer() { + return (org.eclipse.hawkbit.ui.customrenderers.client.renderers.RolloutRenderer) super.getRenderer(); + } + + @Override + protected HandlerRegistration addClickHandler( + RendererClickHandler handler) { + return getRenderer().addClickHandler(handler); + } +} \ No newline at end of file diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/customrenderers/client/renderers/LinkRenderer.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/customrenderers/client/renderers/LinkRenderer.java deleted file mode 100644 index 0abe4044b..000000000 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/customrenderers/client/renderers/LinkRenderer.java +++ /dev/null @@ -1,42 +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.ui.customrenderers.client.renderers; - -import com.google.gwt.user.client.ui.Button; -import com.vaadin.client.renderers.ButtonRenderer; -import com.vaadin.client.ui.VButton; -import com.vaadin.client.widget.grid.RendererCellReference; - -/** - * - * Renders link with provided text. - * - */ -public class LinkRenderer extends ButtonRenderer { - @Override - public void render(RendererCellReference cell, String text, Button button) { - button.setText(text); - applystyle(button); - // this is to allow the button to disappear, if the text is null - button.setVisible(text != null); - button.getElement().setId(new StringBuilder("link").append(".").append(text).toString()); - } - - private void applystyle(Button button) { - button.setStyleName(VButton.CLASSNAME); - button.addStyleName(getStyle("borderless")); - button.addStyleName(getStyle("small")); - button.addStyleName(getStyle("on-focus-no-border")); - button.addStyleName(getStyle("link")); - } - - private String getStyle(final String style) { - return new StringBuilder(style).append(" ").append(VButton.CLASSNAME).append("-").append(style).toString(); - } -} diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/customrenderers/client/renderers/RolloutRenderer.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/customrenderers/client/renderers/RolloutRenderer.java new file mode 100644 index 000000000..da8fc2544 --- /dev/null +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/customrenderers/client/renderers/RolloutRenderer.java @@ -0,0 +1,65 @@ +/** + * 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.customrenderers.client.renderers; + +import com.google.gwt.core.shared.GWT; +import com.vaadin.client.renderers.ClickableRenderer; +import com.vaadin.client.ui.VButton; +import com.vaadin.client.widget.grid.RendererCellReference; + +/** + * Renders button with provided CustomObject. + * Used to display button with link. + * + */ +public class RolloutRenderer extends ClickableRenderer { + + @Override + public VButton createWidget() { + VButton b = GWT.create(VButton.class); + b.addClickHandler(this); + b.setStylePrimaryName("v-nativebutton"); + return b; + } + + @Override + public void render(RendererCellReference cell, RolloutRendererData text, VButton button) { + final String creating = "CREATING"; + button.setText(text.getName()); + applystyle(button); + // this is to allow the button to disappear, if the text is null + button.setVisible(text.getName() != null); + button.getElement().setId(new StringBuilder("link").append(".").append(text.getName()).toString()); + /* + * checking Rollout Status for applying button style. If Rollout status + * is not "CREATING", then the Rollout button is applying hyperlink + * style + */ + final boolean isStatusCreate = text.getStatus() != null && creating.equalsIgnoreCase(text.getStatus()); + if (isStatusCreate) { + button.addStyleName(getStyle("boldhide")); + button.setEnabled(false); + } else { + button.setEnabled(true); + } + } + + private void applystyle(VButton button) { + button.setStyleName(VButton.CLASSNAME); + button.addStyleName(getStyle("borderless")); + button.addStyleName(getStyle("small")); + button.addStyleName(getStyle("on-focus-no-border")); + button.addStyleName(getStyle("link")); + } + + private String getStyle(final String style) { + return new StringBuilder(style).append(" ").append(VButton.CLASSNAME).append("-").append(style).toString(); + } + +} \ No newline at end of file diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/customrenderers/client/renderers/RolloutRendererData.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/customrenderers/client/renderers/RolloutRendererData.java new file mode 100644 index 000000000..6c751e6a2 --- /dev/null +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/customrenderers/client/renderers/RolloutRendererData.java @@ -0,0 +1,62 @@ +/** + * 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.customrenderers.client.renderers; + +import java.io.Serializable; + +/** + * RendererData class with Name and Status. + * + */ + +public class RolloutRendererData implements Serializable { + private static final long serialVersionUID = -5018181529953620263L; + + private String name; + + private String status; + + /** + * Initialize the RendererData. + */ + public RolloutRendererData() { + + } + + /** + * Initialize the RendererData. + * + * @param name + * Name of the Rollout. + * @param status + * Status of Rollout. + */ + public RolloutRendererData(String name, String status) { + super(); + this.name = name; + this.status = status; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + +} diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/customrenderers/renderers/LinkRenderer.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/customrenderers/renderers/LinkRenderer.java deleted file mode 100644 index d913ca380..000000000 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/customrenderers/renderers/LinkRenderer.java +++ /dev/null @@ -1,37 +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.ui.customrenderers.renderers; - -import com.vaadin.ui.renderers.ButtonRenderer; - -/** - * - * Renders link with provided text. - * - */ -public class LinkRenderer extends ButtonRenderer { - private static final long serialVersionUID = -1242995370043404892L; - - /** - * Intialise link renderer. - */ - public LinkRenderer() { - super(); - } - - /** - * Intialise link renderer with {@link RendererClickListener} - * - * @param listener - * RendererClickListener - */ - public LinkRenderer(RendererClickListener listener) { - super(listener); - } -} diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/customrenderers/renderers/RolloutRenderer.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/customrenderers/renderers/RolloutRenderer.java new file mode 100644 index 000000000..29663dd9d --- /dev/null +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/customrenderers/renderers/RolloutRenderer.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.ui.customrenderers.renderers; + +import org.eclipse.hawkbit.ui.customrenderers.client.renderers.RolloutRendererData; + +import com.vaadin.ui.renderers.ClickableRenderer; + +import elemental.json.JsonValue; + +/** + * Renders button with provided CustomObject. + * Used to display button with link. + * + */ + +public class RolloutRenderer extends ClickableRenderer { + + private static final long serialVersionUID = -8754180585906263554L; + + /** + * Creates a new custom object renderer. + */ + public RolloutRenderer() { + super(RolloutRendererData.class, null); + } + + /** + * Initialize custom object renderer with {@link Class} + * + * @param presentationType + * Class + */ + + public RolloutRenderer(Class presentationType) { + super(presentationType); + } + + /** + * Creates a new custom object renderer and adds the given click listener to it. + * + * @param listener + * the click listener to register + */ + public RolloutRenderer(RendererClickListener listener) { + this(); + addClickListener(listener); + } + + @Override + public JsonValue encode(RolloutRendererData resource) { + return super.encode(resource, RolloutRendererData.class); + } +} diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/DistributionsView.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/DistributionsView.java index 451a16ea7..ab41bc579 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/DistributionsView.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/DistributionsView.java @@ -13,7 +13,7 @@ import javax.annotation.PreDestroy; import org.eclipse.hawkbit.repository.SpPermissionChecker; import org.eclipse.hawkbit.ui.HawkbitUI; import org.eclipse.hawkbit.ui.artifacts.event.SoftwareModuleEvent; -import org.eclipse.hawkbit.ui.artifacts.event.SoftwareModuleEvent.SoftwareModuleEventType; +import org.eclipse.hawkbit.ui.common.table.BaseEntityEventType; import org.eclipse.hawkbit.ui.distributions.disttype.DSTypeFilterLayout; import org.eclipse.hawkbit.ui.distributions.dstable.DistributionSetTableLayout; import org.eclipse.hawkbit.ui.distributions.event.DragEvent; @@ -22,7 +22,6 @@ import org.eclipse.hawkbit.ui.distributions.smtable.SwModuleTableLayout; import org.eclipse.hawkbit.ui.distributions.smtype.DistSMTypeFilterLayout; import org.eclipse.hawkbit.ui.distributions.state.ManageDistUIState; import org.eclipse.hawkbit.ui.management.event.DistributionTableEvent; -import org.eclipse.hawkbit.ui.management.event.DistributionTableEvent.DistributionComponentEvent; import org.eclipse.hawkbit.ui.utils.I18N; import org.eclipse.hawkbit.ui.utils.SPUIDefinitions; import org.eclipse.hawkbit.ui.utils.UINotification; @@ -160,18 +159,18 @@ public class DistributionsView extends VerticalLayout implements View, BrowserWi @EventBusListenerMethod(scope = EventScope.SESSION) void onEvent(final DistributionTableEvent event) { - if (event.getDistributionComponentEvent() == DistributionComponentEvent.MINIMIZED) { + if (BaseEntityEventType.MINIMIZED == event.getEventType()) { minimizeDistTable(); - } else if (event.getDistributionComponentEvent() == DistributionComponentEvent.MAXIMIZED) { + } else if (BaseEntityEventType.MAXIMIZED == event.getEventType()) { maximizeDistTable(); } } @EventBusListenerMethod(scope = EventScope.SESSION) void onEvent(final SoftwareModuleEvent event) { - if (event.getSoftwareModuleEventType() == SoftwareModuleEventType.MINIMIZED) { + if (BaseEntityEventType.MINIMIZED == event.getEventType()) { minimizeSwTable(); - } else if (event.getSoftwareModuleEventType() == SoftwareModuleEventType.MAXIMIZED) { + } else if (BaseEntityEventType.MAXIMIZED == event.getEventType()) { maximizeSwTable(); } } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/disttype/CreateUpdateDistSetTypeLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/disttype/CreateUpdateDistSetTypeLayout.java index 8d609f628..64a06bd38 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/disttype/CreateUpdateDistSetTypeLayout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/disttype/CreateUpdateDistSetTypeLayout.java @@ -284,7 +284,7 @@ public class CreateUpdateDistSetTypeLayout extends CustomComponent implements Co mainLayout.addComponent(fieldLayout); mainLayout.addComponent(twinTableLayout); - + colorLayout = new HorizontalLayout(); sliderLayout = new VerticalLayout(); final HorizontalLayout chooseColorLayout = new HorizontalLayout(); @@ -299,6 +299,7 @@ public class CreateUpdateDistSetTypeLayout extends CustomComponent implements Co mainWindowLayout.addComponent(colorLayout); mainWindowLayout.addComponent(buttonLayout); setCompositionRoot(mainWindowLayout); + typeName.focus(); } private HorizontalLayout createTwinColumnLayout() { diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/disttype/DSTypeFilterButtons.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/disttype/DSTypeFilterButtons.java index cd36918e8..1abc32a3e 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/disttype/DSTypeFilterButtons.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/disttype/DSTypeFilterButtons.java @@ -8,10 +8,7 @@ */ package org.eclipse.hawkbit.ui.distributions.disttype; -import javax.annotation.PreDestroy; - import org.eclipse.hawkbit.ui.common.DistributionSetTypeBeanQuery; -import org.eclipse.hawkbit.ui.common.filterlayout.AbstractFilterButtonClickBehaviour; import org.eclipse.hawkbit.ui.common.filterlayout.AbstractFilterButtons; import org.eclipse.hawkbit.ui.distributions.event.DistributionSetTypeEvent; import org.eclipse.hawkbit.ui.distributions.event.DistributionsViewAcceptCriteria; @@ -23,7 +20,6 @@ import org.eclipse.hawkbit.ui.utils.SPUIDefinitions; import org.springframework.beans.factory.annotation.Autowired; import org.vaadin.addons.lazyquerycontainer.BeanQueryFactory; import org.vaadin.addons.lazyquerycontainer.LazyQueryContainer; -import org.vaadin.spring.events.EventBus; import org.vaadin.spring.events.EventScope; import org.vaadin.spring.events.annotation.EventBusListenerMethod; @@ -45,27 +41,12 @@ public class DSTypeFilterButtons extends AbstractFilterButtons { private static final long serialVersionUID = 771251569981876005L; - @Autowired - private transient EventBus.SessionEventBus eventBus; - @Autowired private ManageDistUIState manageDistUIState; @Autowired private DistributionsViewAcceptCriteria distributionsViewAcceptCriteria; - /** - * Initialize component. - * - * @param filterButtonClickBehaviour - * the clickable behaviour. - */ - @Override - public void init(final AbstractFilterButtonClickBehaviour filterButtonClickBehaviour) { - super.init(filterButtonClickBehaviour); - eventBus.subscribe(this); - } - @Override protected String getButtonsTableId() { @@ -79,10 +60,9 @@ public class DSTypeFilterButtons extends AbstractFilterButtons { } @Override - protected boolean isClickedByDefault(final Long buttonId) { - + protected boolean isClickedByDefault(final String typeName) { return manageDistUIState.getManageDistFilters().getClickedDistSetType() != null - && manageDistUIState.getManageDistFilters().getClickedDistSetType().getId().equals(buttonId); + && manageDistUIState.getManageDistFilters().getClickedDistSetType().getName().equals(typeName); } @Override @@ -141,9 +121,4 @@ public class DSTypeFilterButtons extends AbstractFilterButtons { setContainerDataSource(createButtonsLazyQueryContainer()); } - @PreDestroy - void destroy() { - eventBus.unsubscribe(this); - } - } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/disttype/DSTypeFilterHeader.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/disttype/DSTypeFilterHeader.java index 068c28065..02c959286 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/disttype/DSTypeFilterHeader.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/disttype/DSTypeFilterHeader.java @@ -10,14 +10,12 @@ package org.eclipse.hawkbit.ui.distributions.disttype; import javax.annotation.PostConstruct; -import org.eclipse.hawkbit.repository.SpPermissionChecker; import org.eclipse.hawkbit.ui.common.filterlayout.AbstractFilterHeader; import org.eclipse.hawkbit.ui.distributions.event.DistributionsUIEvent; import org.eclipse.hawkbit.ui.distributions.state.ManageDistUIState; import org.eclipse.hawkbit.ui.utils.SPUIDefinitions; import org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions; import org.springframework.beans.factory.annotation.Autowired; -import org.vaadin.spring.events.EventBus; import com.vaadin.spring.annotation.SpringComponent; import com.vaadin.spring.annotation.ViewScope; @@ -34,12 +32,6 @@ public class DSTypeFilterHeader extends AbstractFilterHeader { private static final long serialVersionUID = 3433417459392880222L; - @Autowired - private SpPermissionChecker permChecker; - - @Autowired - private transient EventBus.SessionEventBus eventbus; - @Autowired private ManageDistUIState manageDistUIState; @@ -81,8 +73,7 @@ public class DSTypeFilterHeader extends AbstractFilterHeader { @Override protected void hideFilterButtonLayout() { manageDistUIState.setDistTypeFilterClosed(true); - eventbus.publish(this, DistributionsUIEvent.HIDE_DIST_FILTER_BY_TYPE); - + eventBus.publish(this, DistributionsUIEvent.HIDE_DIST_FILTER_BY_TYPE); } @Override diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/dstable/DistributionSetDetails.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/dstable/DistributionSetDetails.java index d72fd971a..a1d1ffcfe 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/dstable/DistributionSetDetails.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/dstable/DistributionSetDetails.java @@ -13,19 +13,15 @@ import java.util.HashSet; import java.util.Map; import java.util.Set; -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; - import org.eclipse.hawkbit.repository.DistributionSetManagement; import org.eclipse.hawkbit.repository.SoftwareManagement; -import org.eclipse.hawkbit.repository.SpPermissionChecker; import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.DistributionSetIdName; import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.repository.model.SoftwareModuleIdName; import org.eclipse.hawkbit.ui.artifacts.event.SoftwareModuleEvent; import org.eclipse.hawkbit.ui.artifacts.event.SoftwareModuleEvent.SoftwareModuleEventType; -import org.eclipse.hawkbit.ui.common.detailslayout.AbstractTableDetailsLayout; +import org.eclipse.hawkbit.ui.common.detailslayout.AbstractNamedVersionedEntityTableDetailsLayout; import org.eclipse.hawkbit.ui.common.detailslayout.SoftwareModuleDetailsTable; import org.eclipse.hawkbit.ui.common.tagdetails.DistributionTagToken; import org.eclipse.hawkbit.ui.components.SPUIComponentProvider; @@ -35,12 +31,9 @@ import org.eclipse.hawkbit.ui.distributions.event.SoftwareModuleAssignmentDiscar import org.eclipse.hawkbit.ui.distributions.state.ManageDistUIState; import org.eclipse.hawkbit.ui.management.dstable.DistributionAddUpdateWindowLayout; import org.eclipse.hawkbit.ui.management.event.DistributionTableEvent; -import org.eclipse.hawkbit.ui.management.event.DistributionTableEvent.DistributionComponentEvent; import org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil; -import org.eclipse.hawkbit.ui.utils.I18N; import org.eclipse.hawkbit.ui.utils.SPUIComponetIdProvider; import org.springframework.beans.factory.annotation.Autowired; -import org.vaadin.spring.events.EventBus; import org.vaadin.spring.events.EventScope; import org.vaadin.spring.events.annotation.EventBusListenerMethod; @@ -64,7 +57,7 @@ import com.vaadin.ui.Window; */ @SpringComponent @ViewScope -public class DistributionSetDetails extends AbstractTableDetailsLayout { +public class DistributionSetDetails extends AbstractNamedVersionedEntityTableDetailsLayout { private static final long serialVersionUID = -4595004466943546669L; @@ -72,15 +65,6 @@ public class DistributionSetDetails extends AbstractTableDetailsLayout { private static final String UNASSIGN_SOFT_MODULE = "unassignSoftModule"; - @Autowired - private I18N i18n; - - @Autowired - private transient EventBus.SessionEventBus eventBus; - - @Autowired - private SpPermissionChecker permissionChecker; - @Autowired private ManageDistUIState manageDistUIState; @@ -100,25 +84,17 @@ public class DistributionSetDetails extends AbstractTableDetailsLayout { private VerticalLayout tagsLayout; - private DistributionSet selectedDsModule; - - private Long dsId; - - private UI ui; - Map assignedSWModule = new HashMap<>(); /** * softwareLayout Initialize the component. */ @Override - @PostConstruct protected void init() { softwareModuleTable = new SoftwareModuleDetailsTable(); - softwareModuleTable.init(i18n, true, permissionChecker, distributionSetManagement, eventBus, manageDistUIState); + softwareModuleTable.init(getI18n(), true, getPermissionChecker(), distributionSetManagement, getEventBus(), + manageDistUIState); super.init(); - ui = UI.getCurrent(); - eventBus.subscribe(this); } protected VerticalLayout createTagsLayout() { @@ -126,28 +102,15 @@ public class DistributionSetDetails extends AbstractTableDetailsLayout { return tagsLayout; } - private void populateDetailsWidget(final DistributionSet ds) { - if (ds != null) { - setDsId(ds.getId()); - setName(getDefaultCaption(), HawkbitCommonUtil.getFormattedNameVersion(ds.getName(), ds.getVersion())); - populateDetails(ds); - populateDescription(ds); - populateLog(ds); - populteModule(ds); - populateTags(ds); - } else { - setDsId(null); - setName(getDefaultCaption(), HawkbitCommonUtil.SP_STRING_EMPTY); - populateDetails(null); - populateDescription(null); - populteModule(null); - populateTags(null); - populateLog(null); - } + @Override + protected void populateDetailsWidget() { + populateDetails(); + populateModule(); + populateTags(); } - private void populteModule(final DistributionSet distributionSet) { - softwareModuleTable.populateModule(distributionSet); + private void populateModule() { + softwareModuleTable.populateModule(getSelectedBaseEntity()); showUnsavedAssignment(); } @@ -179,7 +142,7 @@ public class DistributionSetDetails extends AbstractTableDetailsLayout { assignedSWModule.put(softwareModule.getType().getName(), new StringBuilder().append("").append( getUnsavedAssigedSwModule(softwareModule.getName(), softwareModule.getVersion())) - .append("")); + .append("")); } } @@ -195,12 +158,8 @@ public class DistributionSetDetails extends AbstractTableDetailsLayout { } } - /** - * @param item - * @param entry - */ private void assignSoftModuleButton(final Item item, final Map.Entry entry) { - if (permissionChecker.hasUpdateDistributionPermission() && distributionSetManagement + if (getPermissionChecker().hasUpdateDistributionPermission() && distributionSetManagement .findDistributionSetById(manageDistUIState.getLastSelectedDistribution().get().getId()) .getAssignedTargets().isEmpty()) { final Button reassignSoftModule = SPUIComponentProvider.getButton(entry.getKey(), "", "", "", true, @@ -263,215 +222,108 @@ public class DistributionSetDetails extends AbstractTableDetailsLayout { return softwareLayout; } - private void populateTags(final DistributionSet ds) { + private void populateTags() { tagsLayout.removeAllComponents(); - if (null != ds) { - tagsLayout.addComponent(distributionTagToken.getTokenField()); + if (getSelectedBaseEntity() == null) { + return; } + tagsLayout.addComponent(distributionTagToken.getTokenField()); } - private void populateLog(final DistributionSet ds) { - if (null != ds) { - updateLogLayout(getLogLayout(), ds.getLastModifiedAt(), ds.getLastModifiedBy(), ds.getCreatedAt(), - ds.getCreatedBy(), i18n); - } else { - updateLogLayout(getLogLayout(), null, HawkbitCommonUtil.SP_STRING_EMPTY, null, null, i18n); - } - } - - private void populateDetails(final DistributionSet ds) { - if (ds != null) { - updateDistributionSetDetailsLayout(ds.getType().getName(), ds.isRequiredMigrationStep()); + private void populateDetails() { + if (getSelectedBaseEntity() != null) { + updateDistributionSetDetailsLayout(getSelectedBaseEntity().getType().getName(), + getSelectedBaseEntity().isRequiredMigrationStep()); } else { updateDistributionSetDetailsLayout(null, null); } } - private void populateDescription(final DistributionSet ds) { - if (ds != null) { - updateDescriptionLayout(i18n.get("label.description"), ds.getDescription()); - } else { - updateDescriptionLayout(i18n.get("label.description"), null); - } - } - private void updateDistributionSetDetailsLayout(final String type, final Boolean isMigrationRequired) { final VerticalLayout detailsTabLayout = getDetailsLayout(); detailsTabLayout.removeAllComponents(); if (type != null) { - final Label typeLabel = SPUIComponentProvider.createNameValueLabel(i18n.get("label.dist.details.type"), + final Label typeLabel = SPUIComponentProvider.createNameValueLabel(getI18n().get("label.dist.details.type"), type); typeLabel.setId(SPUIComponetIdProvider.DETAILS_TYPE_LABEL_ID); detailsTabLayout.addComponent(typeLabel); } if (isMigrationRequired != null) { - detailsTabLayout.addComponent( - SPUIComponentProvider.createNameValueLabel(i18n.get("checkbox.dist.migration.required"), - isMigrationRequired.equals(Boolean.TRUE) ? i18n.get("label.yes") : i18n.get("label.no"))); + detailsTabLayout.addComponent(SPUIComponentProvider.createNameValueLabel( + getI18n().get("checkbox.dist.migration.required"), + isMigrationRequired.equals(Boolean.TRUE) ? getI18n().get("label.yes") : getI18n().get("label.no"))); } } - public Long getDsId() { - return dsId; - } - - public void setDsId(final Long dsId) { - this.dsId = dsId; - } - - /* - * (non-Javadoc) - * - * @see hawkbit.server.ui.common.detailslayout.AbstractTableDetailsLayout# - * onEdit(com.vaadin.ui .Button.ClickEvent) - */ @Override protected void onEdit(final ClickEvent event) { final Window newDistWindow = distributionAddUpdateWindowLayout.getWindow(); - distributionAddUpdateWindowLayout.populateValuesOfDistribution(getDsId()); - newDistWindow.setCaption(i18n.get("caption.update.dist")); + distributionAddUpdateWindowLayout.populateValuesOfDistribution(getSelectedBaseEntityId()); + newDistWindow.setCaption(getI18n().get("caption.update.dist")); UI.getCurrent().addWindow(newDistWindow); newDistWindow.setVisible(Boolean.TRUE); } - /* - * (non-Javadoc) - * - * @see hawkbit.server.ui.common.detailslayout.AbstractTableDetailsLayout# - * getEditButtonId() - */ @Override protected String getEditButtonId() { return SPUIComponetIdProvider.DS_EDIT_BUTTON; } - /* - * (non-Javadoc) - * - * @see hawkbit.server.ui.common.detailslayout.AbstractTableDetailsLayout# - * onLoadIsSwModuleSelected () - */ @Override protected Boolean onLoadIsTableRowSelected() { return manageDistUIState.getSelectedDistributions().isPresent() && !manageDistUIState.getSelectedDistributions().get().isEmpty(); } - /* - * (non-Javadoc) - * - * @see hawkbit.server.ui.common.detailslayout.AbstractTableDetailsLayout# - * onLoadIsTableMaximized () - */ @Override protected Boolean onLoadIsTableMaximized() { return manageDistUIState.isDsTableMaximized(); } - /* - * (non-Javadoc) - * - * @see hawkbit.server.ui.common.detailslayout.AbstractTableDetailsLayout# - * populateDetailsWidget() - */ - @Override - protected void populateDetailsWidget() { - populateDetailsWidget(selectedDsModule); - } - - /* - * (non-Javadoc) - * - * @see hawkbit.server.ui.common.detailslayout.AbstractTableDetailsLayout# - * getDefaultCaption() - */ @Override protected String getDefaultCaption() { - return i18n.get("distribution.details.header"); + return getI18n().get("distribution.details.header"); } - /* - * (non-Javadoc) - * - * @see hawkbit.server.ui.common.detailslayout.AbstractTableDetailsLayout# - * addTabs(com.vaadin. ui.TabSheet) - */ @Override protected void addTabs(final TabSheet detailsTab) { - detailsTab.addTab(createDetailsLayout(), i18n.get("caption.tab.details"), null); - detailsTab.addTab(createDescriptionLayout(), i18n.get("caption.tab.description"), null); - detailsTab.addTab(createSoftwareModuleTab(), i18n.get("caption.softwares.distdetail.tab"), null); - detailsTab.addTab(createTagsLayout(), i18n.get("caption.tags.tab"), null); - detailsTab.addTab(createLogLayout(), i18n.get("caption.logs.tab"), null); + detailsTab.addTab(createDetailsLayout(), getI18n().get("caption.tab.details"), null); + detailsTab.addTab(createDescriptionLayout(), getI18n().get("caption.tab.description"), null); + detailsTab.addTab(createSoftwareModuleTab(), getI18n().get("caption.softwares.distdetail.tab"), null); + detailsTab.addTab(createTagsLayout(), getI18n().get("caption.tags.tab"), null); + detailsTab.addTab(createLogLayout(), getI18n().get("caption.logs.tab"), null); } - /* - * (non-Javadoc) - * - * @see hawkbit.server.ui.common.detailslayout.AbstractTableDetailsLayout# - * clearDetails() - */ - @Override - protected void clearDetails() { - populateDetailsWidget(null); - } - - /* - * (non-Javadoc) - * - * @see hawkbit.server.ui.common.detailslayout.AbstractTableDetailsLayout# - * hasEditSoftwareModulePermission() - */ @Override protected Boolean hasEditPermission() { - return permissionChecker.hasUpdateDistributionPermission(); + return getPermissionChecker().hasUpdateDistributionPermission(); } @EventBusListenerMethod(scope = EventScope.SESSION) void onEvent(final SoftwareModuleEvent event) { if (event.getSoftwareModuleEventType() == SoftwareModuleEventType.ASSIGN_SOFTWARE_MODULE) { - ui.access(() -> updateSoftwareModule(event.getSoftwareModule())); + UI.getCurrent().access(() -> updateSoftwareModule(event.getEntity())); } } @EventBusListenerMethod(scope = EventScope.SESSION) void onEvent(final DistributionTableEvent distributionTableEvent) { - if (distributionTableEvent.getDistributionComponentEvent() == DistributionComponentEvent.ON_VALUE_CHANGE - || distributionTableEvent - .getDistributionComponentEvent() == DistributionComponentEvent.EDIT_DISTRIBUTION) { - assignedSWModule.clear(); - ui.access(() -> { - /** - * distributionTableEvent.getDistributionSet() is null when - * table has no data. - */ - if (distributionTableEvent.getDistributionSet() != null) { - selectedDsModule = distributionTableEvent.getDistributionSet(); - populateData(true); - } else { - populateData(false); - } - }); - } else if (distributionTableEvent.getDistributionComponentEvent() == DistributionComponentEvent.MINIMIZED) { - ui.access(() -> showLayout()); - } else if (distributionTableEvent.getDistributionComponentEvent() == DistributionComponentEvent.MAXIMIZED) { - ui.access(() -> hideLayout()); - } + onBaseEntityEvent(distributionTableEvent); } @EventBusListenerMethod(scope = EventScope.SESSION) void onEvent(final SoftwareModuleAssignmentDiscardEvent softwareModuleAssignmentDiscardEvent) { if (softwareModuleAssignmentDiscardEvent.getDistributionSetIdName() != null) { - ui.access(() -> { + UI.getCurrent().access(() -> { final DistributionSetIdName distIdName = softwareModuleAssignmentDiscardEvent .getDistributionSetIdName(); - if (distIdName.getId().equals(selectedDsModule.getId()) - && distIdName.getName().equals(selectedDsModule.getName())) { - selectedDsModule = distributionSetManagement - .findDistributionSetByIdWithDetails(selectedDsModule.getId()); - populteModule(selectedDsModule); + if (distIdName.getId().equals(getSelectedBaseEntityId()) + && distIdName.getName().equals(getSelectedBaseEntity().getName())) { + setSelectedBaseEntity( + distributionSetManagement.findDistributionSetByIdWithDetails(getSelectedBaseEntityId())); + populateModule(); } }); } @@ -481,10 +333,11 @@ public class DistributionSetDetails extends AbstractTableDetailsLayout { void onEvent(final SaveActionWindowEvent saveActionWindowEvent) { if ((saveActionWindowEvent == SaveActionWindowEvent.SAVED_ASSIGNMENTS || saveActionWindowEvent == SaveActionWindowEvent.DISCARD_ALL_ASSIGNMENTS) - && selectedDsModule != null) { + && getSelectedBaseEntity() != null) { assignedSWModule.clear(); - selectedDsModule = distributionSetManagement.findDistributionSetByIdWithDetails(selectedDsModule.getId()); - ui.access(() -> populteModule(selectedDsModule)); + setSelectedBaseEntity( + distributionSetManagement.findDistributionSetByIdWithDetails(getSelectedBaseEntityId())); + UI.getCurrent().access(() -> populateModule()); } } @@ -498,21 +351,6 @@ public class DistributionSetDetails extends AbstractTableDetailsLayout { } } - @PreDestroy - void destroy() { - /* - * It's good to do this, even though vaadin-spring will automatically - * unsubscribe . - */ - eventBus.unsubscribe(this); - } - - /* - * (non-Javadoc) - * - * @see hawkbit.server.ui.common.detailslayout.AbstractTableDetailsLayout# - * getTabSheetId() - */ @Override protected String getTabSheetId() { return null; diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/dstable/DistributionSetTable.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/dstable/DistributionSetTable.java index 8d22f6782..01c242247 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/dstable/DistributionSetTable.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/dstable/DistributionSetTable.java @@ -12,15 +12,11 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; -import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; - import org.eclipse.hawkbit.repository.DistributionSetManagement; import org.eclipse.hawkbit.repository.SoftwareManagement; import org.eclipse.hawkbit.repository.SpPermissionChecker; @@ -32,23 +28,21 @@ import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.repository.model.SoftwareModuleIdName; import org.eclipse.hawkbit.ui.artifacts.event.SoftwareModuleEvent; import org.eclipse.hawkbit.ui.artifacts.event.SoftwareModuleEvent.SoftwareModuleEventType; +import org.eclipse.hawkbit.ui.common.table.AbstractNamedVersionTable; import org.eclipse.hawkbit.ui.common.table.AbstractTable; +import org.eclipse.hawkbit.ui.common.table.BaseEntityEventType; import org.eclipse.hawkbit.ui.distributions.event.DistributionsUIEvent; import org.eclipse.hawkbit.ui.distributions.event.DistributionsViewAcceptCriteria; import org.eclipse.hawkbit.ui.distributions.event.DragEvent; import org.eclipse.hawkbit.ui.distributions.event.SaveActionWindowEvent; import org.eclipse.hawkbit.ui.distributions.state.ManageDistUIState; import org.eclipse.hawkbit.ui.management.event.DistributionTableEvent; -import org.eclipse.hawkbit.ui.management.event.DistributionTableEvent.DistributionComponentEvent; import org.eclipse.hawkbit.ui.management.event.DistributionTableFilterEvent; import org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil; -import org.eclipse.hawkbit.ui.utils.I18N; -import org.eclipse.hawkbit.ui.utils.SPDateTimeUtil; import org.eclipse.hawkbit.ui.utils.SPUIComponetIdProvider; import org.eclipse.hawkbit.ui.utils.SPUIDefinitions; import org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions; import org.eclipse.hawkbit.ui.utils.SPUIStyleDefinitions; -import org.eclipse.hawkbit.ui.utils.TableColumn; import org.eclipse.hawkbit.ui.utils.UINotification; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -56,7 +50,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.vaadin.addons.lazyquerycontainer.BeanQueryFactory; import org.vaadin.addons.lazyquerycontainer.LazyQueryContainer; import org.vaadin.addons.lazyquerycontainer.LazyQueryDefinition; -import org.vaadin.spring.events.EventBus; import org.vaadin.spring.events.EventScope; import org.vaadin.spring.events.annotation.EventBusListenerMethod; @@ -77,7 +70,7 @@ import com.vaadin.ui.UI; */ @SpringComponent @ViewScope -public class DistributionSetTable extends AbstractTable { +public class DistributionSetTable extends AbstractNamedVersionTable { private static final long serialVersionUID = -7731776093470487988L; @@ -86,18 +79,12 @@ public class DistributionSetTable extends AbstractTable { private static final List DISPLAY_DROP_HINT_EVENTS = new ArrayList<>( Arrays.asList(DragEvent.SOFTWAREMODULE_DRAG)); - @Autowired - private I18N i18n; - @Autowired private SpPermissionChecker permissionChecker; @Autowired private ManageDistUIState manageDistUIState; - @Autowired - private transient EventBus.SessionEventBus eventBus; - @Autowired private transient DistributionSetManagement distributionSetManagement; @@ -117,12 +104,9 @@ public class DistributionSetTable extends AbstractTable { * Initialize the component. */ @Override - @PostConstruct protected void init() { super.init(); addTableStyleGenerator(); - setNoDataAvailable(); - eventBus.subscribe(this); } @EventBusListenerMethod(scope = EventScope.SESSION) @@ -171,13 +155,6 @@ public class DistributionSetTable extends AbstractTable { Boolean.class, null, false, true); } - @Override - protected void addCustomGeneratedColumns() { - /** - * No generated columns. - */ - } - @Override protected boolean isFirstRowSelectedOnLoad() { return !manageDistUIState.getSelectedDistributions().isPresent() @@ -193,37 +170,19 @@ public class DistributionSetTable extends AbstractTable { } @Override - protected void onValueChange() { - eventBus.publish(this, DragEvent.HIDE_DROP_HINT); - @SuppressWarnings("unchecked") - final Set values = (Set) getValue(); - DistributionSetIdName value = null; - if (values != null && !values.isEmpty()) { - final Iterator iterator = values.iterator(); + protected DistributionSet findEntityByTableValue(final DistributionSetIdName entityTableId) { + return distributionSetManagement.findDistributionSetByIdWithDetails(entityTableId.getId()); + } - while (iterator.hasNext()) { - value = iterator.next(); - } - /** - * Adding null check to make to avoid NPE.Its weird that at times - * getValue returns null. - */ - if (null != value) { - manageDistUIState.setSelectedDistributions(values); - manageDistUIState.setLastSelectedDistribution(value); + @Override + protected ManageDistUIState getManagmentEntityState() { + return manageDistUIState; + } - final DistributionSet lastSelectedDistSet = distributionSetManagement - .findDistributionSetByIdWithDetails(value.getId()); - eventBus.publish(this, - new DistributionTableEvent(DistributionComponentEvent.ON_VALUE_CHANGE, lastSelectedDistSet)); - } - } else { - manageDistUIState.setSelectedDistributions(null); - manageDistUIState.setLastSelectedDistribution(null); - eventBus.publish(this, new DistributionTableEvent(DistributionComponentEvent.ON_VALUE_CHANGE, null)); - } + @Override + protected void publishEntityAfterValueChange(final DistributionSet distributionSet) { + eventBus.publish(this, new DistributionTableEvent(BaseEntityEventType.SELECTED_ENTITY, distributionSet)); eventBus.publish(this, DistributionsUIEvent.ORDER_BY_DISTRIBUTION); - } @Override @@ -231,11 +190,6 @@ public class DistributionSetTable extends AbstractTable { return manageDistUIState.isDsTableMaximized(); } - @Override - protected List getTableVisibleColumns() { - return HawkbitCommonUtil.getTableVisibleColumns(isMaximized(), false, i18n); - } - @Override protected DropHandler getTableDropHandler() { return new DropHandler() { @@ -257,15 +211,9 @@ public class DistributionSetTable extends AbstractTable { private void onDrop(final DragAndDropEvent event) { final TableTransferable transferable = (TableTransferable) event.getTransferable(); - final Table source = transferable.getSourceComponent(); - final Set softwareModuleSelected = (Set) source.getValue(); - final Set softwareModulesIdList = new HashSet<>(); - - if (!softwareModuleSelected.contains(transferable.getData("itemId"))) { - softwareModulesIdList.add((Long) transferable.getData("itemId")); - } else { - softwareModulesIdList.addAll(softwareModuleSelected); - } + @SuppressWarnings("unchecked") + final AbstractTable source = (AbstractTable) transferable.getSourceComponent(); + final Set softwareModulesIdList = source.getDeletedEntityByTransferable(transferable); final AbstractSelectTargetDetails dropData = (AbstractSelectTargetDetails) event.getTargetDetails(); @@ -276,11 +224,6 @@ public class DistributionSetTable extends AbstractTable { } } - /** - * @param source - * @param softwareModulesIdList - * @param item - */ private void handleDropEvent(final Table source, final Set softwareModulesIdList, final Item item) { final Long distId = (Long) item.getItemProperty("id").getValue(); final String distName = (String) item.getItemProperty("name").getValue(); @@ -331,10 +274,6 @@ public class DistributionSetTable extends AbstractTable { updateDropedDetails(distributionSetIdName, softwareModules); } - /** - * @param distId - * @param softwareModule - */ private void publishAssignEvent(final Long distId, final SoftwareModule softwareModule) { if (manageDistUIState.getLastSelectedDistribution().isPresent() && manageDistUIState.getLastSelectedDistribution().get().getId().equals(distId)) { @@ -343,11 +282,6 @@ public class DistributionSetTable extends AbstractTable { } } - /** - * @param map - * @param softwareModule - * @param softwareModuleIdName - */ private void handleFirmwareCase(final Map> map, final SoftwareModule softwareModule, final SoftwareModuleIdName softwareModuleIdName) { if (softwareModule.getType().getMaxAssignments() == 1) { @@ -361,11 +295,6 @@ public class DistributionSetTable extends AbstractTable { } } - /** - * @param map - * @param softwareModule - * @param softwareModuleIdName - */ private void handleSoftwareCase(final Map> map, final SoftwareModule softwareModule, final SoftwareModuleIdName softwareModuleIdName) { if (softwareModule.getType().getMaxAssignments() == Integer.MAX_VALUE) { @@ -475,37 +404,6 @@ public class DistributionSetTable extends AbstractTable { return true; } - /** - * Add new software module to table. - * - * @param swModule - * new software module - */ - @SuppressWarnings("unchecked") - private void addDistributionSet(final DistributionSet distributionSet) { - final Object addItem = addItem(); - final Item item = getItem(addItem); - - item.getItemProperty(SPUILabelDefinitions.VAR_NAME).setValue(distributionSet.getName()); - item.getItemProperty(SPUILabelDefinitions.DIST_ID).setValue(distributionSet.getId()); - item.getItemProperty(SPUILabelDefinitions.VAR_ID).setValue(distributionSet.getId()); - item.getItemProperty(SPUILabelDefinitions.VAR_DESC).setValue(distributionSet.getDescription()); - item.getItemProperty(SPUILabelDefinitions.VAR_VERSION).setValue(distributionSet.getVersion()); - item.getItemProperty(SPUILabelDefinitions.VAR_CREATED_BY) - .setValue(HawkbitCommonUtil.getIMUser(distributionSet.getCreatedBy())); - item.getItemProperty(SPUILabelDefinitions.VAR_LAST_MODIFIED_BY) - .setValue(HawkbitCommonUtil.getIMUser(distributionSet.getLastModifiedBy())); - item.getItemProperty(SPUILabelDefinitions.VAR_CREATED_DATE) - .setValue(SPDateTimeUtil.getFormattedDate(distributionSet.getCreatedAt())); - item.getItemProperty(SPUILabelDefinitions.VAR_LAST_MODIFIED_DATE) - .setValue(SPDateTimeUtil.getFormattedDate(distributionSet.getLastModifiedAt())); - item.getItemProperty(SPUILabelDefinitions.VAR_IS_DISTRIBUTION_COMPLETE).setValue(distributionSet.isComplete()); - if (manageDistUIState.getSelectedDistributions().isPresent()) { - manageDistUIState.getSelectedDistributions().get().stream().forEach(dsNameId -> unselect(dsNameId)); - } - select(distributionSet.getDistributionSetIdName()); - } - private void addTableStyleGenerator() { setCellStyleGenerator((source, itemId, propertyId) -> { if (propertyId == null) { @@ -525,13 +423,7 @@ public class DistributionSetTable extends AbstractTable { @EventBusListenerMethod(scope = EventScope.SESSION) void onEvent(final DistributionTableEvent event) { - if (event.getDistributionComponentEvent() == DistributionComponentEvent.MINIMIZED) { - UI.getCurrent().access(() -> applyMinTableSettings()); - } else if (event.getDistributionComponentEvent() == DistributionComponentEvent.MAXIMIZED) { - UI.getCurrent().access(() -> applyMaxTableSettings()); - } else if (event.getDistributionComponentEvent() == DistributionComponentEvent.ADD_DISTRIBUTION) { - UI.getCurrent().access(() -> addDistributionSet(event.getDistributionSet())); - } + onBaseEntityEvent(event); } @EventBusListenerMethod(scope = EventScope.SESSION) @@ -556,21 +448,28 @@ public class DistributionSetTable extends AbstractTable { } } - @PreDestroy - void destroy() { - /* - * It's good manners to do this, even though vaadin-spring will - * automatically unsubscribe when this UI is garbage collected. - */ - eventBus.unsubscribe(this); + @Override + protected Item addEntity(final DistributionSet baseEntity) { + final Item item = super.addEntity(baseEntity); + if (manageDistUIState.getSelectedDistributions().isPresent()) { + manageDistUIState.getSelectedDistributions().get().stream().forEach(this::unselect); + } + select(baseEntity.getDistributionSetIdName()); + return item; } - private void setNoDataAvailable() { - final int containerSize = getContainerDataSource().size(); - if (containerSize == 0) { - manageDistUIState.setNoDataAvailableDist(true); - } else { - manageDistUIState.setNoDataAvailableDist(false); - } + @Override + @SuppressWarnings("unchecked") + protected void updateEntity(final DistributionSet baseEntity, final Item item) { + item.getItemProperty(SPUILabelDefinitions.DIST_ID).setValue(baseEntity.getId()); + item.getItemProperty(SPUILabelDefinitions.VAR_IS_DISTRIBUTION_COMPLETE).setValue(baseEntity.isComplete()); + super.updateEntity(baseEntity, item); } + + @Override + protected void setDataAvailable(final boolean available) { + manageDistUIState.setNoDataAvailableDist(!available); + + } + } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/dstable/DistributionSetTableHeader.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/dstable/DistributionSetTableHeader.java index f8cb7a45b..a42563505 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/dstable/DistributionSetTableHeader.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/dstable/DistributionSetTableHeader.java @@ -8,22 +8,16 @@ */ package org.eclipse.hawkbit.ui.distributions.dstable; -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; - -import org.eclipse.hawkbit.repository.SpPermissionChecker; import org.eclipse.hawkbit.ui.common.table.AbstractTableHeader; +import org.eclipse.hawkbit.ui.common.table.BaseEntityEventType; import org.eclipse.hawkbit.ui.distributions.event.DistributionsUIEvent; import org.eclipse.hawkbit.ui.distributions.event.DragEvent; import org.eclipse.hawkbit.ui.distributions.state.ManageDistUIState; import org.eclipse.hawkbit.ui.management.dstable.DistributionAddUpdateWindowLayout; import org.eclipse.hawkbit.ui.management.event.DistributionTableEvent; -import org.eclipse.hawkbit.ui.management.event.DistributionTableEvent.DistributionComponentEvent; import org.eclipse.hawkbit.ui.management.event.DistributionTableFilterEvent; -import org.eclipse.hawkbit.ui.utils.I18N; import org.eclipse.hawkbit.ui.utils.SPUIComponetIdProvider; import org.springframework.beans.factory.annotation.Autowired; -import org.vaadin.spring.events.EventBus; import org.vaadin.spring.events.EventScope; import org.vaadin.spring.events.annotation.EventBusListenerMethod; @@ -43,28 +37,12 @@ public class DistributionSetTableHeader extends AbstractTableHeader { private static final long serialVersionUID = -3483238438474530748L; - @Autowired - private I18N i18n; - - @Autowired - private SpPermissionChecker permChecker; - - @Autowired - private transient EventBus.SessionEventBus eventbus; - @Autowired private ManageDistUIState manageDistUIstate; @Autowired private DistributionAddUpdateWindowLayout addUpdateWindowLayout; - @Override - @PostConstruct - protected void init() { - super.init(); - eventbus.subscribe(this); - } - @EventBusListenerMethod(scope = EventScope.SESSION) void onEvent(final DistributionsUIEvent event) { if (event == DistributionsUIEvent.HIDE_DIST_FILTER_BY_TYPE) { @@ -147,13 +125,13 @@ public class DistributionSetTableHeader extends AbstractTableHeader { @Override public void maximizeTable() { manageDistUIstate.setDsTableMaximized(Boolean.TRUE); - eventbus.publish(this, new DistributionTableEvent(DistributionComponentEvent.MAXIMIZED, null)); + eventbus.publish(this, new DistributionTableEvent(BaseEntityEventType.MAXIMIZED, null)); } @Override public void minimizeTable() { manageDistUIstate.setDsTableMaximized(Boolean.FALSE); - eventbus.publish(this, new DistributionTableEvent(DistributionComponentEvent.MINIMIZED, null)); + eventbus.publish(this, new DistributionTableEvent(BaseEntityEventType.MINIMIZED, null)); } @Override @@ -181,11 +159,6 @@ public class DistributionSetTableHeader extends AbstractTableHeader { eventbus.publish(this, DragEvent.HIDE_DROP_HINT); } - @PreDestroy - void destroy() { - eventbus.unsubscribe(this); - } - @Override protected Boolean isAddNewItemAllowed() { return Boolean.TRUE; diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/dstable/ManageDistBeanQuery.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/dstable/ManageDistBeanQuery.java index 60b547285..78410f29c 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/dstable/ManageDistBeanQuery.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/dstable/ManageDistBeanQuery.java @@ -20,6 +20,7 @@ import org.eclipse.hawkbit.repository.DistributionSetManagement; import org.eclipse.hawkbit.repository.OffsetBasedPageRequest; import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.DistributionSetType; +import org.eclipse.hawkbit.ui.common.UserDetailsFormatter; import org.eclipse.hawkbit.ui.components.ProxyDistribution; import org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil; import org.eclipse.hawkbit.ui.utils.SPDateTimeUtil; @@ -113,8 +114,8 @@ public class ManageDistBeanQuery extends AbstractBeanQuery { proxyDistribution.setCreatedDate(SPDateTimeUtil.getFormattedDate(distributionSet.getCreatedAt())); proxyDistribution.setLastModifiedDate(SPDateTimeUtil.getFormattedDate(distributionSet.getLastModifiedAt())); proxyDistribution.setDescription(distributionSet.getDescription()); - proxyDistribution.setCreatedByUser(HawkbitCommonUtil.getIMUser(distributionSet.getCreatedBy())); - proxyDistribution.setModifiedByUser(HawkbitCommonUtil.getIMUser(distributionSet.getLastModifiedBy())); + proxyDistribution.setCreatedByUser(UserDetailsFormatter.loadAndFormatCreatedBy(distributionSet)); + proxyDistribution.setModifiedByUser(UserDetailsFormatter.loadAndFormatLastModifiedBy(distributionSet)); proxyDistribution.setIsComplete(distributionSet.isComplete()); proxyDistributions.add(proxyDistribution); } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/event/DistributionsViewAcceptCriteria.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/event/DistributionsViewAcceptCriteria.java index 5b79b96f4..140fb41da 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/event/DistributionsViewAcceptCriteria.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/event/DistributionsViewAcceptCriteria.java @@ -16,10 +16,6 @@ import java.util.Map; import org.eclipse.hawkbit.ui.common.AbstractAcceptCriteria; import org.eclipse.hawkbit.ui.utils.SPUIComponetIdProvider; import org.eclipse.hawkbit.ui.utils.SPUIDefinitions; -import org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions; -import org.eclipse.hawkbit.ui.utils.UINotification; -import org.springframework.beans.factory.annotation.Autowired; -import org.vaadin.spring.events.EventBus; import com.vaadin.spring.annotation.SpringComponent; import com.vaadin.spring.annotation.ViewScope; @@ -39,29 +35,6 @@ public class DistributionsViewAcceptCriteria extends AbstractAcceptCriteria { private static final Map> DROP_CONFIGS = createDropConfigurations(); - @Autowired - private transient UINotification uiNotification; - - @Autowired - private transient EventBus.SessionEventBus eventBus; - - @Override - protected void analyseDragComponent(final Component compsource) { - final String sourceID = getComponentId(compsource); - final Object event = DROP_HINTS_CONFIGS.get(sourceID); - eventBus.publish(this, event); - } - - @Override - protected void hideDropHints() { - eventBus.publish(this, DragEvent.HIDE_DROP_HINT); - } - - @Override - protected void invalidDrop() { - uiNotification.displayValidationError(SPUILabelDefinitions.ACTION_NOT_ALLOWED); - } - @Override protected String getComponentId(final Component component) { String id = component.getId(); @@ -78,11 +51,6 @@ public class DistributionsViewAcceptCriteria extends AbstractAcceptCriteria { return DROP_HINTS_CONFIGS; } - @Override - protected void publishDragStartEvent(final Object event) { - eventBus.publish(this, event); - } - @Override protected Map> getDropConfigurations() { return DROP_CONFIGS; diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/footer/DSDeleteActionsLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/footer/DSDeleteActionsLayout.java index 5b51bb224..5bc1627a9 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/footer/DSDeleteActionsLayout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/footer/DSDeleteActionsLayout.java @@ -15,28 +15,22 @@ import java.util.List; import java.util.Map.Entry; import java.util.Set; -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; - -import org.eclipse.hawkbit.repository.SpPermissionChecker; import org.eclipse.hawkbit.repository.SystemManagement; import org.eclipse.hawkbit.repository.model.DistributionSetIdName; import org.eclipse.hawkbit.repository.model.DistributionSetType; import org.eclipse.hawkbit.repository.model.SoftwareModuleIdName; import org.eclipse.hawkbit.ui.common.footer.AbstractDeleteActionsLayout; +import org.eclipse.hawkbit.ui.common.table.AbstractTable; import org.eclipse.hawkbit.ui.distributions.event.DistributionsUIEvent; import org.eclipse.hawkbit.ui.distributions.event.DistributionsViewAcceptCriteria; import org.eclipse.hawkbit.ui.distributions.event.DragEvent; import org.eclipse.hawkbit.ui.distributions.event.SaveActionWindowEvent; import org.eclipse.hawkbit.ui.distributions.state.ManageDistUIState; import org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil; -import org.eclipse.hawkbit.ui.utils.I18N; import org.eclipse.hawkbit.ui.utils.SPUIComponetIdProvider; import org.eclipse.hawkbit.ui.utils.SPUIDefinitions; import org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions; -import org.eclipse.hawkbit.ui.utils.UINotification; import org.springframework.beans.factory.annotation.Autowired; -import org.vaadin.spring.events.EventBus; import org.vaadin.spring.events.EventScope; import org.vaadin.spring.events.annotation.EventBusListenerMethod; @@ -44,7 +38,6 @@ import com.vaadin.event.dd.DragAndDropEvent; import com.vaadin.event.dd.acceptcriteria.AcceptCriterion; import com.vaadin.spring.annotation.ViewScope; import com.vaadin.ui.Component; -import com.vaadin.ui.Label; import com.vaadin.ui.Table; import com.vaadin.ui.Table.TableTransferable; import com.vaadin.ui.UI; @@ -65,21 +58,6 @@ public class DSDeleteActionsLayout extends AbstractDeleteActionsLayout { Arrays.asList(DragEvent.DISTRIBUTION_TYPE_DRAG, DragEvent.DISTRIBUTION_DRAG, DragEvent.SOFTWAREMODULE_DRAG, DragEvent.SOFTWAREMODULE_TYPE_DRAG)); - @Autowired - private I18N i18n; - - @Autowired - private SpPermissionChecker permChecker; - - @Autowired - private transient EventBus.SessionEventBus eventBus; - - @Autowired - private transient UINotification notification; - - @Autowired - private transient UINotification uiNotification; - @Autowired private transient SystemManagement systemManagement; @@ -92,28 +70,6 @@ public class DSDeleteActionsLayout extends AbstractDeleteActionsLayout { @Autowired private DistributionsViewAcceptCriteria distributionsViewAcceptCriteria; - /* - * (non-Javadoc) - * - * @see - * org.eclipse.hawkbit.server.ui.common.footer.DeleteActionsLayout#init() - */ - @Override - @PostConstruct - protected void init() { - super.init(); - eventBus.subscribe(this); - } - - @PreDestroy - void destroy() { - /* - * It's good manners to do this, even though vaadin-spring will - * automatically unsubscribe when this UI is garbage collected. - */ - eventBus.unsubscribe(this); - } - @EventBusListenerMethod(scope = EventScope.SESSION) void onEvent(final DragEvent event) { if (event == DragEvent.HIDE_DROP_HINT) { @@ -139,77 +95,34 @@ public class DSDeleteActionsLayout extends AbstractDeleteActionsLayout { } } - /* - * (non-Javadoc) - * - * @see - * org.eclipse.hawkbit.server.ui.common.footer.AbstractDeleteActionsLayout# - * hasDeletePermission() - */ @Override protected boolean hasDeletePermission() { return permChecker.hasDeleteDistributionPermission(); } - /* - * (non-Javadoc) - * - * @see - * org.eclipse.hawkbit.server.ui.common.footer.AbstractDeleteActionsLayout# - * hasUpdatePermission() - */ @Override protected boolean hasUpdatePermission() { return permChecker.hasUpdateDistributionPermission(); } - /* - * (non-Javadoc) - * - * @see - * org.eclipse.hawkbit.server.ui.common.footer.AbstractDeleteActionsLayout# - * getDeleteAreaLabel() - */ @Override protected String getDeleteAreaLabel() { return i18n.get("label.components.drop.area"); } - /* - * (non-Javadoc) - * - * @see - * org.eclipse.hawkbit.server.ui.common.footer.AbstractDeleteActionsLayout# - * getDeleteAreaId() - */ @Override protected String getDeleteAreaId() { return SPUIComponetIdProvider.DELETE_BUTTON_WRAPPER_ID; } - /* - * (non-Javadoc) - * - * @see - * org.eclipse.hawkbit.server.ui.common.footer.AbstractDeleteActionsLayout# - * getDeleteLayoutAcceptCriteria () - */ @Override protected AcceptCriterion getDeleteLayoutAcceptCriteria() { - return distributionsViewAcceptCriteria; } - /* - * (non-Javadoc) - * - * @see - * org.eclipse.hawkbit.server.ui.common.footer.AbstractDeleteActionsLayout# - * processDroppedComponent(com .vaadin.event.dd.DragAndDropEvent) - */ @Override protected void processDroppedComponent(final DragAndDropEvent event) { final Component sourceComponent = event.getTransferable().getSourceComponent(); @@ -276,13 +189,8 @@ public class DSDeleteActionsLayout extends AbstractDeleteActionsLayout { private void addInDeleteDistributionList(final Table sourceTable, final TableTransferable transferable) { @SuppressWarnings("unchecked") - final Set distSelected = (Set) sourceTable.getValue(); - final Set distributionIdNameSet = new HashSet<>(); - if (!distSelected.contains(transferable.getData(SPUIDefinitions.ITEMID))) { - distributionIdNameSet.add((DistributionSetIdName) transferable.getData(SPUIDefinitions.ITEMID)); - } else { - distributionIdNameSet.addAll(distSelected); - } + final AbstractTable table = (AbstractTable) sourceTable; + final Set distributionIdNameSet = table.getDeletedEntityByTransferable(transferable); /* * Flags to identify whether all dropped distributions are already in * the deleted list (or) some distributions are already in the deleted @@ -298,7 +206,7 @@ public class DSDeleteActionsLayout extends AbstractDeleteActionsLayout { * message accordingly. */ - uiNotification.displayValidationError(i18n.get("message.targets.already.deleted")); + notification.displayValidationError(i18n.get("message.targets.already.deleted")); } else if (newDeletedDistributionsSize - existingDeletedDistributionsSize != distributionIdNameSet.size()) { /* * Not the all distributions dropped now are added to the delete @@ -306,21 +214,16 @@ public class DSDeleteActionsLayout extends AbstractDeleteActionsLayout { * delete list. Hence display warning message accordingly. */ - uiNotification.displayValidationError(i18n.get("message.dist.deleted.pending")); + notification.displayValidationError(i18n.get("message.dist.deleted.pending")); } } private void addToSWDeleteList(final Table sourceTable, final TableTransferable transferable) { - @SuppressWarnings("unchecked") - final Set swModuleSelected = (Set) sourceTable.getValue(); - final Set swModuleIdNameSet = new HashSet<>(); - if (!swModuleSelected.contains(transferable.getData(SPUIDefinitions.ITEMID))) { - swModuleIdNameSet.add((Long) transferable.getData(SPUIDefinitions.ITEMID)); - } else { - swModuleIdNameSet.addAll(swModuleSelected); - } + final AbstractTable swTable = (AbstractTable) sourceTable; + final Set swModuleIdNameSet = swTable.getDeletedEntityByTransferable(transferable); + swModuleIdNameSet.forEach(id -> { final String swModuleName = (String) sourceTable.getContainerDataSource().getItem(id) .getItemProperty(SPUILabelDefinitions.NAME_VERSION).getValue(); @@ -366,64 +269,12 @@ public class DSDeleteActionsLayout extends AbstractDeleteActionsLayout { return SPUIComponetIdProvider.UPLOAD_SOFTWARE_MODULE_TABLE.equals(source.getId()); } - /* - * (non-Javadoc) - * - * @see - * org.eclipse.hawkbit.server.ui.common.footer.AbstractDeleteActionsLayout# - * getNoActionsButtonLabel() - */ - @Override - protected String getNoActionsButtonLabel() { - return i18n.get("button.no.actions"); - } - - /* - * (non-Javadoc) - * - * @see - * org.eclipse.hawkbit.server.ui.common.footer.AbstractDeleteActionsLayout# - * getActionsButtonLabel() - */ - @Override - protected String getActionsButtonLabel() { - - return i18n.get("button.actions"); - - } - - /* - * (non-Javadoc) - * - * @see - * org.eclipse.hawkbit.server.ui.common.footer.AbstractDeleteActionsLayout# - * reloadActionCount() - */ @Override protected void restoreActionCount() { updateDSActionCount(); } - /* - * (non-Javadoc) - * - * @see - * org.eclipse.hawkbit.server.ui.common.footer.AbstractDeleteActionsLayout# - * getUnsavedActionsWindowCaption () - */ - @Override - protected String getUnsavedActionsWindowCaption() { - return i18n.get("caption.save.window"); - } - - /* - * (non-Javadoc) - * - * @see - * org.eclipse.hawkbit.server.ui.common.footer.AbstractDeleteActionsLayout# - * unsavedActionsWindowClosed() - */ @Override protected void unsavedActionsWindowClosed() { final String message = distConfirmationWindowLayout.getConsolidatedMessage(); @@ -433,26 +284,12 @@ public class DSDeleteActionsLayout extends AbstractDeleteActionsLayout { } - /* - * (non-Javadoc) - * - * @see - * org.eclipse.hawkbit.server.ui.common.footer.AbstractDeleteActionsLayout# - * getUnsavedActionsWindowContent () - */ @Override protected Component getUnsavedActionsWindowContent() { - distConfirmationWindowLayout.init(); + distConfirmationWindowLayout.initialize(); return distConfirmationWindowLayout; } - /* - * (non-Javadoc) - * - * @see - * org.eclipse.hawkbit.server.ui.common.footer.AbstractDeleteActionsLayout# - * hasUnsavedActions() - */ @Override protected boolean hasUnsavedActions() { boolean unSavedActionsTypes = false; @@ -469,53 +306,6 @@ public class DSDeleteActionsLayout extends AbstractDeleteActionsLayout { return unSavedActionsTables || unSavedActionsTypes; } - @Override - protected boolean hasCountMessage() { - return false; - } - - @Override - protected Label getCountMessageLabel() { - return null; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.hawkbit.ui.common.footer.AbstractDeleteActionsLayout# - * hasBulkUploadPermission() - */ - @Override - protected boolean hasBulkUploadPermission() { - return false; - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.hawkbit.ui.common.footer.AbstractDeleteActionsLayout# - * showBulkUploadWindow() - */ - @Override - protected void showBulkUploadWindow() { - /** - * Bulk upload not supported No implementation required. - */ - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.hawkbit.ui.common.footer.AbstractDeleteActionsLayout# - * restoreBulkUploadStatusCount() - */ - @Override - protected void restoreBulkUploadStatusCount() { - /** - * No implementation required.As no bulk upload in Distribution view. - */ - } - private DistributionSetType getCurrentDistributionSetType() { return systemManagement.getTenantMetadata().getDefaultDsType(); } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/footer/DistributionsConfirmationWindowLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/footer/DistributionsConfirmationWindowLayout.java index 2299054f3..a97c5786d 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/footer/DistributionsConfirmationWindowLayout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/footer/DistributionsConfirmationWindowLayout.java @@ -8,7 +8,6 @@ */ package org.eclipse.hawkbit.ui.distributions.footer; -import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; @@ -17,8 +16,6 @@ import java.util.Map.Entry; import java.util.Set; import java.util.stream.Collectors; -import javax.annotation.PostConstruct; - import org.eclipse.hawkbit.repository.DistributionSetManagement; import org.eclipse.hawkbit.repository.SoftwareManagement; import org.eclipse.hawkbit.repository.model.DistributionSet; @@ -32,13 +29,11 @@ import org.eclipse.hawkbit.ui.decorators.SPUIButtonStyleSmallNoBorder; import org.eclipse.hawkbit.ui.distributions.event.SaveActionWindowEvent; import org.eclipse.hawkbit.ui.distributions.state.ManageDistUIState; import org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil; -import org.eclipse.hawkbit.ui.utils.I18N; import org.eclipse.hawkbit.ui.utils.SPUIComponetIdProvider; import org.eclipse.hawkbit.ui.utils.SPUIDefinitions; import org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions; import org.eclipse.hawkbit.ui.utils.SPUIStyleDefinitions; import org.springframework.beans.factory.annotation.Autowired; -import org.vaadin.spring.events.EventBus; import org.vaadin.spring.events.EventScope; import org.vaadin.spring.events.annotation.EventBusListenerMethod; @@ -48,6 +43,7 @@ import com.vaadin.data.util.IndexedContainer; import com.vaadin.server.FontAwesome; import com.vaadin.spring.annotation.ViewScope; import com.vaadin.ui.Button; +import com.vaadin.ui.Button.ClickListener; import com.vaadin.ui.Table.Align; import com.vaadin.ui.themes.ValoTheme; @@ -83,12 +79,6 @@ public class DistributionsConfirmationWindowLayout extends AbstractConfirmationW private ConfirmationTab assignmnetTab; - @Autowired - private I18N i18n; - - @Autowired - private transient EventBus.SessionEventBus eventBus; - @Autowired private transient DistributionSetManagement dsManagement; @@ -98,20 +88,6 @@ public class DistributionsConfirmationWindowLayout extends AbstractConfirmationW @Autowired private ManageDistUIState manageDistUIState; - /** - * Initialze the component. - */ - @PostConstruct - public void init() { - super.inittialize(); - } - - /* - * (non-Javadoc) - * - * @see org.eclipse.hawkbit.server.ui.common.confirmwindow.layout. - * AbstractConfirmationWindowLayout# getConfimrationTabs() - */ @Override protected Map getConfimrationTabs() { final Map tabs = new HashMap<>(); @@ -161,26 +137,13 @@ public class DistributionsConfirmationWindowLayout extends AbstractConfirmationW /* Add the discard action column */ tab.getTable().addGeneratedColumn(SW_DISCARD_CHGS, (source, itemId, columnId) -> { - final Button deleteswIcon = SPUIComponentProvider.getButton("", "", SPUILabelDefinitions.DISCARD, - ValoTheme.BUTTON_TINY + " " + SPUIStyleDefinitions.REDICON, true, FontAwesome.REPLY, - SPUIButtonStyleSmallNoBorder.class); - deleteswIcon.setData(itemId); - deleteswIcon.setImmediate(true); - deleteswIcon.addClickListener(event -> discardSoftwareDelete(event, itemId, tab)); - return deleteswIcon; + final ClickListener clickListener = event -> discardSoftwareDelete(event, itemId, tab); + return createDiscardButton(itemId, clickListener); }); - /* set the visible columns */ - final List visibleColumnIds = new ArrayList<>(); - final List visibleColumnLabels = new ArrayList<>(); - if (visibleColumnIds.isEmpty() && visibleColumnLabels.isEmpty()) { - visibleColumnIds.add(SW_MODULE_NAME_MSG); - visibleColumnIds.add(SW_DISCARD_CHGS); - visibleColumnLabels.add(i18n.get("upload.swModuleTable.header")); - visibleColumnLabels.add(i18n.get("header.second.deletetarget.table")); - } - tab.getTable().setVisibleColumns(visibleColumnIds.toArray()); - tab.getTable().setColumnHeaders(visibleColumnLabels.toArray(new String[0])); + tab.getTable().setVisibleColumns(SW_MODULE_NAME_MSG, SW_DISCARD_CHGS); + tab.getTable().setColumnHeaders(i18n.get("upload.swModuleTable.header"), + i18n.get("header.second.deletetarget.table")); tab.getTable().setColumnExpandRatio(SW_MODULE_NAME_MSG, SPUIDefinitions.TARGET_DISTRIBUTION_COLUMN_WIDTH); tab.getTable().setColumnExpandRatio(SW_DISCARD_CHGS, SPUIDefinitions.DISCARD_COLUMN_WIDTH); @@ -295,18 +258,9 @@ public class DistributionsConfirmationWindowLayout extends AbstractConfirmationW return deleteIcon; }); - // set the visible columns - final List visibleColumnIds = new ArrayList<>(); - final List visibleColumnLabels = new ArrayList<>(); - if (visibleColumnIds.isEmpty() && visibleColumnLabels.isEmpty()) { - visibleColumnIds.add(SW_MODULE_TYPE_NAME); - visibleColumnIds.add(DISCARD); - visibleColumnLabels.add(i18n.get("header.first.delete.swmodule.type.table")); - visibleColumnLabels.add(i18n.get("header.second.delete.swmodule.type.table")); - - } - tab.getTable().setVisibleColumns(visibleColumnIds.toArray()); - tab.getTable().setColumnHeaders(visibleColumnLabels.toArray(new String[0])); + tab.getTable().setVisibleColumns(SW_MODULE_TYPE_NAME, DISCARD); + tab.getTable().setColumnHeaders(i18n.get("header.first.delete.swmodule.type.table"), + i18n.get("header.second.delete.swmodule.type.table")); tab.getTable().setColumnExpandRatio(SW_MODULE_TYPE_NAME, 2); tab.getTable().setColumnExpandRatio(SW_DISCARD_CHGS, SPUIDefinitions.DISCARD_COLUMN_WIDTH); @@ -383,26 +337,14 @@ public class DistributionsConfirmationWindowLayout extends AbstractConfirmationW /* Add the discard action column */ tab.getTable().addGeneratedColumn(DISCARD, (source, itemId, columnId) -> { - final Button deleteswIcon = SPUIComponentProvider.getButton("", "", SPUILabelDefinitions.DISCARD, - ValoTheme.BUTTON_TINY + " " + SPUIStyleDefinitions.REDICON, true, FontAwesome.REPLY, - SPUIButtonStyleSmallNoBorder.class); - deleteswIcon.setData(itemId); - deleteswIcon.setImmediate(true); - deleteswIcon.addClickListener(event -> discardDistDelete(event, itemId, tab)); - return deleteswIcon; + final ClickListener clickListener = event -> discardDistDelete(event, itemId, tab); + return createDiscardButton(itemId, clickListener); + }); - /* set the visible columns */ - final List visibleColumnIds = new ArrayList<>(); - final List visibleColumnLabels = new ArrayList<>(); - if (visibleColumnIds.isEmpty() && visibleColumnLabels.isEmpty()) { - visibleColumnIds.add(DIST_NAME); - visibleColumnIds.add(DISCARD); - visibleColumnLabels.add(i18n.get("header.one.deletedist.table")); - visibleColumnLabels.add(i18n.get("header.second.deletedist.table")); - } - tab.getTable().setVisibleColumns(visibleColumnIds.toArray()); - tab.getTable().setColumnHeaders(visibleColumnLabels.toArray(new String[0])); + tab.getTable().setVisibleColumns(DIST_NAME, DISCARD); + tab.getTable().setColumnHeaders(i18n.get("header.one.deletedist.table"), + i18n.get("header.second.deletedist.table")); tab.getTable().setColumnExpandRatio(DIST_NAME, SPUIDefinitions.TARGET_DISTRIBUTION_COLUMN_WIDTH); tab.getTable().setColumnExpandRatio(DISCARD, SPUIDefinitions.DISCARD_COLUMN_WIDTH); @@ -495,30 +437,15 @@ public class DistributionsConfirmationWindowLayout extends AbstractConfirmationW // Add the discard action column tab.getTable().addGeneratedColumn(DISCARD, (source, itemId, columnId) -> { - final StringBuilder style = new StringBuilder(ValoTheme.BUTTON_TINY); - style.append(' '); - style.append(SPUIStyleDefinitions.REDICON); - final Button deleteIcon = SPUIComponentProvider.getButton("", "", SPUILabelDefinitions.DISCARD, - style.toString(), true, FontAwesome.REPLY, SPUIButtonStyleSmallNoBorder.class); - deleteIcon.setData(itemId); - deleteIcon.setImmediate(true); - deleteIcon.addClickListener( - event -> discardDistTypeDelete((String) ((Button) event.getComponent()).getData(), itemId, tab)); - return deleteIcon; + final ClickListener clickListener = event -> discardDistTypeDelete( + (String) ((Button) event.getComponent()).getData(), itemId, tab); + return createDiscardButton(itemId, clickListener); + }); - // set the visible columns - final List visibleColumnIds = new ArrayList<>(); - final List visibleColumnLabels = new ArrayList<>(); - if (visibleColumnIds.isEmpty() && visibleColumnLabels.isEmpty()) { - visibleColumnIds.add(DIST_SET_NAME); - visibleColumnIds.add(DISCARD); - visibleColumnLabels.add(i18n.get("header.first.delete.dist.type.table")); - visibleColumnLabels.add(i18n.get("header.second.delete.dist.type.table")); - - } - tab.getTable().setVisibleColumns(visibleColumnIds.toArray()); - tab.getTable().setColumnHeaders(visibleColumnLabels.toArray(new String[0])); + tab.getTable().setVisibleColumns(DIST_SET_NAME, DISCARD); + tab.getTable().setColumnHeaders(i18n.get("header.first.delete.dist.type.table"), + i18n.get("header.second.delete.dist.type.table")); tab.getTable().setColumnExpandRatio(DIST_SET_NAME, 2); tab.getTable().setColumnExpandRatio(DISCARD, SPUIDefinitions.DISCARD_COLUMN_WIDTH); @@ -610,20 +537,9 @@ public class DistributionsConfirmationWindowLayout extends AbstractConfirmationW return deleteIcon; }); - // set the visible columns - final List visibleColumnIds = new ArrayList<>(); - final List visibleColumnLabels = new ArrayList<>(); - if (visibleColumnIds.isEmpty() && visibleColumnLabels.isEmpty()) { - visibleColumnIds.add(DIST_NAME); - visibleColumnIds.add(SOFTWARE_MODULE_NAME); - visibleColumnIds.add(DISCARD); - visibleColumnLabels.add(i18n.get("header.dist.first.assignment.table")); - visibleColumnLabels.add(i18n.get("header.dist.second.assignment.table")); - visibleColumnLabels.add(i18n.get("header.third.assignment.table")); - - } - assignmnetTab.getTable().setVisibleColumns(visibleColumnIds.toArray()); - assignmnetTab.getTable().setColumnHeaders(visibleColumnLabels.toArray(new String[0])); + assignmnetTab.getTable().setVisibleColumns(DIST_NAME, SOFTWARE_MODULE_NAME, DISCARD); + assignmnetTab.getTable().setColumnHeaders(i18n.get("header.dist.first.assignment.table"), + i18n.get("header.dist.second.assignment.table"), i18n.get("header.third.assignment.table")); assignmnetTab.getTable().setColumnExpandRatio(DIST_NAME, 2); assignmnetTab.getTable().setColumnExpandRatio(SOFTWARE_MODULE_NAME, 2); diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/smtable/SwModuleBeanQuery.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/smtable/SwModuleBeanQuery.java index 859febbce..21ce01347 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/smtable/SwModuleBeanQuery.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/smtable/SwModuleBeanQuery.java @@ -17,13 +17,12 @@ import org.eclipse.hawkbit.repository.SoftwareManagement; import org.eclipse.hawkbit.repository.model.CustomSoftwareModule; import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.repository.model.SoftwareModuleType; +import org.eclipse.hawkbit.ui.common.UserDetailsFormatter; import org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil; import org.eclipse.hawkbit.ui.utils.SPDateTimeUtil; import org.eclipse.hawkbit.ui.utils.SPUIDefinitions; import org.eclipse.hawkbit.ui.utils.SpringContextHelper; import org.springframework.data.domain.Slice; -import org.springframework.data.domain.Sort; -import org.springframework.data.domain.Sort.Direction; import org.vaadin.addons.lazyquerycontainer.AbstractBeanQuery; import org.vaadin.addons.lazyquerycontainer.QueryDefinition; @@ -79,9 +78,8 @@ public class SwModuleBeanQuery extends AbstractBeanQuery final Slice swModuleBeans; final List proxyBeans = new ArrayList<>(); - swModuleBeans = getSoftwareManagement().findSoftwareModuleOrderByDistribution( - new OffsetBasedPageRequest(startIndex, count, new Sort(Direction.ASC, "name", "version")), - orderByDistId, searchText, type); + swModuleBeans = getSoftwareManagement().findSoftwareModuleOrderBySetAssignmentAndModuleNameAscModuleVersionAsc( + new OffsetBasedPageRequest(startIndex, count), orderByDistId, searchText, type); for (final CustomSoftwareModule swModule : swModuleBeans) { proxyBeans.add(getProxyBean(swModule)); @@ -102,8 +100,8 @@ public class SwModuleBeanQuery extends AbstractBeanQuery proxyItem.setVersion(bean.getVersion()); proxyItem.setVendor(bean.getVendor()); proxyItem.setDescription(bean.getDescription()); - proxyItem.setCreatedByUser(HawkbitCommonUtil.getIMUser(bean.getCreatedBy())); - proxyItem.setModifiedByUser(HawkbitCommonUtil.getIMUser(bean.getLastModifiedBy())); + proxyItem.setCreatedByUser(UserDetailsFormatter.loadAndFormatCreatedBy(bean)); + proxyItem.setModifiedByUser(UserDetailsFormatter.loadAndFormatLastModifiedBy(bean)); proxyItem.setAssigned(customSoftwareModule.isAssigned()); proxyItem.setColour(bean.getType().getColour()); proxyItem.setTypeId(bean.getType().getId()); diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/smtable/SwModuleDetails.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/smtable/SwModuleDetails.java index 3b1a2cad6..8774c9e08 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/smtable/SwModuleDetails.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/smtable/SwModuleDetails.java @@ -8,22 +8,15 @@ */ package org.eclipse.hawkbit.ui.distributions.smtable; -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; - -import org.eclipse.hawkbit.repository.SpPermissionChecker; import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.ui.artifacts.event.SoftwareModuleEvent; -import org.eclipse.hawkbit.ui.artifacts.event.SoftwareModuleEvent.SoftwareModuleEventType; import org.eclipse.hawkbit.ui.artifacts.smtable.SoftwareModuleAddUpdateWindow; -import org.eclipse.hawkbit.ui.common.detailslayout.AbstractTableDetailsLayout; +import org.eclipse.hawkbit.ui.common.detailslayout.AbstractNamedVersionedEntityTableDetailsLayout; import org.eclipse.hawkbit.ui.components.SPUIComponentProvider; import org.eclipse.hawkbit.ui.distributions.state.ManageDistUIState; import org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil; -import org.eclipse.hawkbit.ui.utils.I18N; import org.eclipse.hawkbit.ui.utils.SPUIComponetIdProvider; import org.springframework.beans.factory.annotation.Autowired; -import org.vaadin.spring.events.EventBus; import org.vaadin.spring.events.EventScope; import org.vaadin.spring.events.annotation.EventBusListenerMethod; @@ -42,76 +35,26 @@ import com.vaadin.ui.Window; */ @SpringComponent @ViewScope -public class SwModuleDetails extends AbstractTableDetailsLayout { +public class SwModuleDetails extends AbstractNamedVersionedEntityTableDetailsLayout { private static final long serialVersionUID = -1052279281066089812L; - @Autowired - private I18N i18n; - - @Autowired - private transient EventBus.SessionEventBus eventBus; - - @Autowired - private SpPermissionChecker permissionChecker; - @Autowired private SoftwareModuleAddUpdateWindow softwareModuleAddUpdateWindow; @Autowired private ManageDistUIState manageDistUIState; - private UI ui; - - private Long swModuleId; - - private SoftwareModule selectedSwModule; - - @Override - @PostConstruct - protected void init() { - super.init(); - ui = UI.getCurrent(); - eventBus.subscribe(this); - } - - @PreDestroy - void destroy() { - /* - * It's good manners to do this, even though vaadin-spring will - * automatically unsubscribe when this UI is garbage collected. - */ - eventBus.unsubscribe(this); - } - @EventBusListenerMethod(scope = EventScope.SESSION) void onEvent(final SoftwareModuleEvent softwareModuleEvent) { - if (softwareModuleEvent.getSoftwareModuleEventType() == SoftwareModuleEventType.SELECTED_SOFTWARE_MODULE - || softwareModuleEvent - .getSoftwareModuleEventType() == SoftwareModuleEventType.UPDATED_SOFTWARE_MODULE) { - ui.access(() -> { - /** - * softwareModuleEvent.getSoftwareModule() is null when table - * has no data. - */ - if (softwareModuleEvent.getSoftwareModule() != null) { - selectedSwModule = softwareModuleEvent.getSoftwareModule(); - populateData(true); - } else { - populateData(false); - } - }); - } else if (softwareModuleEvent.getSoftwareModuleEventType() == SoftwareModuleEventType.MINIMIZED) { - showLayout(); - } else if (softwareModuleEvent.getSoftwareModuleEventType() == SoftwareModuleEventType.MAXIMIZED) { - hideLayout(); - } + onBaseEntityEvent(softwareModuleEvent); } @Override protected void onEdit(final ClickEvent event) { - final Window addSoftwareModule = softwareModuleAddUpdateWindow.createUpdateSoftwareModuleWindow(swModuleId); - addSoftwareModule.setCaption(i18n.get("upload.caption.update.swmodule")); + final Window addSoftwareModule = softwareModuleAddUpdateWindow + .createUpdateSoftwareModuleWindow(getSelectedBaseEntityId()); + addSoftwareModule.setCaption(getI18n().get("upload.caption.update.swmodule")); UI.getCurrent().addWindow(addSoftwareModule); addSoftwareModule.setVisible(Boolean.TRUE); } @@ -123,14 +66,14 @@ public class SwModuleDetails extends AbstractTableDetailsLayout { @Override protected void addTabs(final TabSheet detailsTab) { - detailsTab.addTab(createDetailsLayout(), i18n.get("caption.tab.details"), null); - detailsTab.addTab(createDescriptionLayout(), i18n.get("caption.tab.description"), null); - detailsTab.addTab(createLogLayout(), i18n.get("caption.logs.tab"), null); + detailsTab.addTab(createDetailsLayout(), getI18n().get("caption.tab.details"), null); + detailsTab.addTab(createDescriptionLayout(), getI18n().get("caption.tab.description"), null); + detailsTab.addTab(createLogLayout(), getI18n().get("caption.logs.tab"), null); } @Override protected String getDefaultCaption() { - return i18n.get("upload.swModuleTable.header"); + return getI18n().get("upload.swModuleTable.header"); } @Override @@ -143,19 +86,9 @@ public class SwModuleDetails extends AbstractTableDetailsLayout { return manageDistUIState.isSwModuleTableMaximized(); } - @Override - protected void populateDetailsWidget() { - populateDetailsWidget(selectedSwModule); - } - - @Override - protected void clearDetails() { - populateDetailsWidget(null); - } - @Override protected Boolean hasEditPermission() { - return permissionChecker.hasUpdateDistributionPermission(); + return getPermissionChecker().hasUpdateDistributionPermission(); } @Override @@ -163,81 +96,49 @@ public class SwModuleDetails extends AbstractTableDetailsLayout { return null; } - private void populateDetails(final SoftwareModule swModule) { + private void populateDetails() { String maxAssign = HawkbitCommonUtil.SP_STRING_EMPTY; - if (swModule != null) { - if (swModule.getType().getMaxAssignments() == Integer.MAX_VALUE) { - maxAssign = i18n.get("label.multiAssign.type"); + if (getSelectedBaseEntity() != null) { + if (getSelectedBaseEntity().getType().getMaxAssignments() == Integer.MAX_VALUE) { + maxAssign = getI18n().get("label.multiAssign.type"); } else { - maxAssign = i18n.get("label.singleAssign.type"); + maxAssign = getI18n().get("label.singleAssign.type"); } - updateSwModuleDetailsLayout(swModule.getType().getName(), swModule.getVendor(), maxAssign); + updateSwModuleDetailsLayout(getSelectedBaseEntity().getType().getName(), + getSelectedBaseEntity().getVendor(), maxAssign); } else { updateSwModuleDetailsLayout(HawkbitCommonUtil.SP_STRING_EMPTY, HawkbitCommonUtil.SP_STRING_EMPTY, maxAssign); } } - private void populateDescription(final SoftwareModule sw) { - if (sw != null) { - updateDescriptionLayout(i18n.get("label.description"), sw.getDescription()); - } else { - updateDescriptionLayout(i18n.get("label.description"), null); - } - } - private void updateSwModuleDetailsLayout(final String type, final String vendor, final String maxAssign) { final VerticalLayout detailsTabLayout = getDetailsLayout(); detailsTabLayout.removeAllComponents(); - final Label vendorLabel = SPUIComponentProvider.createNameValueLabel(i18n.get("label.dist.details.vendor"), + final Label vendorLabel = SPUIComponentProvider.createNameValueLabel(getI18n().get("label.dist.details.vendor"), HawkbitCommonUtil.trimAndNullIfEmpty(vendor) == null ? "" : vendor); vendorLabel.setId(SPUIComponetIdProvider.DETAILS_VENDOR_LABEL_ID); detailsTabLayout.addComponent(vendorLabel); if (type != null) { - final Label typeLabel = SPUIComponentProvider.createNameValueLabel(i18n.get("label.dist.details.type"), + final Label typeLabel = SPUIComponentProvider.createNameValueLabel(getI18n().get("label.dist.details.type"), type); typeLabel.setId(SPUIComponetIdProvider.DETAILS_TYPE_LABEL_ID); detailsTabLayout.addComponent(typeLabel); } - final Label assignLabel = SPUIComponentProvider.createNameValueLabel(i18n.get("label.assigned.type"), + final Label assignLabel = SPUIComponentProvider.createNameValueLabel(getI18n().get("label.assigned.type"), HawkbitCommonUtil.trimAndNullIfEmpty(maxAssign) == null ? "" : maxAssign); assignLabel.setId(SPUIComponetIdProvider.SWM_DTLS_MAX_ASSIGN); detailsTabLayout.addComponent(assignLabel); } - private void populateLog(final SoftwareModule softwareModule) { - if (null != softwareModule) { - updateLogLayout(getLogLayout(), softwareModule.getLastModifiedAt(), softwareModule.getLastModifiedBy(), - softwareModule.getCreatedAt(), softwareModule.getCreatedBy(), i18n); - } else { - updateLogLayout(getLogLayout(), null, HawkbitCommonUtil.SP_STRING_EMPTY, null, null, i18n); - } - } - - public void setSwModuleId(final Long swModuleId) { - this.swModuleId = swModuleId; - } - - private void populateDetailsWidget(final SoftwareModule swModule) { - if (swModule != null) { - setSwModuleId(swModule.getId()); - setName(getDefaultCaption(), - HawkbitCommonUtil.getFormattedNameVersion(swModule.getName(), swModule.getVersion())); - populateDetails(swModule); - populateDescription(swModule); - populateLog(swModule); - } else { - setSwModuleId(null); - setName(getDefaultCaption(), HawkbitCommonUtil.SP_STRING_EMPTY); - populateDetails(null); - populateDescription(null); - populateLog(null); - } + @Override + protected void populateDetailsWidget() { + populateDetails(); } @Override diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/smtable/SwModuleTable.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/smtable/SwModuleTable.java index 9218198b9..eeea33723 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/smtable/SwModuleTable.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/smtable/SwModuleTable.java @@ -8,34 +8,26 @@ */ package org.eclipse.hawkbit.ui.distributions.smtable; -import java.util.ArrayList; -import java.util.Collections; import java.util.HashMap; -import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; - import org.eclipse.hawkbit.repository.SoftwareManagement; import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.ui.artifacts.details.ArtifactDetailsLayout; import org.eclipse.hawkbit.ui.artifacts.event.SMFilterEvent; import org.eclipse.hawkbit.ui.artifacts.event.SoftwareModuleEvent; -import org.eclipse.hawkbit.ui.artifacts.event.SoftwareModuleEvent.SoftwareModuleEventType; -import org.eclipse.hawkbit.ui.common.table.AbstractTable; +import org.eclipse.hawkbit.ui.common.ManagmentEntityState; +import org.eclipse.hawkbit.ui.common.table.AbstractNamedVersionTable; +import org.eclipse.hawkbit.ui.common.table.BaseEntityEventType; import org.eclipse.hawkbit.ui.components.SPUIComponentProvider; import org.eclipse.hawkbit.ui.decorators.SPUIButtonStyleSmallNoBorder; import org.eclipse.hawkbit.ui.distributions.event.DistributionsUIEvent; import org.eclipse.hawkbit.ui.distributions.event.DistributionsViewAcceptCriteria; -import org.eclipse.hawkbit.ui.distributions.event.DragEvent; import org.eclipse.hawkbit.ui.distributions.event.SaveActionWindowEvent; import org.eclipse.hawkbit.ui.distributions.state.ManageDistUIState; import org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil; -import org.eclipse.hawkbit.ui.utils.I18N; -import org.eclipse.hawkbit.ui.utils.SPDateTimeUtil; import org.eclipse.hawkbit.ui.utils.SPUIComponetIdProvider; import org.eclipse.hawkbit.ui.utils.SPUIDefinitions; import org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions; @@ -45,7 +37,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.vaadin.addons.lazyquerycontainer.BeanQueryFactory; import org.vaadin.addons.lazyquerycontainer.LazyQueryContainer; import org.vaadin.addons.lazyquerycontainer.LazyQueryDefinition; -import org.vaadin.spring.events.EventBus; import org.vaadin.spring.events.EventScope; import org.vaadin.spring.events.annotation.EventBusListenerMethod; @@ -71,19 +62,13 @@ import com.vaadin.ui.Window; */ @SpringComponent @ViewScope -public class SwModuleTable extends AbstractTable { +public class SwModuleTable extends AbstractNamedVersionTable { private static final long serialVersionUID = 6785314784507424750L; - @Autowired - private I18N i18n; - @Autowired private ManageDistUIState manageDistUIState; - @Autowired - private transient EventBus.SessionEventBus eventBus; - @Autowired private transient SoftwareManagement softwareManagement; @@ -97,21 +82,9 @@ public class SwModuleTable extends AbstractTable { * Initialize the filter layout. */ @Override - @PostConstruct protected void init() { super.init(); - eventBus.subscribe(this); styleTableOnDistSelection(); - setNoDataAvailable(); - } - - @PreDestroy - void destroy() { - /* - * It's good manners to do this, even though vaadin-spring will - * automatically unsubscribe when this UI is garbage collected. - */ - eventBus.unsubscribe(this); } /* All event Listeners */ @@ -148,13 +121,7 @@ public class SwModuleTable extends AbstractTable { @EventBusListenerMethod(scope = EventScope.SESSION) void onEvent(final SoftwareModuleEvent event) { - if (event.getSoftwareModuleEventType() == SoftwareModuleEventType.MINIMIZED) { - UI.getCurrent().access(() -> applyMinTableSettings()); - } else if (event.getSoftwareModuleEventType() == SoftwareModuleEventType.MAXIMIZED) { - UI.getCurrent().access(() -> applyMaxTableSettings()); - } else if (event.getSoftwareModuleEventType() == SoftwareModuleEventType.NEW_SOFTWARE_MODULE) { - UI.getCurrent().access(() -> addSoftwareModule(event.getSoftwareModule())); - } + onBaseEntityEvent(event); } @Override @@ -237,56 +204,43 @@ public class SwModuleTable extends AbstractTable { return manageDistUIState.isSwModuleTableMaximized(); } - @SuppressWarnings("rawtypes") @Override - protected void onValueChange() { - eventBus.publish(this, DragEvent.HIDE_DROP_HINT); - @SuppressWarnings("unchecked") - final Set values = (Set) getValue(); - if (values != null && !values.isEmpty()) { - final Iterator iterator = values.iterator(); - Long value = null; - while (iterator.hasNext()) { - value = iterator.next(); - } - if (null != value) { - manageDistUIState.setSelectedBaseSwModuleId(value); - final SoftwareModule baseSoftwareModule = softwareManagement.findSoftwareModuleById(value); - manageDistUIState.setSelectedSoftwareModules(values); - eventBus.publish(this, - new SoftwareModuleEvent(SoftwareModuleEventType.SELECTED_SOFTWARE_MODULE, baseSoftwareModule)); - } - } else { - manageDistUIState.setSelectedBaseSwModuleId(null); - manageDistUIState.setSelectedSoftwareModules(Collections.emptySet()); - eventBus.publish(this, new SoftwareModuleEvent(SoftwareModuleEventType.SELECTED_SOFTWARE_MODULE, null)); - } + protected void publishEntityAfterValueChange(final SoftwareModule selectedLastEntity) { + eventBus.publish(this, new SoftwareModuleEvent(BaseEntityEventType.SELECTED_ENTITY, selectedLastEntity)); + } + + @Override + protected void setManagementEntitiyStateValues(final Set values, final Long lastId) { + manageDistUIState.setSelectedBaseSwModuleId(lastId); + manageDistUIState.setSelectedSoftwareModules(values); + } + + @Override + protected SoftwareModule findEntityByTableValue(final Long lastSelectedId) { + return softwareManagement.findSoftwareModuleById(lastSelectedId); + } + + @Override + protected ManagmentEntityState getManagmentEntityState() { + return null; } @Override protected List getTableVisibleColumns() { - final List columnList = new ArrayList<>(); + final List columnList = super.getTableVisibleColumns(); if (isMaximized()) { - columnList.add(new TableColumn(SPUILabelDefinitions.VAR_NAME, i18n.get("header.name"), 0.2F)); - columnList.add(new TableColumn(SPUILabelDefinitions.VAR_VERSION, i18n.get("header.version"), 0.1F)); - columnList.add(new TableColumn(SPUILabelDefinitions.VAR_VENDOR, i18n.get("header.vendor"), 0.1f)); - columnList.add(new TableColumn(SPUILabelDefinitions.VAR_CREATED_BY, i18n.get("header.createdBy"), 0.1F)); - columnList - .add(new TableColumn(SPUILabelDefinitions.VAR_CREATED_DATE, i18n.get("header.createdDate"), 0.1F)); - columnList.add( - new TableColumn(SPUILabelDefinitions.VAR_LAST_MODIFIED_BY, i18n.get("header.modifiedBy"), 0.1F)); - columnList.add(new TableColumn(SPUILabelDefinitions.VAR_LAST_MODIFIED_DATE, i18n.get("header.modifiedDate"), - 0.1F)); - columnList.add(new TableColumn(SPUILabelDefinitions.VAR_DESC, i18n.get("header.description"), 0.2F)); + columnList.add(new TableColumn(SPUILabelDefinitions.VAR_VENDOR, i18n.get("header.vendor"), 0.1F)); } else { - columnList.add(new TableColumn(SPUILabelDefinitions.VAR_NAME, i18n.get("header.name"), 0.7F)); - columnList.add(new TableColumn(SPUILabelDefinitions.VAR_VERSION, i18n.get("header.version"), 0.2F)); columnList.add(new TableColumn(SPUILabelDefinitions.ARTIFACT_ICON, "", 0.1F)); - } return columnList; } + @Override + protected float getColumnNameMinimizedSize() { + return 0.7F; + } + @Override protected DropHandler getTableDropHandler() { return new DropHandler() { @@ -369,30 +323,27 @@ public class SwModuleTable extends AbstractTable { return name + "." + version; } - @SuppressWarnings("unchecked") - private void addSoftwareModule(final SoftwareModule swModule) { - final Object addItem = addItem(); - final Item item = getItem(addItem); - final String swNameVersion = HawkbitCommonUtil.concatStrings(":", swModule.getName(), swModule.getVersion()); - item.getItemProperty(SPUILabelDefinitions.NAME_VERSION).setValue(swNameVersion); - item.getItemProperty("swId").setValue(swModule.getId()); - item.getItemProperty(SPUILabelDefinitions.VAR_ID).setValue(swModule.getId()); - item.getItemProperty(SPUILabelDefinitions.VAR_DESC).setValue(swModule.getDescription()); - item.getItemProperty(SPUILabelDefinitions.VAR_VERSION).setValue(swModule.getVersion()); - item.getItemProperty(SPUILabelDefinitions.VAR_NAME).setValue(swModule.getName()); - item.getItemProperty(SPUILabelDefinitions.VAR_VENDOR).setValue(swModule.getVendor()); - item.getItemProperty(SPUILabelDefinitions.VAR_CREATED_BY).setValue(swModule.getCreatedBy()); - item.getItemProperty(SPUILabelDefinitions.VAR_LAST_MODIFIED_BY).setValue(swModule.getLastModifiedBy()); - item.getItemProperty(SPUILabelDefinitions.VAR_CREATED_DATE) - .setValue(SPDateTimeUtil.getFormattedDate(swModule.getCreatedAt())); - item.getItemProperty(SPUILabelDefinitions.VAR_LAST_MODIFIED_DATE) - .setValue(SPDateTimeUtil.getFormattedDate(swModule.getLastModifiedAt())); + @Override + protected Item addEntity(final SoftwareModule baseEntity) { + final Item item = super.addEntity(baseEntity); - item.getItemProperty(SPUILabelDefinitions.VAR_COLOR).setValue(swModule.getType().getColour()); if (!manageDistUIState.getSelectedSoftwareModules().isEmpty()) { - manageDistUIState.getSelectedSoftwareModules().stream().forEach(swmNameId -> unselect(swmNameId)); + manageDistUIState.getSelectedSoftwareModules().stream().forEach(this::unselect); } - select(swModule.getId()); + select(baseEntity.getId()); + return item; + } + + @Override + @SuppressWarnings("unchecked") + protected void updateEntity(final SoftwareModule baseEntity, final Item item) { + final String swNameVersion = HawkbitCommonUtil.concatStrings(":", baseEntity.getName(), + baseEntity.getVersion()); + item.getItemProperty(SPUILabelDefinitions.NAME_VERSION).setValue(swNameVersion); + item.getItemProperty("swId").setValue(baseEntity.getId()); + item.getItemProperty(SPUILabelDefinitions.VAR_VENDOR).setValue(baseEntity.getVendor()); + item.getItemProperty(SPUILabelDefinitions.VAR_COLOR).setValue(baseEntity.getType().getColour()); + super.updateEntity(baseEntity, item); } private void showArtifactDetailsWindow(final Long itemId, final String nameVersionStr) { @@ -431,13 +382,10 @@ public class SwModuleTable extends AbstractTable { UI.getCurrent().addWindow(atrifactDtlsWindow); } - private void setNoDataAvailable() { - final int conatinerSize = getContainerDataSource().size(); - if (conatinerSize == 0) { - manageDistUIState.setNoDataAvilableSwModule(true); - } else { - manageDistUIState.setNoDataAvilableSwModule(false); - } + @Override + protected void setDataAvailable(final boolean available) { + manageDistUIState.setNoDataAvilableSwModule(!available); + } } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/smtable/SwModuleTableHeader.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/smtable/SwModuleTableHeader.java index 56d7706fc..e02dffa8e 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/smtable/SwModuleTableHeader.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/smtable/SwModuleTableHeader.java @@ -8,21 +8,15 @@ */ package org.eclipse.hawkbit.ui.distributions.smtable; -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; - -import org.eclipse.hawkbit.repository.SpPermissionChecker; import org.eclipse.hawkbit.ui.artifacts.event.SMFilterEvent; import org.eclipse.hawkbit.ui.artifacts.event.SoftwareModuleEvent; -import org.eclipse.hawkbit.ui.artifacts.event.SoftwareModuleEvent.SoftwareModuleEventType; import org.eclipse.hawkbit.ui.artifacts.smtable.SoftwareModuleAddUpdateWindow; import org.eclipse.hawkbit.ui.common.table.AbstractTableHeader; +import org.eclipse.hawkbit.ui.common.table.BaseEntityEventType; import org.eclipse.hawkbit.ui.distributions.event.DistributionsUIEvent; import org.eclipse.hawkbit.ui.distributions.state.ManageDistUIState; -import org.eclipse.hawkbit.ui.utils.I18N; import org.eclipse.hawkbit.ui.utils.SPUIComponetIdProvider; import org.springframework.beans.factory.annotation.Autowired; -import org.vaadin.spring.events.EventBus; import org.vaadin.spring.events.EventScope; import org.vaadin.spring.events.annotation.EventBusListenerMethod; @@ -43,33 +37,12 @@ public class SwModuleTableHeader extends AbstractTableHeader { private static final long serialVersionUID = 242961845006626297L; - @Autowired - private I18N i18n; - - @Autowired - private SpPermissionChecker permChecker; - - @Autowired - private transient EventBus.SessionEventBus eventbus; - @Autowired private ManageDistUIState manageDistUIState; @Autowired private SoftwareModuleAddUpdateWindow softwareModuleAddUpdateWindow; - @Override - @PostConstruct - protected void init() { - super.init(); - eventbus.subscribe(this); - } - - @PreDestroy - void destroy() { - eventbus.unsubscribe(this); - } - @EventBusListenerMethod(scope = EventScope.SESSION) void onEvent(final DistributionsUIEvent event) { if (event == DistributionsUIEvent.HIDE_SM_FILTER_BY_TYPE) { @@ -149,14 +122,14 @@ public class SwModuleTableHeader extends AbstractTableHeader { @Override public void maximizeTable() { manageDistUIState.setSwModuleTableMaximized(Boolean.TRUE); - eventbus.publish(this, new SoftwareModuleEvent(SoftwareModuleEventType.MAXIMIZED, null)); + eventbus.publish(this, new SoftwareModuleEvent(BaseEntityEventType.MAXIMIZED, null)); } @Override public void minimizeTable() { manageDistUIState.setSwModuleTableMaximized(Boolean.FALSE); - eventbus.publish(this, new SoftwareModuleEvent(SoftwareModuleEventType.MINIMIZED, null)); + eventbus.publish(this, new SoftwareModuleEvent(BaseEntityEventType.MINIMIZED, null)); } @Override diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/smtype/DistSMTypeFilterButtons.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/smtype/DistSMTypeFilterButtons.java index d3251cf9b..146d8f019 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/smtype/DistSMTypeFilterButtons.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/smtype/DistSMTypeFilterButtons.java @@ -11,11 +11,8 @@ package org.eclipse.hawkbit.ui.distributions.smtype; import java.util.HashMap; import java.util.Map; -import javax.annotation.PreDestroy; - import org.eclipse.hawkbit.ui.artifacts.event.SoftwareModuleTypeEvent; import org.eclipse.hawkbit.ui.common.SoftwareModuleTypeBeanQuery; -import org.eclipse.hawkbit.ui.common.filterlayout.AbstractFilterButtonClickBehaviour; import org.eclipse.hawkbit.ui.common.filterlayout.AbstractFilterButtons; import org.eclipse.hawkbit.ui.distributions.event.DistributionsViewAcceptCriteria; import org.eclipse.hawkbit.ui.distributions.event.SaveActionWindowEvent; @@ -27,7 +24,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.vaadin.addons.lazyquerycontainer.BeanQueryFactory; import org.vaadin.addons.lazyquerycontainer.LazyQueryContainer; import org.vaadin.addons.lazyquerycontainer.LazyQueryDefinition; -import org.vaadin.spring.events.EventBus; import org.vaadin.spring.events.EventScope; import org.vaadin.spring.events.annotation.EventBusListenerMethod; @@ -47,21 +43,12 @@ public class DistSMTypeFilterButtons extends AbstractFilterButtons { private static final long serialVersionUID = 6804534533362387433L; - @Autowired - private transient EventBus.SessionEventBus eventBus; - @Autowired private ManageDistUIState manageDistUIState; @Autowired private DistributionsViewAcceptCriteria distributionsViewAcceptCriteria; - @Override - public void init(final AbstractFilterButtonClickBehaviour filterButtonClickBehaviour) { - super.init(filterButtonClickBehaviour); - eventBus.subscribe(this); - } - @Override protected String getButtonsTableId() { return SPUIComponetIdProvider.SW_MODULE_TYPE_TABLE_ID; @@ -82,10 +69,9 @@ public class DistSMTypeFilterButtons extends AbstractFilterButtons { } @Override - protected boolean isClickedByDefault(final Long buttonId) { - + protected boolean isClickedByDefault(final String typeName) { return manageDistUIState.getSoftwareModuleFilters().getSoftwareModuleType().isPresent() - && manageDistUIState.getSoftwareModuleFilters().getSoftwareModuleType().get().getId().equals(buttonId); + && manageDistUIState.getSoftwareModuleFilters().getSoftwareModuleType().get().getName().equals(typeName); } @Override @@ -136,9 +122,5 @@ public class DistSMTypeFilterButtons extends AbstractFilterButtons { setContainerDataSource(createButtonsLazyQueryContainer()); } - @PreDestroy - void destroy() { - eventBus.unsubscribe(this); - } } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/smtype/DistSMTypeFilterHeader.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/smtype/DistSMTypeFilterHeader.java index edf20b206..e328b45a4 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/smtype/DistSMTypeFilterHeader.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/smtype/DistSMTypeFilterHeader.java @@ -10,7 +10,6 @@ package org.eclipse.hawkbit.ui.distributions.smtype; import javax.annotation.PostConstruct; -import org.eclipse.hawkbit.repository.SpPermissionChecker; import org.eclipse.hawkbit.ui.artifacts.smtype.CreateUpdateSoftwareTypeLayout; import org.eclipse.hawkbit.ui.common.filterlayout.AbstractFilterHeader; import org.eclipse.hawkbit.ui.distributions.event.DistributionsUIEvent; @@ -19,7 +18,6 @@ import org.eclipse.hawkbit.ui.utils.SPUIComponetIdProvider; import org.eclipse.hawkbit.ui.utils.SPUIDefinitions; import org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions; import org.springframework.beans.factory.annotation.Autowired; -import org.vaadin.spring.events.EventBus; import com.vaadin.spring.annotation.SpringComponent; import com.vaadin.spring.annotation.ViewScope; @@ -36,12 +34,6 @@ public class DistSMTypeFilterHeader extends AbstractFilterHeader { private static final long serialVersionUID = -8763788280848718344L; - @Autowired - private SpPermissionChecker permChecker; - - @Autowired - private transient EventBus.SessionEventBus eventBus; - @Autowired private ManageDistUIState manageDistUIState; diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/state/ManageDistUIState.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/state/ManageDistUIState.java index ce31f649b..a68a42e00 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/state/ManageDistUIState.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/distributions/state/ManageDistUIState.java @@ -18,6 +18,7 @@ import java.util.Set; import org.eclipse.hawkbit.repository.model.DistributionSetIdName; import org.eclipse.hawkbit.repository.model.SoftwareModuleIdName; +import org.eclipse.hawkbit.ui.common.ManagmentEntityState; import org.springframework.beans.factory.annotation.Autowired; import com.vaadin.spring.annotation.SpringComponent; @@ -30,7 +31,7 @@ import com.vaadin.spring.annotation.VaadinSessionScope; */ @SpringComponent @VaadinSessionScope -public class ManageDistUIState implements Serializable { +public class ManageDistUIState implements ManagmentEntityState, Serializable { private static final long serialVersionUID = -7569047247017742928L; @@ -101,26 +102,23 @@ public class ManageDistUIState implements Serializable { * @return the slectedDistributions */ public Optional> getSelectedDistributions() { - return selectedDistributions == null ? Optional.empty() : Optional.of(selectedDistributions); + return Optional.ofNullable(selectedDistributions); } /** * @return the lastSelectedDistribution */ public Optional getLastSelectedDistribution() { - return lastSelectedDistribution == null ? Optional.empty() : Optional.of(lastSelectedDistribution); + return Optional.ofNullable(lastSelectedDistribution); } - /** - * @param lastSelectedDistribution - * the lastSelectedDistribution to set - */ - public void setLastSelectedDistribution(final DistributionSetIdName lastSelectedDistribution) { - this.lastSelectedDistribution = lastSelectedDistribution; + @Override + public void setLastSelectedEntity(final DistributionSetIdName value) { + this.lastSelectedDistribution = value; } - public void setSelectedDistributions(final Set slectedDistributions) { - selectedDistributions = slectedDistributions; + public void setSelectedEnitities(final Set values) { + selectedDistributions = values; } /** @@ -141,7 +139,7 @@ public class ManageDistUIState implements Serializable { * @return the selectedBaseSwModuleId */ public Optional getSelectedBaseSwModuleId() { - return selectedBaseSwModuleId != null ? Optional.of(selectedBaseSwModuleId) : Optional.empty(); + return Optional.ofNullable(selectedBaseSwModuleId); } /** diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/CreateOrUpdateFilterHeader.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/CreateOrUpdateFilterHeader.java index 97d2bf031..6a671e228 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/CreateOrUpdateFilterHeader.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/CreateOrUpdateFilterHeader.java @@ -68,6 +68,8 @@ public class CreateOrUpdateFilterHeader extends VerticalLayout implements Button private static final long serialVersionUID = 7474232427119031474L; + private static final String breadcrumbCustomFilters = "breadcrumb.target.filter.custom.filters"; + @Autowired private I18N i18n; @@ -93,6 +95,12 @@ public class CreateOrUpdateFilterHeader extends VerticalLayout implements Button @Qualifier("uiExecutor") private transient Executor executor; + private HorizontalLayout breadcrumbLayout; + + private Button breadcrumbButton; + + private Label breadcrumbName; + private Label headerCaption; private TextField queryTextField; @@ -169,6 +177,7 @@ public class CreateOrUpdateFilterHeader extends VerticalLayout implements Button oldFilterName = filterManagementUIState.getTfQuery().get().getName(); oldFilterQuery = filterManagementUIState.getTfQuery().get().getQuery(); } + breadcrumbName.setValue(nameLabel.getValue()); showValidationSuccesIcon(); titleFilterIconsLayout.addStyleName(SPUIStyleDefinitions.TARGET_FILTER_CAPTION_LAYOUT); headerCaption.setVisible(false); @@ -177,6 +186,7 @@ public class CreateOrUpdateFilterHeader extends VerticalLayout implements Button private void resetComponents() { headerCaption.setVisible(true); + breadcrumbName.setValue(headerCaption.getValue()); nameLabel.setValue(""); queryTextField.setValue(""); setInitialStatusIconStyle(validationIcon); @@ -201,6 +211,9 @@ public class CreateOrUpdateFilterHeader extends VerticalLayout implements Button } private void createComponents() { + + breadcrumbButton = createBreadcrumbButton(); + headerCaption = SPUIComponentProvider.getLabel(SPUILabelDefinitions.VAR_CREATE_FILTER, SPUILabelDefinitions.SP_WIDGET_CAPTION); @@ -221,12 +234,23 @@ public class CreateOrUpdateFilterHeader extends VerticalLayout implements Button closeIcon = createSearchResetIcon(); } + private Button createBreadcrumbButton() { + final Button createFilterViewLink = SPUIComponentProvider.getButton(null, "", "", null, false, null, + SPUIButtonStyleSmallNoBorder.class); + createFilterViewLink.setStyleName(ValoTheme.LINK_SMALL + " " + "on-focus-no-border link rollout-caption-links"); + createFilterViewLink.setDescription(i18n.get(breadcrumbCustomFilters)); + createFilterViewLink.setCaption(i18n.get(breadcrumbCustomFilters)); + createFilterViewLink.addClickListener(value -> showCustomFiltersView()); + + return createFilterViewLink; + } + private TextField createNameTextField() { final TextField nameField = SPUIComponentProvider.getTextField("", ValoTheme.TEXTFIELD_TINY, false, null, i18n.get("textfield.customfiltername"), true, SPUILabelDefinitions.TEXT_FIELD_MAX_LENGTH); nameField.setId(SPUIComponetIdProvider.CUSTOM_FILTER_ADD_NAME); nameField.setPropertyDataSource(nameLabel); - nameField.addTextChangeListener(event -> onFiterNameChange(event)); + nameField.addTextChangeListener(event -> onFilterNameChange(event)); return nameField; } @@ -256,7 +280,7 @@ public class CreateOrUpdateFilterHeader extends VerticalLayout implements Button }; } - private void onFiterNameChange(final TextChangeEvent event) { + private void onFilterNameChange(final TextChangeEvent event) { if (isNameAndQueryEmpty(event.getText(), queryTextField.getValue()) || (event.getText().equals(oldFilterName) && queryTextField.getValue().equals(oldFilterQuery))) { saveButton.setEnabled(false); @@ -276,6 +300,13 @@ public class CreateOrUpdateFilterHeader extends VerticalLayout implements Button titleFilterIconsLayout.addComponents(headerCaption, captionLayout); titleFilterIconsLayout.setSpacing(true); + breadcrumbLayout = new HorizontalLayout(); + breadcrumbLayout.addComponent(breadcrumbButton); + breadcrumbLayout.addComponent(new Label(">")); + breadcrumbName = SPUIComponentProvider.getLabel(null, SPUILabelDefinitions.SP_WIDGET_CAPTION); + breadcrumbLayout.addComponent(breadcrumbName); + breadcrumbName.addStyleName("breadcrumbPaddingLeft"); + final HorizontalLayout titleFilterLayout = new HorizontalLayout(); titleFilterLayout.setSizeFull(); titleFilterLayout.addComponents(titleFilterIconsLayout, closeIcon); @@ -290,7 +321,7 @@ public class CreateOrUpdateFilterHeader extends VerticalLayout implements Button searchLayout.setSpacing(false); searchLayout.addComponents(validationIcon, queryTextField); searchLayout.addStyleName("custom-search-layout"); - searchLayout.setComponentAlignment(validationIcon, Alignment.MIDDLE_CENTER); + searchLayout.setComponentAlignment(validationIcon, Alignment.TOP_CENTER); final HorizontalLayout iconLayout = new HorizontalLayout(); iconLayout.setSizeUndefined(); @@ -302,10 +333,12 @@ public class CreateOrUpdateFilterHeader extends VerticalLayout implements Button queryLayout.setSpacing(true); queryLayout.addComponents(searchLayout, iconLayout); + addComponent(breadcrumbLayout); addComponent(titleFilterLayout); addComponent(queryLayout); setSpacing(true); addStyleName(SPUIStyleDefinitions.WIDGET_TITLE); + addStyleName("bordered-layout"); } private void setUpCaptionLayout(final boolean isCreateView) { @@ -524,4 +557,8 @@ public class CreateOrUpdateFilterHeader extends VerticalLayout implements Button } } + private void showCustomFiltersView() { + eventBus.publish(this, CustomFilterUIEvent.SHOW_FILTER_MANAGEMENT); + } + } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/CreateOrUpdateFilterTable.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/CreateOrUpdateFilterTable.java index ebeb95957..11121c1a5 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/CreateOrUpdateFilterTable.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/CreateOrUpdateFilterTable.java @@ -17,10 +17,12 @@ import java.util.Map; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; +import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.TargetUpdateStatus; import org.eclipse.hawkbit.ui.components.SPUIComponentProvider; import org.eclipse.hawkbit.ui.filtermanagement.event.CustomFilterUIEvent; import org.eclipse.hawkbit.ui.filtermanagement.state.FilterManagementUIState; +import org.eclipse.hawkbit.ui.utils.AssignInstalledDSTooltipGenerator; import org.eclipse.hawkbit.ui.utils.I18N; import org.eclipse.hawkbit.ui.utils.SPUIComponetIdProvider; import org.eclipse.hawkbit.ui.utils.SPUIDefinitions; @@ -69,6 +71,10 @@ public class CreateOrUpdateFilterTable extends Table { private static final int PROPERTY_DEPT = 3; + private static final String ASSIGN_DIST_SET = "assignedDistributionSet"; + + private static final String INSTALL_DIST_SET = "installedDistributionSet"; + /** * Initialize the Action History Table. */ @@ -87,6 +93,7 @@ public class CreateOrUpdateFilterTable extends Table { setId(SPUIComponetIdProvider.CUSTOM_FILTER_TARGET_TABLE_ID); setSelectable(false); eventBus.subscribe(this); + setItemDescriptionGenerator(new AssignInstalledDSTooltipGenerator()); } @PreDestroy @@ -160,6 +167,9 @@ public class CreateOrUpdateFilterTable extends Table { private void setCollapsibleColumns() { setColumnCollapsed(SPUILabelDefinitions.VAR_LAST_MODIFIED_BY, true); setColumnCollapsed(SPUILabelDefinitions.VAR_LAST_MODIFIED_DATE, true); + + setColumnCollapsed(ASSIGN_DIST_SET, true); + setColumnCollapsed(INSTALL_DIST_SET, true); } /** @@ -172,10 +182,13 @@ public class CreateOrUpdateFilterTable extends Table { container.addContainerProperty(SPUILabelDefinitions.VAR_CREATED_DATE, Date.class, null); container.addContainerProperty(SPUILabelDefinitions.VAR_LAST_MODIFIED_BY, String.class, null, false, true); container.addContainerProperty(SPUILabelDefinitions.VAR_LAST_MODIFIED_DATE, String.class, null, false, true); - container.addContainerProperty(SPUILabelDefinitions.ASSIGNED_DISTRIBUTION_NAME_VER, String.class, ""); - container.addContainerProperty(SPUILabelDefinitions.INSTALLED_DISTRIBUTION_NAME_VER, String.class, null); container.addContainerProperty(SPUILabelDefinitions.VAR_TARGET_STATUS, TargetUpdateStatus.class, null); container.addContainerProperty(SPUILabelDefinitions.VAR_DESC, String.class, "", false, true); + + container.addContainerProperty(ASSIGN_DIST_SET, DistributionSet.class, null, false, true); + container.addContainerProperty(INSTALL_DIST_SET, DistributionSet.class, null, false, true); + container.addContainerProperty(SPUILabelDefinitions.ASSIGNED_DISTRIBUTION_NAME_VER, String.class, ""); + container.addContainerProperty(SPUILabelDefinitions.INSTALLED_DISTRIBUTION_NAME_VER, String.class, null); } private List getVisbleColumns() { @@ -186,12 +199,9 @@ public class CreateOrUpdateFilterTable extends Table { columnList.add(new TableColumn(SPUILabelDefinitions.VAR_LAST_MODIFIED_BY, i18n.get("header.modifiedBy"), 0.1F)); columnList.add( new TableColumn(SPUILabelDefinitions.VAR_LAST_MODIFIED_DATE, i18n.get("header.modifiedDate"), 0.1F)); - columnList.add(new TableColumn(SPUILabelDefinitions.ASSIGNED_DISTRIBUTION_NAME_VER, - i18n.get("header.assigned.ds"), 0.125F)); - columnList.add(new TableColumn(SPUILabelDefinitions.INSTALLED_DISTRIBUTION_NAME_VER, - i18n.get("header.installed.ds"), 0.125F)); columnList.add(new TableColumn(SPUILabelDefinitions.VAR_DESC, i18n.get("header.description"), 0.1F)); columnList.add(new TableColumn(SPUILabelDefinitions.STATUS_ICON, i18n.get("header.status"), 0.1F)); + return columnList; } @@ -244,4 +254,5 @@ public class CreateOrUpdateFilterTable extends Table { populateTableData(); eventBus.publish(this, CustomFilterUIEvent.UPDATE_TARGET_FILTER_SEARCH_ICON); } + } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/CustomTargetBeanQuery.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/CustomTargetBeanQuery.java index bf5fdbe54..35f88f5a1 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/CustomTargetBeanQuery.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/CustomTargetBeanQuery.java @@ -13,8 +13,8 @@ import java.util.List; import java.util.Map; import org.eclipse.hawkbit.repository.TargetManagement; -import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.Target; +import org.eclipse.hawkbit.ui.common.UserDetailsFormatter; import org.eclipse.hawkbit.ui.components.ProxyTarget; import org.eclipse.hawkbit.ui.filtermanagement.state.FilterManagementUIState; import org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil; @@ -118,22 +118,9 @@ public class CustomTargetBeanQuery extends AbstractBeanQuery { prxyTarget.setLastModifiedDate(SPDateTimeUtil.getFormattedDate(targ.getLastModifiedAt())); prxyTarget.setCreatedDate(SPDateTimeUtil.getFormattedDate(targ.getCreatedAt())); prxyTarget.setCreatedAt(targ.getCreatedAt()); - prxyTarget.setCreatedByUser(HawkbitCommonUtil.getIMUser(targ.getCreatedBy())); - prxyTarget.setModifiedByUser(HawkbitCommonUtil.getIMUser(targ.getLastModifiedBy())); - final Target target = getTargetManagement().findTargetByControllerIDWithDetails(targ.getControllerId()); - final DistributionSet installedDistributionSet = target.getTargetInfo().getInstalledDistributionSet(); - prxyTarget.setInstalledDistributionSet(installedDistributionSet); - final DistributionSet assignedDistributionSet = target.getAssignedDistributionSet(); - prxyTarget.setAssignedDistributionSet(assignedDistributionSet); + prxyTarget.setCreatedByUser(UserDetailsFormatter.loadAndFormatCreatedBy(targ)); + prxyTarget.setModifiedByUser(UserDetailsFormatter.loadAndFormatLastModifiedBy(targ)); - if (null != assignedDistributionSet) { - prxyTarget.setAssignedDistNameVersion(HawkbitCommonUtil.getFormattedNameVersion( - assignedDistributionSet.getName(), assignedDistributionSet.getVersion())); - } - if (null != installedDistributionSet) { - prxyTarget.setInstalledDistNameVersion(HawkbitCommonUtil.getFormattedNameVersion( - installedDistributionSet.getName(), installedDistributionSet.getVersion())); - } prxyTarget.setUpdateStatus(targ.getTargetInfo().getUpdateStatus()); prxyTarget.setLastTargetQuery(targ.getTargetInfo().getLastTargetQuery()); prxyTarget.setTargetInfo(targ.getTargetInfo()); diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/FilterManagementView.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/FilterManagementView.java index 06cbe4d69..ef759aa5f 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/FilterManagementView.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/FilterManagementView.java @@ -96,7 +96,8 @@ public class FilterManagementView extends VerticalLayout implements View { } else if (custFilterUIEvent == CustomFilterUIEvent.CREATE_NEW_FILTER_CLICK || custFilterUIEvent == CustomFilterUIEvent.FILTER_TARGET_BY_QUERY) { this.getUI().access(() -> viewCreateTargetFilterLayout()); - } else if (custFilterUIEvent == CustomFilterUIEvent.EXIT_CREATE_OR_UPDATE_FILTRER_VIEW) { + } else if (custFilterUIEvent == CustomFilterUIEvent.EXIT_CREATE_OR_UPDATE_FILTRER_VIEW + || custFilterUIEvent == CustomFilterUIEvent.SHOW_FILTER_MANAGEMENT) { UI.getCurrent().access(() -> viewListView()); } } @@ -121,11 +122,11 @@ public class FilterManagementView extends VerticalLayout implements View { tableHeaderLayout.setComponentAlignment(createNewFilterHeader, Alignment.TOP_CENTER); tableHeaderLayout.addComponent(createNewFilterTable); tableHeaderLayout.setComponentAlignment(createNewFilterTable, Alignment.TOP_CENTER); - tableHeaderLayout.setExpandRatio(createNewFilterTable, 1.0f); + tableHeaderLayout.setExpandRatio(createNewFilterTable, 1.0F); addComponent(tableHeaderLayout); setComponentAlignment(tableHeaderLayout, Alignment.TOP_CENTER); - setExpandRatio(tableHeaderLayout, 1.0f); + setExpandRatio(tableHeaderLayout, 1.0F); final HorizontalLayout targetsCountmessageLabelLayout = addTargetFilterMessageLabel(); addComponent(targetsCountmessageLabelLayout); @@ -135,17 +136,17 @@ public class FilterManagementView extends VerticalLayout implements View { private void viewListView() { removeAllComponents(); - final VerticalLayout tableHeaderLayout = new VerticalLayout(); - tableHeaderLayout.setSizeFull(); - tableHeaderLayout.setSpacing(false); - tableHeaderLayout.setMargin(false); - tableHeaderLayout.setStyleName("table-layout"); - tableHeaderLayout.addComponent(targetFilterHeader); - tableHeaderLayout.setComponentAlignment(targetFilterHeader, Alignment.TOP_CENTER); - tableHeaderLayout.addComponent(targetFilterTable); - tableHeaderLayout.setComponentAlignment(targetFilterTable, Alignment.TOP_CENTER); - tableHeaderLayout.setExpandRatio(targetFilterTable, 1.0f); - addComponent(tableHeaderLayout); + final VerticalLayout tableListViewLayout = new VerticalLayout(); + tableListViewLayout.setSizeFull(); + tableListViewLayout.setSpacing(false); + tableListViewLayout.setMargin(false); + tableListViewLayout.setStyleName("table-layout"); + tableListViewLayout.addComponent(targetFilterHeader); + tableListViewLayout.setComponentAlignment(targetFilterHeader, Alignment.TOP_CENTER); + tableListViewLayout.addComponent(targetFilterTable); + tableListViewLayout.setComponentAlignment(targetFilterTable, Alignment.TOP_CENTER); + tableListViewLayout.setExpandRatio(targetFilterTable, 1.0F); + addComponent(tableListViewLayout); } private HorizontalLayout addTargetFilterMessageLabel() { diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/FilterQueryValidation.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/FilterQueryValidation.java index d3ec6245d..4f528c74a 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/FilterQueryValidation.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/FilterQueryValidation.java @@ -31,10 +31,7 @@ import cz.jirutka.rsql.parser.RSQLParserException; * * Validates the target filter query. * - * - * */ - public final class FilterQueryValidation { private static final Logger LOGGER = LoggerFactory.getLogger(FilterQueryValidation.class); @@ -103,6 +100,9 @@ public final class FilterQueryValidation { * @param expectedTokens * @return */ + // Exception squid:S2095 - see + // https://jira.sonarsource.com/browse/SONARJAVA-1478 + @SuppressWarnings({ "squid:S2095" }) public static List processExpectedTokens(final List expectedTokens) { final List expectToken = new ArrayList<>(); if (expectedTokens.size() == 2 && expectedTokens.contains(9) && expectedTokens.contains(4)) { diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/TargetFilterBeanQuery.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/TargetFilterBeanQuery.java index 9c50640cd..4a2d6da6c 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/TargetFilterBeanQuery.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/TargetFilterBeanQuery.java @@ -14,6 +14,7 @@ import java.util.Map; import org.eclipse.hawkbit.repository.TargetFilterQueryManagement; import org.eclipse.hawkbit.repository.model.TargetFilterQuery; +import org.eclipse.hawkbit.ui.common.UserDetailsFormatter; import org.eclipse.hawkbit.ui.components.ProxyTargetFilter; import org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil; import org.eclipse.hawkbit.ui.utils.SPDateTimeUtil; @@ -93,9 +94,9 @@ public class TargetFilterBeanQuery extends AbstractBeanQuery proxyTarFilter.setName(tarFilterQuery.getName()); proxyTarFilter.setId(tarFilterQuery.getId()); proxyTarFilter.setCreatedDate(SPDateTimeUtil.getFormattedDate(tarFilterQuery.getCreatedAt())); - proxyTarFilter.setCreatedBy(HawkbitCommonUtil.getIMUser(tarFilterQuery.getCreatedBy())); + proxyTarFilter.setCreatedBy(UserDetailsFormatter.loadAndFormatCreatedBy(tarFilterQuery)); proxyTarFilter.setModifiedDate(SPDateTimeUtil.getFormattedDate(tarFilterQuery.getLastModifiedAt())); - proxyTarFilter.setLastModifiedBy(HawkbitCommonUtil.getIMUser(tarFilterQuery.getLastModifiedBy())); + proxyTarFilter.setLastModifiedBy(UserDetailsFormatter.loadAndFormatLastModifiedBy(tarFilterQuery)); proxyTarFilter.setQuery(tarFilterQuery.getQuery()); proxyTargetFilter.add(proxyTarFilter); } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/TargetFilterHeader.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/TargetFilterHeader.java index 08592f20c..79877f299 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/TargetFilterHeader.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/TargetFilterHeader.java @@ -13,7 +13,6 @@ import javax.annotation.PostConstruct; import org.eclipse.hawkbit.repository.SpPermissionChecker; import org.eclipse.hawkbit.ui.components.SPUIButton; import org.eclipse.hawkbit.ui.components.SPUIComponentProvider; -import org.eclipse.hawkbit.ui.decorators.SPUIButtonStyleSmall; import org.eclipse.hawkbit.ui.decorators.SPUIButtonStyleSmallNoBorder; import org.eclipse.hawkbit.ui.filtermanagement.event.CustomFilterUIEvent; import org.eclipse.hawkbit.ui.filtermanagement.state.FilterManagementUIState; @@ -79,9 +78,8 @@ public class TargetFilterHeader extends VerticalLayout { } private Label createHeaderCaption() { - final Label captionLabel = SPUIComponentProvider.getLabel("Custom Filters", + return SPUIComponentProvider.getLabel(SPUIDefinitions.TARGET_FILTER_LIST_HEADER_CAPTION, SPUILabelDefinitions.SP_WIDGET_CAPTION); - return captionLabel; } private void buildLayout() { @@ -110,10 +108,9 @@ public class TargetFilterHeader extends VerticalLayout { } private Button createAddButton() { - final Button button = SPUIComponentProvider.getButton("camp.search.add.Id", "Create Filter", "Create Filter", - "", false, null, SPUIButtonStyleSmall.class); + final Button button = SPUIComponentProvider.getButton(SPUIComponetIdProvider.TARGET_FILTER_ADD_ICON_ID, "", "", + null, false, FontAwesome.PLUS, SPUIButtonStyleSmallNoBorder.class); button.addClickListener(event -> addNewFilter()); - button.addStyleName("on-focus-no-border link"); return button; } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/event/CustomFilterUIEvent.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/event/CustomFilterUIEvent.java index 57de12aca..a09d3d397 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/event/CustomFilterUIEvent.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/filtermanagement/event/CustomFilterUIEvent.java @@ -15,5 +15,5 @@ package org.eclipse.hawkbit.ui.filtermanagement.event; * */ public enum CustomFilterUIEvent { - FILTER_TARGET_BY_QUERY, FILTER_BY_CUST_FILTER_TEXT, FILTER_BY_CUST_FILTER_TEXT_REMOVE, CREATE_NEW_FILTER_CLICK, EXIT_CREATE_OR_UPDATE_FILTRER_VIEW, TARGET_FILTER_DETAIL_VIEW, TARGET_DETAILS_VIEW, CREATE_TARGET_FILTER_QUERY, UPDATED_TARGET_FILTER_QUERY, UPDATE_TARGET_FILTER_SEARCH_ICON + FILTER_TARGET_BY_QUERY, FILTER_BY_CUST_FILTER_TEXT, FILTER_BY_CUST_FILTER_TEXT_REMOVE, CREATE_NEW_FILTER_CLICK, EXIT_CREATE_OR_UPDATE_FILTRER_VIEW, TARGET_FILTER_DETAIL_VIEW, TARGET_DETAILS_VIEW, CREATE_TARGET_FILTER_QUERY, UPDATED_TARGET_FILTER_QUERY, UPDATE_TARGET_FILTER_SEARCH_ICON, SHOW_FILTER_MANAGEMENT } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/login/LoginView.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/login/LoginView.java index 0ddf0fcd3..a6cc46708 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/login/LoginView.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/login/LoginView.java @@ -225,7 +225,7 @@ public class LoginView extends VerticalLayout implements View { final String linkStyle = "v-link"; if (!uiProperties.getLinks().getDocumentation().getRoot().isEmpty()) { - final Link docuLink = SPUIComponentProvider.getLink(SPUIComponetIdProvider.LINK_DOCUMENATION, + final Link docuLink = SPUIComponentProvider.getLink(SPUIComponetIdProvider.LINK_DOCUMENTATION, i18n.get("link.documentation.name"), uiProperties.getLinks().getDocumentation().getRoot(), FontAwesome.QUESTION_CIRCLE, "_blank", linkStyle, true); links.addComponent(docuLink); diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/DeploymentView.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/DeploymentView.java index 9069858aa..e260a3bf4 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/DeploymentView.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/DeploymentView.java @@ -12,6 +12,7 @@ import javax.annotation.PreDestroy; import org.eclipse.hawkbit.repository.SpPermissionChecker; import org.eclipse.hawkbit.ui.HawkbitUI; +import org.eclipse.hawkbit.ui.common.table.BaseEntityEventType; import org.eclipse.hawkbit.ui.management.actionhistory.ActionHistoryComponent; import org.eclipse.hawkbit.ui.management.dstable.DistributionTableLayout; import org.eclipse.hawkbit.ui.management.dstag.DistributionTagLayout; @@ -108,19 +109,18 @@ public class DeploymentView extends VerticalLayout implements View, BrowserWindo @EventBusListenerMethod(scope = EventScope.SESSION) void onEvent(final DistributionTableEvent event) { - if (event.getDistributionComponentEvent() == DistributionTableEvent.DistributionComponentEvent.MINIMIZED) { + if (BaseEntityEventType.MINIMIZED == event.getEventType()) { minimizeDistTable(); - } else if (event - .getDistributionComponentEvent() == DistributionTableEvent.DistributionComponentEvent.MAXIMIZED) { + } else if (BaseEntityEventType.MAXIMIZED == event.getEventType()) { maximizeDistTable(); } } @EventBusListenerMethod(scope = EventScope.SESSION) void onEvent(final TargetTableEvent event) { - if (event.getTargetComponentEvent() == TargetTableEvent.TargetComponentEvent.MINIMIZED) { + if (BaseEntityEventType.MINIMIZED == event.getEventType()) { minimizeTargetTable(); - } else if (event.getTargetComponentEvent() == TargetTableEvent.TargetComponentEvent.MAXIMIZED) { + } else if (BaseEntityEventType.MAXIMIZED == event.getEventType()) { maximizeTargetTable(); } } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/actionhistory/ActionHistoryComponent.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/actionhistory/ActionHistoryComponent.java index 908c8c18f..25448fbe1 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/actionhistory/ActionHistoryComponent.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/actionhistory/ActionHistoryComponent.java @@ -12,8 +12,8 @@ import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import org.eclipse.hawkbit.repository.model.Target; +import org.eclipse.hawkbit.ui.common.table.BaseEntityEventType; import org.eclipse.hawkbit.ui.management.event.TargetTableEvent; -import org.eclipse.hawkbit.ui.management.event.TargetTableEvent.TargetComponentEvent; import org.eclipse.hawkbit.ui.utils.SPUIDefinitions; import org.springframework.beans.factory.annotation.Autowired; import org.vaadin.spring.events.EventBus; @@ -62,9 +62,9 @@ public class ActionHistoryComponent extends VerticalLayout { @EventBusListenerMethod(scope = EventScope.SESSION) void onEvent(final TargetTableEvent targetUIEvent) { - if (targetUIEvent.getTargetComponentEvent() == TargetComponentEvent.SELECTED_TARGET) { + if (BaseEntityEventType.SELECTED_ENTITY == targetUIEvent.getEventType()) { setData(SPUIDefinitions.DATA_AVAILABLE); - UI.getCurrent().access(() -> populateActionHistoryDetails(targetUIEvent.getTarget())); + UI.getCurrent().access(() -> populateActionHistoryDetails(targetUIEvent.getEntity())); } } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/actionhistory/ActionHistoryTable.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/actionhistory/ActionHistoryTable.java index 3f7b7eee5..be1a96c37 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/actionhistory/ActionHistoryTable.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/actionhistory/ActionHistoryTable.java @@ -25,11 +25,11 @@ import org.eclipse.hawkbit.repository.model.ActionStatus; import org.eclipse.hawkbit.repository.model.ActionWithStatusCount; import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.ui.common.ConfirmationDialog; +import org.eclipse.hawkbit.ui.common.table.BaseEntityEventType; import org.eclipse.hawkbit.ui.components.SPUIComponentProvider; import org.eclipse.hawkbit.ui.management.event.ManagementUIEvent; import org.eclipse.hawkbit.ui.management.event.PinUnpinEvent; import org.eclipse.hawkbit.ui.management.event.TargetTableEvent; -import org.eclipse.hawkbit.ui.management.event.TargetTableEvent.TargetComponentEvent; import org.eclipse.hawkbit.ui.management.state.ManagementUIState; import org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil; import org.eclipse.hawkbit.ui.utils.I18N; @@ -296,8 +296,8 @@ public class ActionHistoryTable extends TreeTable implements Handler { * add distribution name to the item which will be displayed in the * table. The name should not exceed certain limit. */ - item.getItemProperty(SPUIDefinitions.ACTION_HIS_TBL_DIST).setValue(HawkbitCommonUtil - .getFormattedText(actionWithStatusCount.getDsName() + ":" + actionWithStatusCount.getDsVersion())); + item.getItemProperty(SPUIDefinitions.ACTION_HIS_TBL_DIST).setValue(actionWithStatusCount.getDsName() + ":" + + actionWithStatusCount.getDsVersion()); item.getItemProperty(SPUIDefinitions.ACTION_HIS_TBL_FORCED).setValue(action); /* Default no child */ @@ -442,8 +442,8 @@ public class ActionHistoryTable extends TreeTable implements Handler { childItem.getItemProperty(SPUIDefinitions.ACTION_HIS_TBL_ACTIVE_HIDDEN).setValue(""); childItem.getItemProperty(SPUIDefinitions.ACTION_HIS_TBL_DIST) - .setValue(HawkbitCommonUtil.getFormattedText(action.getDistributionSet().getName() + ":" - + action.getDistributionSet().getVersion())); + .setValue(action.getDistributionSet().getName() + ":" + + action.getDistributionSet().getVersion()); childItem.getItemProperty(SPUIDefinitions.ACTION_HIS_TBL_DATETIME) .setValue(SPDateTimeUtil.getFormattedDate(actionStatus.getCreatedAt())); @@ -855,11 +855,7 @@ public class ActionHistoryTable extends TreeTable implements Handler { } private void updateTargetAndDsTable() { - /* - * Update the target status in the Target table and update the color - * settings for DS in DS table. - */ - eventBus.publish(this, new TargetTableEvent(TargetComponentEvent.EDIT_TARGET, target)); + eventBus.publish(this, new TargetTableEvent(BaseEntityEventType.UPDATED_ENTITY, target)); updateDistributionTableStyle(); } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstable/DistributionAddUpdateWindowLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstable/DistributionAddUpdateWindowLayout.java index 9bbc1c05d..5d9304191 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstable/DistributionAddUpdateWindowLayout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstable/DistributionAddUpdateWindowLayout.java @@ -23,10 +23,10 @@ import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.DistributionSetType; import org.eclipse.hawkbit.repository.model.TenantMetaData; import org.eclipse.hawkbit.ui.common.DistributionSetTypeBeanQuery; +import org.eclipse.hawkbit.ui.common.table.BaseEntityEventType; import org.eclipse.hawkbit.ui.components.SPUIComponentProvider; import org.eclipse.hawkbit.ui.decorators.SPUIButtonStyleSmallNoBorder; import org.eclipse.hawkbit.ui.management.event.DistributionTableEvent; -import org.eclipse.hawkbit.ui.management.event.DistributionTableEvent.DistributionComponentEvent; import org.eclipse.hawkbit.ui.management.event.DragEvent; import org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil; import org.eclipse.hawkbit.ui.utils.I18N; @@ -145,11 +145,12 @@ public class DistributionAddUpdateWindowLayout extends VerticalLayout { setSizeUndefined(); addComponents(madatoryLabel, distsetTypeNameComboBox, distNameTextField, distVersionTextField, descTextArea, reqMigStepCheckbox); - + addComponent(buttonsLayout); setComponentAlignment(madatoryLabel, Alignment.MIDDLE_LEFT); - - } + distNameTextField.focus(); + + } /** * Create required UI components. @@ -260,8 +261,7 @@ public class DistributionAddUpdateWindowLayout extends VerticalLayout { notificationMessage.displaySuccess(i18n.get("message.new.dist.save.success", new Object[] { currentDS.getName(), currentDS.getVersion() })); // update table row+details layout - eventBus.publish(this, - new DistributionTableEvent(DistributionComponentEvent.EDIT_DISTRIBUTION, currentDS)); + eventBus.publish(this, new DistributionTableEvent(BaseEntityEventType.UPDATED_ENTITY, currentDS)); } catch (final EntityAlreadyExistsException entityAlreadyExistsException) { LOG.error("Update distribution failed {}", entityAlreadyExistsException); notificationMessage.displayValidationError( @@ -307,7 +307,7 @@ public class DistributionAddUpdateWindowLayout extends VerticalLayout { /* close the window */ closeThisWindow(); - eventBus.publish(this, new DistributionTableEvent(DistributionComponentEvent.ADD_DISTRIBUTION, newDist)); + eventBus.publish(this, new DistributionTableEvent(BaseEntityEventType.NEW_ENTITY, newDist)); } } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstable/DistributionBeanQuery.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstable/DistributionBeanQuery.java index 7b49ddcb2..7909a3850 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstable/DistributionBeanQuery.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstable/DistributionBeanQuery.java @@ -18,6 +18,7 @@ import org.eclipse.hawkbit.repository.DistributionSetFilter.DistributionSetFilte import org.eclipse.hawkbit.repository.DistributionSetManagement; import org.eclipse.hawkbit.repository.OffsetBasedPageRequest; import org.eclipse.hawkbit.repository.model.DistributionSet; +import org.eclipse.hawkbit.ui.common.UserDetailsFormatter; import org.eclipse.hawkbit.ui.components.ProxyDistribution; import org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil; import org.eclipse.hawkbit.ui.utils.SPDateTimeUtil; @@ -129,8 +130,8 @@ public class DistributionBeanQuery extends AbstractBeanQuery proxyDistribution.setCreatedDate(SPDateTimeUtil.getFormattedDate(distributionSet.getCreatedAt())); proxyDistribution.setLastModifiedDate(SPDateTimeUtil.getFormattedDate(distributionSet.getLastModifiedAt())); proxyDistribution.setDescription(distributionSet.getDescription()); - proxyDistribution.setCreatedByUser(HawkbitCommonUtil.getIMUser(distributionSet.getCreatedBy())); - proxyDistribution.setModifiedByUser(HawkbitCommonUtil.getIMUser(distributionSet.getLastModifiedBy())); + proxyDistribution.setCreatedByUser(UserDetailsFormatter.loadAndFormatCreatedBy(distributionSet)); + proxyDistribution.setModifiedByUser(UserDetailsFormatter.loadAndFormatLastModifiedBy(distributionSet)); proxyDistribution.setNameVersion( HawkbitCommonUtil.getFormattedNameVersion(distributionSet.getName(), distributionSet.getVersion())); proxyDistributions.add(proxyDistribution); diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstable/DistributionDetails.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstable/DistributionDetails.java index ecc4a26c6..81151b076 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstable/DistributionDetails.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstable/DistributionDetails.java @@ -8,23 +8,15 @@ */ package org.eclipse.hawkbit.ui.management.dstable; -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; - -import org.eclipse.hawkbit.repository.SpPermissionChecker; import org.eclipse.hawkbit.repository.model.DistributionSet; -import org.eclipse.hawkbit.ui.common.detailslayout.AbstractTableDetailsLayout; +import org.eclipse.hawkbit.ui.common.detailslayout.AbstractNamedVersionedEntityTableDetailsLayout; import org.eclipse.hawkbit.ui.common.detailslayout.SoftwareModuleDetailsTable; import org.eclipse.hawkbit.ui.common.tagdetails.DistributionTagToken; import org.eclipse.hawkbit.ui.components.SPUIComponentProvider; import org.eclipse.hawkbit.ui.management.event.DistributionTableEvent; -import org.eclipse.hawkbit.ui.management.event.DistributionTableEvent.DistributionComponentEvent; import org.eclipse.hawkbit.ui.management.state.ManagementUIState; -import org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil; -import org.eclipse.hawkbit.ui.utils.I18N; import org.eclipse.hawkbit.ui.utils.SPUIComponetIdProvider; import org.springframework.beans.factory.annotation.Autowired; -import org.vaadin.spring.events.EventBus; import org.vaadin.spring.events.EventScope; import org.vaadin.spring.events.annotation.EventBusListenerMethod; @@ -42,19 +34,10 @@ import com.vaadin.ui.Window; */ @SpringComponent @ViewScope -public class DistributionDetails extends AbstractTableDetailsLayout { +public class DistributionDetails extends AbstractNamedVersionedEntityTableDetailsLayout { private static final long serialVersionUID = 350360207334118826L; - @Autowired - private I18N i18n; - - @Autowired - private transient EventBus.SessionEventBus eventBus; - - @Autowired - private SpPermissionChecker permissionChecker; - @Autowired private ManagementUIState managementUIState; @@ -66,70 +49,37 @@ public class DistributionDetails extends AbstractTableDetailsLayout { private SoftwareModuleDetailsTable softwareModuleTable; - private Long dsId; - - private DistributionSet selectedDsModule; - - private UI ui; - @Override - @PostConstruct protected void init() { - eventBus.subscribe(this); softwareModuleTable = new SoftwareModuleDetailsTable(); - softwareModuleTable.init(i18n, false, permissionChecker, null, null, null); + softwareModuleTable.init(getI18n(), false, getPermissionChecker(), null, null, null); super.init(); - ui = UI.getCurrent(); - } - - @PreDestroy - void destroy() { - eventBus.unsubscribe(this); } @EventBusListenerMethod(scope = EventScope.SESSION) void onEvent(final DistributionTableEvent distributionTableEvent) { - if (distributionTableEvent.getDistributionComponentEvent() == DistributionComponentEvent.ON_VALUE_CHANGE - || distributionTableEvent - .getDistributionComponentEvent() == DistributionComponentEvent.EDIT_DISTRIBUTION) { - ui.access(() -> { - /** - * distributionTableEvent.getDistributionSet() is null when - * table has no data. - */ - if (distributionTableEvent.getDistributionSet() != null) { - selectedDsModule = distributionTableEvent.getDistributionSet(); - populateData(true); - } else { - populateData(false); - } - }); - } else if (distributionTableEvent.getDistributionComponentEvent() == DistributionComponentEvent.MINIMIZED) { - ui.access(() -> showLayout()); - } else if (distributionTableEvent.getDistributionComponentEvent() == DistributionComponentEvent.MAXIMIZED) { - ui.access(() -> hideLayout()); - } + onBaseEntityEvent(distributionTableEvent); } @Override protected String getDefaultCaption() { - return i18n.get("distribution.details.header"); + return getI18n().get("distribution.details.header"); } @Override protected void addTabs(final TabSheet detailsTab) { - detailsTab.addTab(createDetailsLayout(), i18n.get("caption.tab.details"), null); - detailsTab.addTab(createDescriptionLayout(), i18n.get("caption.tab.description"), null); - detailsTab.addTab(createSoftwareModuleTab(), i18n.get("caption.softwares.distdetail.tab"), null); - detailsTab.addTab(createTagsLayout(), i18n.get("caption.tags.tab"), null); - detailsTab.addTab(createLogLayout(), i18n.get("caption.logs.tab"), null); + detailsTab.addTab(createDetailsLayout(), getI18n().get("caption.tab.details"), null); + detailsTab.addTab(createDescriptionLayout(), getI18n().get("caption.tab.description"), null); + detailsTab.addTab(createSoftwareModuleTab(), getI18n().get("caption.softwares.distdetail.tab"), null); + detailsTab.addTab(createTagsLayout(), getI18n().get("caption.tags.tab"), null); + detailsTab.addTab(createLogLayout(), getI18n().get("caption.logs.tab"), null); } @Override protected void onEdit(final ClickEvent event) { final Window newDistWindow = distributionAddUpdateWindowLayout.getWindow(); - distributionAddUpdateWindowLayout.populateValuesOfDistribution(getDsId()); - newDistWindow.setCaption(i18n.get("caption.update.dist")); + distributionAddUpdateWindowLayout.populateValuesOfDistribution(getSelectedBaseEntityId()); + newDistWindow.setCaption(getI18n().get("caption.update.dist")); UI.getCurrent().addWindow(newDistWindow); newDistWindow.setVisible(Boolean.TRUE); } @@ -150,19 +100,9 @@ public class DistributionDetails extends AbstractTableDetailsLayout { return managementUIState.isDsTableMaximized(); } - @Override - protected void populateDetailsWidget() { - populateDetailsWidget(selectedDsModule); - } - - @Override - protected void clearDetails() { - populateDetailsWidget(null); - } - @Override protected Boolean hasEditPermission() { - return permissionChecker.hasUpdateDistributionPermission(); + return getPermissionChecker().hasUpdateDistributionPermission(); } @Override @@ -170,31 +110,11 @@ public class DistributionDetails extends AbstractTableDetailsLayout { return SPUIComponetIdProvider.DISTRIBUTION_DETAILS_TABSHEET; } - private void populateDetailsWidget(final DistributionSet dist) { - if (dist != null) { - setDsId(dist.getId()); - setName(getDefaultCaption(), HawkbitCommonUtil.getFormattedNameVersion(dist.getName(), dist.getVersion())); - populateDetails(dist); - populateDescription(dist); - populateLog(dist); - softwareModuleTable.populateModule(dist); - } else { - setDsId(null); - setName(getDefaultCaption(), HawkbitCommonUtil.SP_STRING_EMPTY); - populateDetails(null); - populateDescription(null); - softwareModuleTable.populateModule(null); - populateLog(null); - } - } + @Override + protected void populateDetailsWidget() { + softwareModuleTable.populateModule(getSelectedBaseEntity()); + populateDetails(getSelectedBaseEntity()); - private void populateLog(final DistributionSet ds) { - if (null != ds) { - updateLogLayout(getLogLayout(), ds.getLastModifiedAt(), ds.getLastModifiedBy(), ds.getCreatedAt(), - ds.getCreatedBy(), i18n); - } else { - updateLogLayout(getLogLayout(), null, HawkbitCommonUtil.SP_STRING_EMPTY, null, null, i18n); - } } private void populateDetails(final DistributionSet ds) { @@ -205,29 +125,21 @@ public class DistributionDetails extends AbstractTableDetailsLayout { } } - private void populateDescription(final DistributionSet ds) { - if (ds != null) { - updateDescriptionLayout(i18n.get("label.description"), ds.getDescription()); - } else { - updateDescriptionLayout(i18n.get("label.description"), null); - } - } - private void updateDistributionDetailsLayout(final String type, final Boolean isMigrationRequired) { final VerticalLayout detailsTabLayout = getDetailsLayout(); detailsTabLayout.removeAllComponents(); if (type != null) { - final Label typeLabel = SPUIComponentProvider.createNameValueLabel(i18n.get("label.dist.details.type"), + final Label typeLabel = SPUIComponentProvider.createNameValueLabel(getI18n().get("label.dist.details.type"), type); typeLabel.setId(SPUIComponetIdProvider.DETAILS_TYPE_LABEL_ID); detailsTabLayout.addComponent(typeLabel); } if (isMigrationRequired != null) { - detailsTabLayout.addComponent( - SPUIComponentProvider.createNameValueLabel(i18n.get("checkbox.dist.migration.required"), - isMigrationRequired.equals(Boolean.TRUE) ? i18n.get("label.yes") : i18n.get("label.no"))); + detailsTabLayout.addComponent(SPUIComponentProvider.createNameValueLabel( + getI18n().get("checkbox.dist.migration.required"), + isMigrationRequired.equals(Boolean.TRUE) ? getI18n().get("label.yes") : getI18n().get("label.no"))); } } @@ -244,14 +156,6 @@ public class DistributionDetails extends AbstractTableDetailsLayout { return tagsLayout; } - public Long getDsId() { - return dsId; - } - - public void setDsId(final Long dsId) { - this.dsId = dsId; - } - @Override protected String getDetailsHeaderCaptionId() { return SPUIComponetIdProvider.DISTRIBUTION_DETAILS_HEADER_LABEL_ID; diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstable/DistributionTable.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstable/DistributionTable.java index 4f4aa8b2f..0df1b0ea5 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstable/DistributionTable.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstable/DistributionTable.java @@ -11,27 +11,25 @@ package org.eclipse.hawkbit.ui.management.dstable; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; -import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; - +import org.apache.commons.lang3.StringUtils; import org.eclipse.hawkbit.repository.DistributionSetManagement; import org.eclipse.hawkbit.repository.SpPermissionChecker; import org.eclipse.hawkbit.repository.TargetManagement; import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.DistributionSetIdName; -import org.eclipse.hawkbit.repository.model.DistributionSetTagAssigmentResult; +import org.eclipse.hawkbit.repository.model.DistributionSetTagAssignmentResult; import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.repository.model.TargetIdName; +import org.eclipse.hawkbit.ui.common.table.AbstractNamedVersionTable; import org.eclipse.hawkbit.ui.common.table.AbstractTable; +import org.eclipse.hawkbit.ui.common.table.BaseEntityEventType; import org.eclipse.hawkbit.ui.components.SPUIComponentProvider; import org.eclipse.hawkbit.ui.management.event.DistributionTableEvent; -import org.eclipse.hawkbit.ui.management.event.DistributionTableEvent.DistributionComponentEvent; import org.eclipse.hawkbit.ui.management.event.DistributionTableFilterEvent; import org.eclipse.hawkbit.ui.management.event.DragEvent; import org.eclipse.hawkbit.ui.management.event.ManagementUIEvent; @@ -40,8 +38,6 @@ import org.eclipse.hawkbit.ui.management.event.PinUnpinEvent; import org.eclipse.hawkbit.ui.management.event.SaveActionWindowEvent; import org.eclipse.hawkbit.ui.management.state.ManagementUIState; import org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil; -import org.eclipse.hawkbit.ui.utils.I18N; -import org.eclipse.hawkbit.ui.utils.SPDateTimeUtil; import org.eclipse.hawkbit.ui.utils.SPUIComponetIdProvider; import org.eclipse.hawkbit.ui.utils.SPUIDefinitions; import org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions; @@ -52,7 +48,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.vaadin.addons.lazyquerycontainer.BeanQueryFactory; import org.vaadin.addons.lazyquerycontainer.LazyQueryContainer; import org.vaadin.addons.lazyquerycontainer.LazyQueryDefinition; -import org.vaadin.spring.events.EventBus; import org.vaadin.spring.events.EventScope; import org.vaadin.spring.events.annotation.EventBusListenerMethod; @@ -76,22 +71,16 @@ import com.vaadin.ui.UI; */ @SpringComponent @ViewScope -public class DistributionTable extends AbstractTable { +public class DistributionTable extends AbstractNamedVersionTable { private static final long serialVersionUID = -1928335256399519494L; - @Autowired - private I18N i18n; - @Autowired private SpPermissionChecker permissionChecker; @Autowired private UINotification notification; - @Autowired - private transient EventBus.SessionEventBus eventBus; - @Autowired private ManagementUIState managementUIState; @@ -111,17 +100,9 @@ public class DistributionTable extends AbstractTable { private Button distributinPinnedBtn; @Override - @PostConstruct protected void init() { super.init(); - eventBus.subscribe(this); notAllowedMsg = i18n.get("message.action.not.allowed"); - setNoDataAvailable(); - } - - @PreDestroy - void destroy() { - eventBus.unsubscribe(this); } /** @@ -151,13 +132,12 @@ public class DistributionTable extends AbstractTable { @EventBusListenerMethod(scope = EventScope.SESSION) void onEvent(final DistributionTableEvent event) { - if (event.getDistributionComponentEvent() == DistributionComponentEvent.MINIMIZED) { - UI.getCurrent().access(() -> applyMinTableSettings()); - } else if (event.getDistributionComponentEvent() == DistributionComponentEvent.MAXIMIZED) { - UI.getCurrent().access(() -> applyMaxTableSettings()); - } else if (event.getDistributionComponentEvent() == DistributionComponentEvent.EDIT_DISTRIBUTION) { - UI.getCurrent().access(() -> updateDistributionInTable(event.getDistributionSet())); + onBaseEntityEvent(event); + if (BaseEntityEventType.UPDATED_ENTITY != event.getEventType()) { + return; } + UI.getCurrent().access(() -> updateDistributionInTable(event.getEntity())); + } @EventBusListenerMethod(scope = EventScope.SESSION) @@ -194,24 +174,11 @@ public class DistributionTable extends AbstractTable { }); } - /* - * (non-Javadoc) - * - * @see - * org.eclipse.hawkbit.server.ui.common.table.AbstractTable#getTableId() - */ @Override protected String getTableId() { return SPUIComponetIdProvider.DIST_TABLE_ID; } - /* - * (non-Javadoc) - * - * @see - * org.eclipse.hawkbit.server.ui.common.table.AbstractTable#createContainer( - * ) - */ @Override protected Container createContainer() { final Map queryConfiguration = prepareQueryConfigFilters(); @@ -272,31 +239,18 @@ public class DistributionTable extends AbstractTable { } @Override - protected void onValueChange() { - eventBus.publish(this, DragEvent.HIDE_DROP_HINT); - final Set values = HawkbitCommonUtil.getSelectedDSDetails(this); - DistributionSetIdName value = null; - if (values != null && !values.isEmpty()) { - final Iterator iterator = values.iterator(); + protected DistributionSet findEntityByTableValue(final DistributionSetIdName lastSelectedId) { + return distributionSetManagement.findDistributionSetByIdWithDetails(lastSelectedId.getId()); + } - while (iterator.hasNext()) { - value = iterator.next(); - } - - if (null != value) { - managementUIState.setSelectedDsIdName(values); - managementUIState.setLastSelectedDsIdName(value); - final DistributionSet lastSelectedDistSet = distributionSetManagement - .findDistributionSetByIdWithDetails(value.getId()); - eventBus.publish(this, - new DistributionTableEvent(DistributionComponentEvent.ON_VALUE_CHANGE, lastSelectedDistSet)); - } - } else { - managementUIState.setSelectedDsIdName(null); - managementUIState.setLastSelectedDsIdName(null); - eventBus.publish(this, new DistributionTableEvent(DistributionComponentEvent.ON_VALUE_CHANGE, null)); - } + @Override + protected void publishEntityAfterValueChange(final DistributionSet selectedLastEntity) { + eventBus.publish(this, new DistributionTableEvent(BaseEntityEventType.SELECTED_ENTITY, selectedLastEntity)); + } + @Override + protected ManagementUIState getManagmentEntityState() { + return managementUIState; } @Override @@ -306,7 +260,17 @@ public class DistributionTable extends AbstractTable { @Override protected List getTableVisibleColumns() { - return HawkbitCommonUtil.getTableVisibleColumns(isMaximized(), true, i18n); + final List columnList = super.getTableVisibleColumns(); + if (isMaximized()) { + return columnList; + } + columnList.add(new TableColumn(SPUILabelDefinitions.PIN_COLUMN, StringUtils.EMPTY, 0.1F)); + return columnList; + } + + @Override + protected float getColumnNameMinimizedSize() { + return 0.7F; } @Override @@ -345,7 +309,7 @@ public class DistributionTable extends AbstractTable { private void assignDsTag(final DragAndDropEvent event) { final com.vaadin.event.dd.TargetDetails taregtDet = event.getTargetDetails(); final Table distTable = (Table) taregtDet.getTarget(); - final Set distsSelected = HawkbitCommonUtil.getSelectedDSDetails(distTable); + final Set distsSelected = getTableValue(distTable); final Set distList = new HashSet<>(); final AbstractSelectTargetDetails dropData = (AbstractSelectTargetDetails) event.getTargetDetails(); @@ -360,10 +324,10 @@ public class DistributionTable extends AbstractTable { final String distTagName = HawkbitCommonUtil.removePrefix(event.getTransferable().getSourceComponent().getId(), SPUIDefinitions.DISTRIBUTION_TAG_ID_PREFIXS); - final DistributionSetTagAssigmentResult result = distributionSetManagement.toggleTagAssignment(distList, + final DistributionSetTagAssignmentResult result = distributionSetManagement.toggleTagAssignment(distList, distTagName); - notification.displaySuccess(HawkbitCommonUtil.getDistributionTagAssignmentMsg(distTagName, result, i18n)); + notification.displaySuccess(HawkbitCommonUtil.createAssignmentMessage(distTagName, result, i18n)); if (result.getAssigned() >= 1 && managementUIState.getDistributionTableFilters().isNoTagSelected()) { refreshFilter(); } @@ -387,17 +351,12 @@ public class DistributionTable extends AbstractTable { } } + @SuppressWarnings("unchecked") private void assignTargetToDs(final DragAndDropEvent event) { final TableTransferable transferable = (TableTransferable) event.getTransferable(); - final Table source = transferable.getSourceComponent(); - final Set targetsSelected = HawkbitCommonUtil.getSelectedTargetDetails(source); - final Set targetDetailsList = new HashSet<>(); - - if (!targetsSelected.contains(transferable.getData("itemId"))) { - targetDetailsList.add((TargetIdName) transferable.getData("itemId")); - } else { - targetDetailsList.addAll(targetsSelected); - } + final AbstractTable source = (AbstractTable) transferable + .getSourceComponent(); + final Set targetDetailsList = source.getDeletedEntityByTransferable(transferable); final AbstractSelectTargetDetails dropData = (AbstractSelectTargetDetails) event.getTargetDetails(); @@ -502,17 +461,7 @@ public class DistributionTable extends AbstractTable { private void updateDistributionInTable(final DistributionSet editedDs) { final Item item = getContainerDataSource() .getItem(new DistributionSetIdName(editedDs.getId(), editedDs.getName(), editedDs.getVersion())); - item.getItemProperty(SPUILabelDefinitions.VAR_NAME).setValue(editedDs.getName()); - item.getItemProperty(SPUILabelDefinitions.VAR_VERSION).setValue(editedDs.getVersion()); - item.getItemProperty(SPUILabelDefinitions.VAR_CREATED_BY) - .setValue(HawkbitCommonUtil.getIMUser(editedDs.getCreatedBy())); - item.getItemProperty(SPUILabelDefinitions.VAR_CREATED_DATE) - .setValue(SPDateTimeUtil.getFormattedDate(editedDs.getCreatedAt())); - item.getItemProperty(SPUILabelDefinitions.VAR_LAST_MODIFIED_BY) - .setValue(HawkbitCommonUtil.getIMUser(editedDs.getLastModifiedBy())); - item.getItemProperty(SPUILabelDefinitions.VAR_LAST_MODIFIED_DATE) - .setValue(SPDateTimeUtil.getFormattedDate(editedDs.getLastModifiedAt())); - item.getItemProperty(SPUILabelDefinitions.VAR_DESC).setValue(editedDs.getDescription()); + updateEntity(editedDs, item); } private void restoreDistributionTableStyle() { @@ -564,7 +513,7 @@ public class DistributionTable extends AbstractTable { .getItemProperty(SPUILabelDefinitions.VAR_DIST_ID_NAME).getValue(); final Button pinBtn = getPinBtn(itemId, dist.getName(), dist.getVersion()); saveDistributionPinnedBtn(pinBtn); - pinBtn.addClickListener(event -> addPinClickListener(event)); + pinBtn.addClickListener(this::addPinClickListener); rePinDistribution(pinBtn, dist.getId()); return pinBtn; } @@ -703,12 +652,10 @@ public class DistributionTable extends AbstractTable { this.distributinPinnedBtn = distributinPinnedBtn; } - private void setNoDataAvailable() { - final int size = getContainerDataSource().size(); - if (size == 0) { - managementUIState.setNoDataAvailableDistribution(true); - } else { - managementUIState.setNoDataAvailableDistribution(false); - } + @Override + protected void setDataAvailable(final boolean available) { + managementUIState.setNoDataAvailableDistribution(!available); + } + } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstable/DistributionTableHeader.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstable/DistributionTableHeader.java index d2ac628a8..2ccbac961 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstable/DistributionTableHeader.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstable/DistributionTableHeader.java @@ -8,21 +8,15 @@ */ package org.eclipse.hawkbit.ui.management.dstable; -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; - -import org.eclipse.hawkbit.repository.SpPermissionChecker; import org.eclipse.hawkbit.ui.common.table.AbstractTableHeader; +import org.eclipse.hawkbit.ui.common.table.BaseEntityEventType; import org.eclipse.hawkbit.ui.management.event.DistributionTableEvent; -import org.eclipse.hawkbit.ui.management.event.DistributionTableEvent.DistributionComponentEvent; import org.eclipse.hawkbit.ui.management.event.DistributionTableFilterEvent; import org.eclipse.hawkbit.ui.management.event.DragEvent; import org.eclipse.hawkbit.ui.management.event.ManagementUIEvent; import org.eclipse.hawkbit.ui.management.state.ManagementUIState; -import org.eclipse.hawkbit.ui.utils.I18N; import org.eclipse.hawkbit.ui.utils.SPUIComponetIdProvider; import org.springframework.beans.factory.annotation.Autowired; -import org.vaadin.spring.events.EventBus; import org.vaadin.spring.events.EventScope; import org.vaadin.spring.events.annotation.EventBusListenerMethod; @@ -43,33 +37,12 @@ import com.vaadin.ui.Window; public class DistributionTableHeader extends AbstractTableHeader { private static final long serialVersionUID = 7597766804650170127L; - @Autowired - private I18N i18n; - - @Autowired - private SpPermissionChecker permChecker; - - @Autowired - private transient EventBus.SessionEventBus eventbus; - @Autowired private ManagementUIState managementUIState; @Autowired private DistributionAddUpdateWindowLayout distributionAddUpdateWindowLayout; - @Override - @PostConstruct - protected void init() { - super.init(); - eventbus.subscribe(this); - } - - @PreDestroy - void destroy() { - eventbus.unsubscribe(this); - } - @EventBusListenerMethod(scope = EventScope.SESSION) void onEvent(final ManagementUIEvent event) { if (event == ManagementUIEvent.HIDE_DISTRIBUTION_TAG_LAYOUT) { @@ -154,13 +127,13 @@ public class DistributionTableHeader extends AbstractTableHeader { @Override public void maximizeTable() { managementUIState.setDsTableMaximized(Boolean.TRUE); - eventbus.publish(this, new DistributionTableEvent(DistributionComponentEvent.MAXIMIZED, null)); + eventbus.publish(this, new DistributionTableEvent(BaseEntityEventType.MAXIMIZED, null)); } @Override public void minimizeTable() { managementUIState.setDsTableMaximized(Boolean.FALSE); - eventbus.publish(this, new DistributionTableEvent(DistributionComponentEvent.MINIMIZED, null)); + eventbus.publish(this, new DistributionTableEvent(BaseEntityEventType.MINIMIZED, null)); } @Override diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstag/CreateUpdateDistributionTagLayoutWindow.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstag/CreateUpdateDistributionTagLayoutWindow.java index 210509623..4d63753fe 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstag/CreateUpdateDistributionTagLayoutWindow.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstag/CreateUpdateDistributionTagLayoutWindow.java @@ -43,10 +43,6 @@ import com.vaadin.ui.themes.ValoTheme; @SpringComponent @VaadinSessionScope public class CreateUpdateDistributionTagLayoutWindow extends CreateUpdateTagLayout { - - /** - * - */ private static final long serialVersionUID = 444276149954167545L; @Autowired @@ -288,16 +284,22 @@ public class CreateUpdateDistributionTagLayoutWindow extends CreateUpdateTagLayo } @EventBusListenerMethod(scope = EventScope.SESSION) + // Exception squid:S1172 - event not needed + @SuppressWarnings({ "squid:S1172" }) void onDistributionSetTagCreatedBulkEvent(final DistributionSetTagCreatedBulkEvent event) { populateTagNameCombo(); } @EventBusListenerMethod(scope = EventScope.SESSION) + // Exception squid:S1172 - event not needed + @SuppressWarnings({ "squid:S1172" }) void onDistributionSetTagDeletedEvent(final DistributionSetTagDeletedEvent event) { populateTagNameCombo(); } @EventBusListenerMethod(scope = EventScope.SESSION) + // Exception squid:S1172 - event not needed + @SuppressWarnings({ "squid:S1172" }) void onDistributionSetTagUpdateEvent(final DistributionSetTagUpdateEvent event) { populateTagNameCombo(); } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstag/DistributionTagButtons.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstag/DistributionTagButtons.java index 98c48d235..934d9c4c7 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstag/DistributionTagButtons.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstag/DistributionTagButtons.java @@ -11,12 +11,9 @@ package org.eclipse.hawkbit.ui.management.dstag; import java.util.HashMap; import java.util.Map; -import javax.annotation.PreDestroy; - import org.eclipse.hawkbit.eventbus.event.DistributionSetTagCreatedBulkEvent; import org.eclipse.hawkbit.eventbus.event.DistributionSetTagDeletedEvent; import org.eclipse.hawkbit.eventbus.event.DistributionSetTagUpdateEvent; -import org.eclipse.hawkbit.repository.TagManagement; import org.eclipse.hawkbit.repository.model.DistributionSetTag; import org.eclipse.hawkbit.ui.common.filterlayout.AbstractFilterButtonClickBehaviour; import org.eclipse.hawkbit.ui.common.filterlayout.AbstractFilterButtons; @@ -32,7 +29,6 @@ import org.eclipse.hawkbit.ui.utils.SPUIStyleDefinitions; import org.springframework.beans.factory.annotation.Autowired; import org.vaadin.addons.lazyquerycontainer.BeanQueryFactory; import org.vaadin.addons.lazyquerycontainer.LazyQueryContainer; -import org.vaadin.spring.events.EventBus; import org.vaadin.spring.events.EventScope; import org.vaadin.spring.events.annotation.EventBusListenerMethod; @@ -52,15 +48,9 @@ public class DistributionTagButtons extends AbstractFilterButtons { private static final long serialVersionUID = -8151483237450892057L; - @Autowired - private transient EventBus.SessionEventBus eventBus; - @Autowired private DistributionTagDropEvent spDistTagDropEvent; - @Autowired - private transient TagManagement tagMgmtService; - @Autowired private ManagementUIState managementUIState; @@ -68,25 +58,25 @@ public class DistributionTagButtons extends AbstractFilterButtons { public void init(final AbstractFilterButtonClickBehaviour filterButtonClickBehaviour) { super.init(filterButtonClickBehaviour); addNewTag(new DistributionSetTag("NO TAG")); - eventBus.subscribe(this); - } - - @PreDestroy - void destroy() { - eventBus.unsubscribe(this); } @EventBusListenerMethod(scope = EventScope.SESSION) + // Exception squid:S1172 - event not needed + @SuppressWarnings({ "squid:S1172" }) void onDistributionSetTagCreatedBulkEvent(final DistributionSetTagCreatedBulkEvent event) { refreshTagTable(); } @EventBusListenerMethod(scope = EventScope.SESSION) + // Exception squid:S1172 - event not needed + @SuppressWarnings({ "squid:S1172" }) void onDistributionSetTagDeletedEvent(final DistributionSetTagDeletedEvent event) { refreshTagTable(); } @EventBusListenerMethod(scope = EventScope.SESSION) + // Exception squid:S1172 - event not needed + @SuppressWarnings({ "squid:S1172" }) void onDistributionSetTagUpdateEvent(final DistributionSetTagUpdateEvent event) { refreshTagTable(); } @@ -121,10 +111,9 @@ public class DistributionTagButtons extends AbstractFilterButtons { } @Override - protected boolean isClickedByDefault(final Long buttonId) { - final DistributionSetTag dsTagObject = tagMgmtService.findDistributionSetTagById(buttonId); + protected boolean isClickedByDefault(final String tagName) { return null != managementUIState.getDistributionTableFilters().getDistSetTags() - && managementUIState.getDistributionTableFilters().getDistSetTags().contains(dsTagObject.getName()); + && managementUIState.getDistributionTableFilters().getDistSetTags().contains(tagName); } @Override diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstag/DistributionTagHeader.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstag/DistributionTagHeader.java index 2d58849dc..df9253bdb 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstag/DistributionTagHeader.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/dstag/DistributionTagHeader.java @@ -10,14 +10,12 @@ package org.eclipse.hawkbit.ui.management.dstag; import javax.annotation.PostConstruct; -import org.eclipse.hawkbit.repository.SpPermissionChecker; import org.eclipse.hawkbit.ui.common.filterlayout.AbstractFilterHeader; import org.eclipse.hawkbit.ui.management.event.ManagementUIEvent; import org.eclipse.hawkbit.ui.management.state.ManagementUIState; import org.eclipse.hawkbit.ui.utils.I18N; import org.eclipse.hawkbit.ui.utils.SPUIComponetIdProvider; import org.springframework.beans.factory.annotation.Autowired; -import org.vaadin.spring.events.EventBus; import com.vaadin.spring.annotation.SpringComponent; import com.vaadin.spring.annotation.ViewScope; @@ -38,12 +36,6 @@ public class DistributionTagHeader extends AbstractFilterHeader { @Autowired private I18N i18n; - @Autowired - private SpPermissionChecker permChecker; - - @Autowired - private transient EventBus.SessionEventBus eventbus; - @Autowired private ManagementUIState managementUIState; @@ -90,7 +82,7 @@ public class DistributionTagHeader extends AbstractFilterHeader { @Override protected void hideFilterButtonLayout() { managementUIState.setDistTagFilterClosed(true); - eventbus.publish(this, ManagementUIEvent.HIDE_DISTRIBUTION_TAG_LAYOUT); + eventBus.publish(this, ManagementUIEvent.HIDE_DISTRIBUTION_TAG_LAYOUT); } @Override diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/event/DistributionTableEvent.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/event/DistributionTableEvent.java index 7690bf109..14eeaf26e 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/event/DistributionTableEvent.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/event/DistributionTableEvent.java @@ -9,50 +9,26 @@ package org.eclipse.hawkbit.ui.management.event; import org.eclipse.hawkbit.repository.model.DistributionSet; +import org.eclipse.hawkbit.ui.common.table.BaseEntityEvent; +import org.eclipse.hawkbit.ui.common.table.BaseEntityEventType; /** * * * */ -public class DistributionTableEvent { +public class DistributionTableEvent extends BaseEntityEvent { /** - * - * + * Constructor. + * + * @param eventType + * the event type + * @param entity + * the distribution set */ - public enum DistributionComponentEvent { - ADD_DISTRIBUTION, EDIT_DISTRIBUTION, DELETE_DISTRIBUTION, ON_VALUE_CHANGE, MAXIMIZED, MINIMIZED - } - - private DistributionComponentEvent distributionComponentEvent; - - private DistributionSet distributionSet; - - /** - * @param distributionComponentEvent - * @param distributionSet - */ - public DistributionTableEvent(final DistributionComponentEvent distributionComponentEvent, - final DistributionSet distributionSet) { - this.distributionComponentEvent = distributionComponentEvent; - this.distributionSet = distributionSet; - } - - public DistributionComponentEvent getDistributionComponentEvent() { - return distributionComponentEvent; - } - - public void setDistributionComponentEvent(final DistributionComponentEvent distributionComponentEvent) { - this.distributionComponentEvent = distributionComponentEvent; - } - - public DistributionSet getDistributionSet() { - return distributionSet; - } - - public void setDistributionSet(final DistributionSet distributionSet) { - this.distributionSet = distributionSet; + public DistributionTableEvent(final BaseEntityEventType eventType, final DistributionSet entity) { + super(eventType, entity); } } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/event/DistributionTagDropEvent.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/event/DistributionTagDropEvent.java index 21013a55e..2b6acbf68 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/event/DistributionTagDropEvent.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/event/DistributionTagDropEvent.java @@ -8,7 +8,6 @@ */ package org.eclipse.hawkbit.ui.management.event; -import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; @@ -16,7 +15,8 @@ import java.util.stream.Collectors; import org.eclipse.hawkbit.repository.DistributionSetManagement; import org.eclipse.hawkbit.repository.SpPermissionChecker; import org.eclipse.hawkbit.repository.model.DistributionSetIdName; -import org.eclipse.hawkbit.repository.model.DistributionSetTagAssigmentResult; +import org.eclipse.hawkbit.repository.model.DistributionSetTagAssignmentResult; +import org.eclipse.hawkbit.ui.common.table.AbstractTable; import org.eclipse.hawkbit.ui.management.state.DistributionTableFilters; import org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil; import org.eclipse.hawkbit.ui.utils.I18N; @@ -68,8 +68,6 @@ public class DistributionTagDropEvent implements DropHandler { @Autowired private ManagementViewAcceptCriteria managementViewAcceptCriteria; - private static final String ITEMID = "itemId"; - @Override public void drop(final DragAndDropEvent event) { if (validate(event) && isNoTagAssigned(event)) { @@ -132,25 +130,22 @@ public class DistributionTagDropEvent implements DropHandler { final com.vaadin.event.dd.TargetDetails targetDetails = event.getTargetDetails(); final TableTransferable transferable = (TableTransferable) event.getTransferable(); - final Table source = transferable.getSourceComponent(); - @SuppressWarnings("unchecked") - final Set distSelected = (Set) source.getValue(); - final Set distributionList = new HashSet<>(); - if (!distSelected.contains(transferable.getData(ITEMID))) { - distributionList.add(((DistributionSetIdName) transferable.getData(ITEMID)).getId()); - } else { - distributionList.addAll(distSelected.stream().map(t -> t.getId()).collect(Collectors.toList())); - } + final AbstractTable source = (AbstractTable) transferable + .getSourceComponent(); + + final Set distSelected = source.getDeletedEntityByTransferable(transferable); + final Set distributionList = distSelected.stream().map(entity -> entity.getId()) + .collect(Collectors.toSet()); final String distTagName = HawkbitCommonUtil.removePrefix(targetDetails.getTarget().getId(), SPUIDefinitions.DISTRIBUTION_TAG_ID_PREFIXS); final List tagsClickedList = distFilterParameters.getDistSetTags(); - final DistributionSetTagAssigmentResult result = distributionSetManagement.toggleTagAssignment(distributionList, - distTagName); + final DistributionSetTagAssignmentResult result = distributionSetManagement + .toggleTagAssignment(distributionList, distTagName); - notification.displaySuccess(HawkbitCommonUtil.getDistributionTagAssignmentMsg(distTagName, result, i18n)); + notification.displaySuccess(HawkbitCommonUtil.createAssignmentMessage(distTagName, result, i18n)); if (result.getUnassigned() >= 1 && !tagsClickedList.isEmpty()) { eventBus.publish(this, TargetFilterEvent.FILTER_BY_TAG); } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/event/ManagementViewAcceptCriteria.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/event/ManagementViewAcceptCriteria.java index 1c44014e8..ddc2c9c1d 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/event/ManagementViewAcceptCriteria.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/event/ManagementViewAcceptCriteria.java @@ -16,10 +16,6 @@ import java.util.Map; import org.eclipse.hawkbit.ui.common.AbstractAcceptCriteria; import org.eclipse.hawkbit.ui.utils.SPUIComponetIdProvider; import org.eclipse.hawkbit.ui.utils.SPUIDefinitions; -import org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions; -import org.eclipse.hawkbit.ui.utils.UINotification; -import org.springframework.beans.factory.annotation.Autowired; -import org.vaadin.spring.events.EventBus; import com.vaadin.spring.annotation.SpringComponent; import com.vaadin.spring.annotation.ViewScope; @@ -41,29 +37,6 @@ public class ManagementViewAcceptCriteria extends AbstractAcceptCriteria { private static final Map DROP_HINTS_CONFIGS = createDropHintConfigurations(); - @Autowired - private transient UINotification uiNotification; - - @Autowired - private transient EventBus.SessionEventBus eventBus; - - @Override - protected void analyseDragComponent(final Component compsource) { - final String sourceID = getComponentId(compsource); - final Object event = DROP_HINTS_CONFIGS.get(sourceID); - eventBus.publish(this, event); - } - - @Override - protected void hideDropHints() { - eventBus.publish(this, DragEvent.HIDE_DROP_HINT); - } - - @Override - protected void invalidDrop() { - uiNotification.displayValidationError(SPUILabelDefinitions.ACTION_NOT_ALLOWED); - } - @Override protected String getComponentId(final Component component) { String id = component.getId(); @@ -80,11 +53,6 @@ public class ManagementViewAcceptCriteria extends AbstractAcceptCriteria { return DROP_HINTS_CONFIGS; } - @Override - protected void publishDragStartEvent(final Object event) { - eventBus.publish(this, event); - } - @Override protected Map> getDropConfigurations() { return DROP_CONFIGS; diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/event/TargetAddUpdateWindowEvent.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/event/TargetAddUpdateWindowEvent.java index f1bc5d8ec..cf2661c60 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/event/TargetAddUpdateWindowEvent.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/event/TargetAddUpdateWindowEvent.java @@ -9,7 +9,8 @@ package org.eclipse.hawkbit.ui.management.event; import org.eclipse.hawkbit.repository.model.Target; -import org.eclipse.hawkbit.ui.management.event.TargetTableEvent.TargetComponentEvent; +import org.eclipse.hawkbit.ui.common.table.BaseEntityEvent; +import org.eclipse.hawkbit.ui.common.table.BaseEntityEventType; /** * @@ -17,34 +18,18 @@ import org.eclipse.hawkbit.ui.management.event.TargetTableEvent.TargetComponentE * * */ -public class TargetAddUpdateWindowEvent { - - private final TargetComponentEvent targetComponentEvent; - - private final Target target; +public class TargetAddUpdateWindowEvent extends BaseEntityEvent { /** + * Constructor. + * * @param eventType * the event type - * @param target - * the target which has been created or modified + * @param entity + * the entity */ - public TargetAddUpdateWindowEvent(final TargetComponentEvent eventType, final Target target) { - this.targetComponentEvent = eventType; - this.target = target; + public TargetAddUpdateWindowEvent(final BaseEntityEventType eventType, final Target entity) { + super(eventType, entity); } - /** - * @return the targetComponentEvent - */ - public TargetComponentEvent getTargetComponentEvent() { - return targetComponentEvent; - } - - /** - * @return the target - */ - public Target getTarget() { - return target; - } } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/event/TargetTableEvent.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/event/TargetTableEvent.java index 1706361f0..04dd917a9 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/event/TargetTableEvent.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/event/TargetTableEvent.java @@ -9,77 +9,51 @@ package org.eclipse.hawkbit.ui.management.event; import org.eclipse.hawkbit.repository.model.Target; -import org.eclipse.hawkbit.repository.model.TargetIdName; +import org.eclipse.hawkbit.ui.common.table.BaseEntityEvent; +import org.eclipse.hawkbit.ui.common.table.BaseEntityEventType; /** * * * */ -public class TargetTableEvent { +public class TargetTableEvent extends BaseEntityEvent { /** * Target table components events. * */ public enum TargetComponentEvent { - REFRESH_TARGETS, EDIT_TARGET, DELETE_TARGET, SELECTED_TARGET, MAXIMIZED, MINIMIZED, SELLECT_ALL, BULK_TARGET_CREATED, BULK_UPLOAD_COMPLETED, BULK_TARGET_UPLOAD_STARTED, BULK_UPLOAD_PROCESS_STARTED + REFRESH_TARGETS, SELLECT_ALL, BULK_TARGET_CREATED, BULK_UPLOAD_COMPLETED, BULK_TARGET_UPLOAD_STARTED, BULK_UPLOAD_PROCESS_STARTED } private TargetComponentEvent targetComponentEvent; - private Target target; - - private TargetIdName targetIdName; + /** + * Constructor. + * + * @param eventType + * the event type. + * @param entity + * the entity + */ + public TargetTableEvent(final BaseEntityEventType eventType, final Target entity) { + super(eventType, entity); + } /** + * The component event. + * * @param targetComponentEvent + * the target component event. */ public TargetTableEvent(final TargetComponentEvent targetComponentEvent) { - super(); + super(null, null); this.targetComponentEvent = targetComponentEvent; } - /** - * @param targetComponentEvent - * @param target - */ - public TargetTableEvent(final TargetComponentEvent targetComponentEvent, final Target target) { - this(targetComponentEvent); - this.target = target; - } - - /** - * @param targetComponentEvent - * @param targetIdName - */ - public TargetTableEvent(final TargetComponentEvent targetComponentEvent, final TargetIdName targetIdName) { - this(targetComponentEvent); - this.targetIdName = targetIdName; - } - public TargetComponentEvent getTargetComponentEvent() { return targetComponentEvent; } - public void setTargetComponentEvent(final TargetComponentEvent targetComponentEvent) { - this.targetComponentEvent = targetComponentEvent; - } - - public Target getTarget() { - return target; - } - - public void setTarget(final Target target) { - this.target = target; - } - - public TargetIdName getTargetIdName() { - return targetIdName; - } - - public void setTargetIdName(final TargetIdName targetIdName) { - this.targetIdName = targetIdName; - } - } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/footer/CountMessageLabel.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/footer/CountMessageLabel.java index 7ff9f53e4..ed002defb 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/footer/CountMessageLabel.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/footer/CountMessageLabel.java @@ -95,8 +95,8 @@ public class CountMessageLabel extends Label { @EventBusListenerMethod(scope = EventScope.SESSION) void onEvent(final TargetTableEvent event) { - if (event.getTargetComponentEvent() == TargetTableEvent.TargetComponentEvent.SELLECT_ALL - || event.getTargetComponentEvent() == TargetComponentEvent.REFRESH_TARGETS) { + if (TargetTableEvent.TargetComponentEvent.SELLECT_ALL == event.getTargetComponentEvent() + || TargetComponentEvent.REFRESH_TARGETS == event.getTargetComponentEvent()) { displayTargetCountStatus(); } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/footer/DeleteActionsLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/footer/DeleteActionsLayout.java index 1786429a1..ad537e626 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/footer/DeleteActionsLayout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/footer/DeleteActionsLayout.java @@ -8,17 +8,13 @@ */ package org.eclipse.hawkbit.ui.management.footer; -import java.util.HashSet; import java.util.Set; -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; - -import org.eclipse.hawkbit.repository.SpPermissionChecker; import org.eclipse.hawkbit.repository.TagManagement; import org.eclipse.hawkbit.repository.model.DistributionSetIdName; import org.eclipse.hawkbit.repository.model.TargetIdName; import org.eclipse.hawkbit.ui.common.footer.AbstractDeleteActionsLayout; +import org.eclipse.hawkbit.ui.common.table.AbstractTable; import org.eclipse.hawkbit.ui.management.event.BulkUploadPopupEvent; import org.eclipse.hawkbit.ui.management.event.DragEvent; import org.eclipse.hawkbit.ui.management.event.ManagementUIEvent; @@ -28,12 +24,9 @@ import org.eclipse.hawkbit.ui.management.event.TargetTableEvent; import org.eclipse.hawkbit.ui.management.event.TargetTableEvent.TargetComponentEvent; import org.eclipse.hawkbit.ui.management.state.ManagementUIState; import org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil; -import org.eclipse.hawkbit.ui.utils.I18N; import org.eclipse.hawkbit.ui.utils.SPUIComponetIdProvider; import org.eclipse.hawkbit.ui.utils.SPUIDefinitions; -import org.eclipse.hawkbit.ui.utils.UINotification; import org.springframework.beans.factory.annotation.Autowired; -import org.vaadin.spring.events.EventBus; import org.vaadin.spring.events.EventScope; import org.vaadin.spring.events.annotation.EventBusListenerMethod; @@ -56,17 +49,6 @@ import com.vaadin.ui.UI; public class DeleteActionsLayout extends AbstractDeleteActionsLayout { private static final long serialVersionUID = -8112907467821886253L; - @Autowired - private I18N i18n; - - @Autowired - private SpPermissionChecker permChecker; - - @Autowired - private transient EventBus.SessionEventBus eventBus; - - @Autowired - private transient UINotification notification; @Autowired private transient TagManagement tagManagementService; @@ -83,18 +65,6 @@ public class DeleteActionsLayout extends AbstractDeleteActionsLayout { @Autowired private CountMessageLabel countMessageLabel; - @Override - @PostConstruct - protected void init() { - super.init(); - eventBus.subscribe(this); - } - - @PreDestroy - void destroy() { - eventBus.unsubscribe(this); - } - @EventBusListenerMethod(scope = EventScope.SESSION) void onEvent(final ManagementUIEvent event) { if (event == ManagementUIEvent.UPDATE_COUNT) { @@ -226,26 +196,11 @@ public class DeleteActionsLayout extends AbstractDeleteActionsLayout { return true; } - @Override - protected String getNoActionsButtonLabel() { - return i18n.get("button.no.actions"); - } - - @Override - protected String getActionsButtonLabel() { - return i18n.get("button.actions"); - } - @Override protected void restoreActionCount() { updateActionCount(); } - @Override - protected String getUnsavedActionsWindowCaption() { - return i18n.get("caption.save.window"); - } - @Override protected void unsavedActionsWindowClosed() { final String message = manangementConfirmationWindowLayout.getConsolidatedMessage(); @@ -256,7 +211,7 @@ public class DeleteActionsLayout extends AbstractDeleteActionsLayout { @Override protected Component getUnsavedActionsWindowContent() { - manangementConfirmationWindowLayout.init(); + manangementConfirmationWindowLayout.initialize(); return manangementConfirmationWindowLayout; } @@ -302,14 +257,9 @@ public class DeleteActionsLayout extends AbstractDeleteActionsLayout { } private void addInDeleteDistributionList(final Table sourceTable, final TableTransferable transferable) { - final Set distSelected = HawkbitCommonUtil.getSelectedDSDetails(sourceTable); - final Set distributionIdNameSet = new HashSet<>(); - - if (!distSelected.contains(transferable.getData(SPUIDefinitions.ITEMID))) { - distributionIdNameSet.add((DistributionSetIdName) transferable.getData(SPUIDefinitions.ITEMID)); - } else { - distributionIdNameSet.addAll(distSelected); - } + @SuppressWarnings("unchecked") + final AbstractTable distTable = (AbstractTable) sourceTable; + final Set distributionIdNameSet = distTable.getDeletedEntityByTransferable(transferable); final DistributionSetIdName dsInBulkUpload = managementUIState.getTargetTableFilters().getBulkUpload() .getDsNameAndVersion(); @@ -317,32 +267,38 @@ public class DeleteActionsLayout extends AbstractDeleteActionsLayout { distributionIdNameSet.remove(dsInBulkUpload); } - if (!distributionIdNameSet.isEmpty()) { - - /* - * Flags to identify whether all dropped distributions are already - * in the deleted list (or) some distributions are already in the - * deleted distribution list. - */ - final int existingDeletedDistributionsSize = managementUIState.getDeletedDistributionList().size(); - managementUIState.getDeletedDistributionList().addAll(distributionIdNameSet); - final int newDeletedDistributionsSize = managementUIState.getDeletedDistributionList().size(); - if (newDeletedDistributionsSize == existingDeletedDistributionsSize) { - /* - * No new distributions are added, all distributions dropped now - * are already available in the delete list. Hence display - * warning message accordingly. - */ - notification.displayValidationError(i18n.get("message.targets.already.deleted")); - } else if (newDeletedDistributionsSize - existingDeletedDistributionsSize != distributionIdNameSet.size()) { - /* - * Not the all distributions dropped now are added to the delete - * list. There are some distributions are already there in the - * delete list. Hence display warning message accordingly. - */ - notification.displayValidationError(i18n.get("message.dist.deleted.pending")); - } + if (distributionIdNameSet.isEmpty()) { + return; } + checkDeletedDistributionSets(distributionIdNameSet); + } + + private void checkDeletedDistributionSets(final Set distributionIdNameSet) { + final int existingDeletedDistributionsSize = managementUIState.getDeletedDistributionList().size(); + managementUIState.getDeletedDistributionList().addAll(distributionIdNameSet); + final int newDeletedDistributionsSize = managementUIState.getDeletedDistributionList().size(); + + showAlreadyDeletedDistributionSetNotfication(existingDeletedDistributionsSize, newDeletedDistributionsSize, + "message.dists.already.deleted"); + showPendingDeletedNotifaction(distributionIdNameSet, existingDeletedDistributionsSize, + newDeletedDistributionsSize, "message.dist.deleted.pending"); + } + + private void showPendingDeletedNotifaction(final Set currentValues, final int existingDeletedSize, + final int newDeletedSize, final String messageKey) { + if (newDeletedSize - existingDeletedSize == currentValues.size()) { + return; + } + notification.displayValidationError(i18n.get(messageKey)); + } + + private void showAlreadyDeletedDistributionSetNotfication(final int existingDeletedSize, final int newDeletedSize, + final String messageKey) { + + if (newDeletedSize != existingDeletedSize) { + return; + } + notification.displayValidationError(i18n.get(messageKey)); } private boolean isDsInUseInBulkUpload(final Set distributionIdNameSet, @@ -356,38 +312,23 @@ public class DeleteActionsLayout extends AbstractDeleteActionsLayout { } private void addInDeleteTargetList(final Table sourceTable, final TableTransferable transferable) { - final Set targetSelected = HawkbitCommonUtil.getSelectedTargetDetails(sourceTable); + @SuppressWarnings("unchecked") + final AbstractTable targetTable = (AbstractTable) sourceTable; + final Set targetIdNameSet = targetTable.getDeletedEntityByTransferable(transferable); - final Set targetIdNameSet = new HashSet<>(); - if (!targetSelected.contains(transferable.getData(SPUIDefinitions.ITEMID))) { - targetIdNameSet.add((TargetIdName) transferable.getData(SPUIDefinitions.ITEMID)); - } else { - targetIdNameSet.addAll(targetSelected); - } + checkDeletedTargets(targetIdNameSet); + } - /* - * Flags to identify whether all dropped targets are already in the - * deleted list (or) some target are already in the deleted distribution - * list. - */ + private void checkDeletedTargets(final Set targetIdNameSet) { final int existingDeletedTargetsSize = managementUIState.getDeletedTargetList().size(); managementUIState.getDeletedTargetList().addAll(targetIdNameSet); final int newDeletedTargetsSize = managementUIState.getDeletedTargetList().size(); - if (newDeletedTargetsSize == existingDeletedTargetsSize) { - /* - * No new targets are added, all targets dropped now are already - * available in the delete list. Hence display warning message - * accordingly. - */ - notification.displayValidationError(i18n.get("message.targets.already.deleted")); - } else if (newDeletedTargetsSize - existingDeletedTargetsSize != targetIdNameSet.size()) { - /* - * Not the all targets dropped now are added to the delete list. - * There are some targets are already there in the delete list. - * Hence display warning message accordingly. - */ - notification.displayValidationError(i18n.get("message.target.deleted.pending")); - } + + showAlreadyDeletedDistributionSetNotfication(existingDeletedTargetsSize, newDeletedTargetsSize, + "message.targets.already.deleted"); + + showPendingDeletedNotifaction(targetIdNameSet, existingDeletedTargetsSize, newDeletedTargetsSize, + "message.target.deleted.pending"); } private void updateActionCount() { diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/footer/ManangementConfirmationWindowLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/footer/ManangementConfirmationWindowLayout.java index c0f681c7a..56e11a6fe 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/footer/ManangementConfirmationWindowLayout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/footer/ManangementConfirmationWindowLayout.java @@ -19,8 +19,6 @@ import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; -import javax.annotation.PostConstruct; - import org.eclipse.hawkbit.repository.DeploymentManagement; import org.eclipse.hawkbit.repository.DistributionSetAssignmentResult; import org.eclipse.hawkbit.repository.DistributionSetManagement; @@ -31,20 +29,15 @@ import org.eclipse.hawkbit.repository.model.DistributionSetIdName; import org.eclipse.hawkbit.repository.model.TargetIdName; import org.eclipse.hawkbit.ui.common.confirmwindow.layout.AbstractConfirmationWindowLayout; import org.eclipse.hawkbit.ui.common.confirmwindow.layout.ConfirmationTab; -import org.eclipse.hawkbit.ui.components.SPUIComponentProvider; -import org.eclipse.hawkbit.ui.decorators.SPUIButtonStyleSmallNoBorder; import org.eclipse.hawkbit.ui.management.event.PinUnpinEvent; import org.eclipse.hawkbit.ui.management.event.SaveActionWindowEvent; import org.eclipse.hawkbit.ui.management.footer.ActionTypeOptionGroupLayout.ActionTypeOption; import org.eclipse.hawkbit.ui.management.state.ManagementUIState; import org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil; -import org.eclipse.hawkbit.ui.utils.I18N; import org.eclipse.hawkbit.ui.utils.SPUIComponetIdProvider; import org.eclipse.hawkbit.ui.utils.SPUIDefinitions; import org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions; -import org.eclipse.hawkbit.ui.utils.SPUIStyleDefinitions; import org.springframework.beans.factory.annotation.Autowired; -import org.vaadin.spring.events.EventBus; import com.vaadin.data.Item; import com.vaadin.data.util.IndexedContainer; @@ -52,8 +45,8 @@ import com.vaadin.server.FontAwesome; import com.vaadin.spring.annotation.SpringComponent; import com.vaadin.spring.annotation.ViewScope; import com.vaadin.ui.Button; +import com.vaadin.ui.Button.ClickListener; import com.vaadin.ui.Table.Align; -import com.vaadin.ui.themes.ValoTheme; /** * Confirmation window for target/ds delete and assignment. @@ -79,12 +72,6 @@ public class ManangementConfirmationWindowLayout extends AbstractConfirmationWin @Autowired private ManagementUIState managementUIState; - @Autowired - private I18N i18n; - - @Autowired - private transient EventBus.SessionEventBus eventBus; - @Autowired private transient TargetManagement targetManagement; @@ -99,14 +86,6 @@ public class ManangementConfirmationWindowLayout extends AbstractConfirmationWin private ConfirmationTab assignmnetTab; - /** - * Initialze the component. - */ - @PostConstruct - public void init() { - super.inittialize(); - } - @Override protected Map getConfimrationTabs() { final Map tabs = new HashMap<>(); @@ -130,6 +109,7 @@ public class ManangementConfirmationWindowLayout extends AbstractConfirmationWin assignmnetTab.getConfirmAll().setIcon(FontAwesome.SAVE); assignmnetTab.getConfirmAll().setCaption(i18n.get("button.assign.all")); assignmnetTab.getConfirmAll().addClickListener(event -> saveAllAssignments(assignmnetTab)); + assignmnetTab.getDiscardAll().setCaption(i18n.get(SPUILabelDefinitions.BUTTON_DISCARD_ALL)); assignmnetTab.getDiscardAll().setId(SPUIComponetIdProvider.DISCARD_ASSIGNMENT); assignmnetTab.getDiscardAll().addClickListener(event -> discardAllAssignments(assignmnetTab)); @@ -139,35 +119,17 @@ public class ManangementConfirmationWindowLayout extends AbstractConfirmationWin // Add the discard action column assignmnetTab.getTable().addGeneratedColumn(DISCARD_CHANGES, (source, itemId, columnId) -> { - final StringBuilder style = new StringBuilder(ValoTheme.BUTTON_TINY); - style.append(' '); - style.append(SPUIStyleDefinitions.REDICON); - final Button deleteIcon = SPUIComponentProvider.getButton("", "", SPUILabelDefinitions.DISCARD, - style.toString(), true, FontAwesome.REPLY, SPUIButtonStyleSmallNoBorder.class); - deleteIcon.setData(itemId); - deleteIcon.setImmediate(true); - deleteIcon.addClickListener(event -> discardAssignment( - (TargetIdName) ((Button) event.getComponent()).getData(), assignmnetTab)); - return deleteIcon; + final ClickListener clickListener = event -> discardAssignment( + (TargetIdName) ((Button) event.getComponent()).getData(), assignmnetTab); + return createDiscardButton(itemId, clickListener); }); - // set the visible columns - final List visibleColumnIds = new ArrayList<>(); - final List visibleColumnLabels = new ArrayList<>(); - if (visibleColumnIds.isEmpty() && visibleColumnLabels.isEmpty()) { - visibleColumnIds.add(TARGET_NAME); - visibleColumnIds.add(DISTRIBUTION_NAME); - visibleColumnIds.add(DISCARD_CHANGES); - visibleColumnLabels.add(i18n.get("header.first.assignment.table")); - visibleColumnLabels.add(i18n.get("header.second.assignment.table")); - visibleColumnLabels.add(i18n.get("header.third.assignment.table")); - } - assignmnetTab.getTable().setColumnExpandRatio(TARGET_NAME, 2); assignmnetTab.getTable().setColumnExpandRatio(DISTRIBUTION_NAME, 2); assignmnetTab.getTable().setColumnExpandRatio(DISCARD_CHANGES, 1); - assignmnetTab.getTable().setVisibleColumns(visibleColumnIds.toArray()); - assignmnetTab.getTable().setColumnHeaders(visibleColumnLabels.toArray(new String[0])); + assignmnetTab.getTable().setVisibleColumns(TARGET_NAME, DISTRIBUTION_NAME, DISCARD_CHANGES); + assignmnetTab.getTable().setColumnHeaders(i18n.get("header.first.assignment.table"), + i18n.get("header.second.assignment.table"), i18n.get("header.third.assignment.table")); assignmnetTab.getTable().setColumnAlignment(DISCARD_CHANGES, Align.CENTER); actionTypeOptionGroupLayout.selectDefaultOption(); @@ -326,27 +288,15 @@ public class ManangementConfirmationWindowLayout extends AbstractConfirmationWin /* Add the discard action column */ tab.getTable().addGeneratedColumn(DISCARD_CHANGES, (source, itemId, columnId) -> { - final Button deletestargetIcon = SPUIComponentProvider.getButton("", "", SPUILabelDefinitions.DISCARD, - ValoTheme.BUTTON_TINY + " " + SPUIStyleDefinitions.REDICON, true, FontAwesome.REPLY, - SPUIButtonStyleSmallNoBorder.class); - deletestargetIcon.setData(itemId); - deletestargetIcon.setImmediate(true); - deletestargetIcon.addClickListener(event -> discardTargetDelete( - (TargetIdName) ((Button) event.getComponent()).getData(), itemId, tab)); - return deletestargetIcon; + final ClickListener clickListener = event -> discardTargetDelete( + (TargetIdName) ((Button) event.getComponent()).getData(), itemId, tab); + return createDiscardButton(itemId, clickListener); + }); - /* set the visible columns */ - final List visibleColumnIds = new ArrayList<>(); - final List visibleColumnLabels = new ArrayList<>(); - if (visibleColumnIds.isEmpty() && visibleColumnLabels.isEmpty()) { - visibleColumnIds.add(TARGET_NAME); - visibleColumnIds.add(DISCARD_CHANGES); - visibleColumnLabels.add(i18n.get("header.first.deletetarget.table")); - visibleColumnLabels.add(i18n.get("header.second.deletetarget.table")); - } - tab.getTable().setVisibleColumns(visibleColumnIds.toArray()); - tab.getTable().setColumnHeaders(visibleColumnLabels.toArray(new String[0])); + tab.getTable().setVisibleColumns(TARGET_NAME, DISCARD_CHANGES); + tab.getTable().setColumnHeaders(i18n.get("header.first.deletetarget.table"), + i18n.get("header.second.deletetarget.table")); tab.getTable().setColumnExpandRatio(TARGET_NAME, SPUIDefinitions.TARGET_DISTRIBUTION_COLUMN_WIDTH); tab.getTable().setColumnExpandRatio(DISCARD_CHANGES, SPUIDefinitions.DISCARD_COLUMN_WIDTH); @@ -371,30 +321,17 @@ public class ManangementConfirmationWindowLayout extends AbstractConfirmationWin /* Add the discard action column */ tab.getTable().addGeneratedColumn(DISCARD_CHANGES, (source, itemId, columnId) -> { - final Button deletesDsIcon = SPUIComponentProvider.getButton("", "", SPUILabelDefinitions.DISCARD, - ValoTheme.BUTTON_TINY + " " + SPUIStyleDefinitions.REDICON, true, FontAwesome.REPLY, - SPUIButtonStyleSmallNoBorder.class); - deletesDsIcon.setData(itemId); - deletesDsIcon.setImmediate(true); - deletesDsIcon.addClickListener(event -> discardDSDelete( - (DistributionSetIdName) ((Button) event.getComponent()).getData(), itemId, tab)); - return deletesDsIcon; - }); + final ClickListener clickListener = event -> discardDSDelete( + (DistributionSetIdName) ((Button) event.getComponent()).getData(), itemId, tab); + return createDiscardButton(itemId, clickListener); - /* set the visible columns */ - final List visibleColumnIds = new ArrayList<>(); - final List visibleColumnLabels = new ArrayList<>(); - if (visibleColumnIds.isEmpty() && visibleColumnLabels.isEmpty()) { - visibleColumnIds.add(DISTRIBUTION_NAME); - visibleColumnIds.add(DISCARD_CHANGES); - visibleColumnLabels.add(i18n.get("header.one.deletedist.table")); - visibleColumnLabels.add(i18n.get("header.second.deletedist.table")); - } + }); tab.getTable().setColumnExpandRatio(DISTRIBUTION_NAME, SPUIDefinitions.TARGET_DISTRIBUTION_COLUMN_WIDTH); tab.getTable().setColumnExpandRatio(DISCARD_CHANGES, SPUIDefinitions.DISCARD_COLUMN_WIDTH); - tab.getTable().setVisibleColumns(visibleColumnIds.toArray()); - tab.getTable().setColumnHeaders(visibleColumnLabels.toArray(new String[0])); + tab.getTable().setVisibleColumns(DISTRIBUTION_NAME, DISCARD_CHANGES); + tab.getTable().setColumnHeaders(i18n.get("header.one.deletedist.table"), + i18n.get("header.second.deletedist.table")); tab.getTable().setColumnAlignment(DISCARD_CHANGES, Align.CENTER); return tab; } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/state/ManagementUIState.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/state/ManagementUIState.java index 3184bf923..653075735 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/state/ManagementUIState.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/state/ManagementUIState.java @@ -19,6 +19,7 @@ import java.util.concurrent.atomic.AtomicLong; import org.eclipse.hawkbit.repository.model.DistributionSetIdName; import org.eclipse.hawkbit.repository.model.TargetIdName; +import org.eclipse.hawkbit.ui.common.ManagmentEntityState; import org.springframework.beans.factory.annotation.Autowired; import com.vaadin.spring.annotation.SpringComponent; @@ -31,7 +32,7 @@ import com.vaadin.spring.annotation.VaadinSessionScope; */ @VaadinSessionScope @SpringComponent -public class ManagementUIState implements Serializable { +public class ManagementUIState implements ManagmentEntityState, Serializable { private static final long serialVersionUID = 7301409196969723794L; @@ -170,7 +171,7 @@ public class ManagementUIState implements Serializable { } public Optional> getSelectedTargetIdName() { - return selectedTargetIdName == null ? Optional.empty() : Optional.of(selectedTargetIdName); + return Optional.ofNullable(selectedTargetIdName); } public void setSelectedTargetIdName(final Set selectedTargetIdName) { @@ -266,16 +267,19 @@ public class ManagementUIState implements Serializable { return lastSelectedDsIdName; } - public void setLastSelectedDsIdName(final DistributionSetIdName lastSelectedDsIdName) { - this.lastSelectedDsIdName = lastSelectedDsIdName; + @Override + public void setLastSelectedEntity(final DistributionSetIdName value) { + this.lastSelectedDsIdName = value; } - public void setSelectedDsIdName(final Set selectedDsIdName) { - this.selectedDsIdName = selectedDsIdName; + @Override + public void setSelectedEnitities(final Set values) { + this.selectedDsIdName = values; + } public Optional> getSelectedDsIdName() { - return selectedDsIdName == null ? Optional.empty() : Optional.of(selectedDsIdName); + return Optional.ofNullable(selectedDsIdName); } /** diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/tag/CreateUpdateTagLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/tag/CreateUpdateTagLayout.java index b78db6b4f..6bed7dd4f 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/tag/CreateUpdateTagLayout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/tag/CreateUpdateTagLayout.java @@ -171,7 +171,7 @@ public abstract class CreateUpdateTagLayout extends CustomComponent implements C tagName = SPUIComponentProvider.getTextField("", ValoTheme.TEXTFIELD_TINY + " " + SPUIDefinitions.TAG_NAME, true, "", i18n.get("textfield.name"), true, SPUILabelDefinitions.TEXT_FIELD_MAX_LENGTH); tagName.setId(SPUIDefinitions.NEW_TARGET_TAG_NAME); - + tagDesc = SPUIComponentProvider.getTextArea("", ValoTheme.TEXTFIELD_TINY + " " + SPUIDefinitions.TAG_DESC, false, "", i18n.get("textfield.description"), SPUILabelDefinitions.TEXT_AREA_MAX_LENGTH); @@ -237,7 +237,8 @@ public abstract class CreateUpdateTagLayout extends CustomComponent implements C fieldLayout.addComponent(madatoryLabel); fieldLayout.addComponent(tagName); fieldLayout.addComponent(tagDesc); - + + final HorizontalLayout colorLabelLayout = new HorizontalLayout(); colorLabelLayout.addComponents(colorLabel, tagColorPreviewBtn); fieldLayout.addComponent(colorLabelLayout); @@ -257,8 +258,8 @@ public abstract class CreateUpdateTagLayout extends CustomComponent implements C mainLayout = new HorizontalLayout(); mainLayout.addComponent(fieldButtonLayout); - setCompositionRoot(mainLayout); + tagName.focus(); } 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..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 @@ -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,41 @@ 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"); + } + 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()) { + return null; + } + if (deletedTags.size() == 1) { + return i18n.get("message.bulk.upload.tag.assignment.failed", deletedTags.get(0)); + } + return i18n.get("message.bulk.upload.tag.assignments.failed"); + } + private boolean ifTagsSelected() { return targetBulkTokenTags.getTokenField().getValue() != null; } @@ -307,59 +373,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 +418,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 +438,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/management/targettable/TargetAddUpdateWindowLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/TargetAddUpdateWindowLayout.java index 48f0ad2bf..e54911d86 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/TargetAddUpdateWindowLayout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/TargetAddUpdateWindowLayout.java @@ -14,11 +14,11 @@ import java.util.Set; import org.eclipse.hawkbit.repository.TargetManagement; import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.repository.model.TargetIdName; +import org.eclipse.hawkbit.ui.common.table.BaseEntityEventType; import org.eclipse.hawkbit.ui.components.SPUIComponentProvider; import org.eclipse.hawkbit.ui.decorators.SPUIButtonStyleSmallNoBorder; import org.eclipse.hawkbit.ui.management.event.DragEvent; import org.eclipse.hawkbit.ui.management.event.TargetTableEvent; -import org.eclipse.hawkbit.ui.management.event.TargetTableEvent.TargetComponentEvent; import org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil; import org.eclipse.hawkbit.ui.utils.I18N; import org.eclipse.hawkbit.ui.utils.SPUIComponetIdProvider; @@ -56,6 +56,8 @@ import com.vaadin.ui.themes.ValoTheme; @SpringComponent @VaadinSessionScope public class TargetAddUpdateWindowLayout extends CustomComponent { + private static final long serialVersionUID = -6659290471705262389L; + @Autowired private I18N i18n; @@ -68,7 +70,6 @@ public class TargetAddUpdateWindowLayout extends CustomComponent { @Autowired private transient UINotification uINotification; - private static final long serialVersionUID = -6659290471705262389L; private TextField controllerIDTextField; private TextField nameTextField; private TextArea descTextArea; @@ -151,7 +152,7 @@ public class TargetAddUpdateWindowLayout extends CustomComponent { madatoryLabel.setVisible(Boolean.FALSE); } mainLayout.addComponents(madatoryLabel, controllerIDTextField, nameTextField, descTextArea, buttonsLayout); - + nameTextField.focus(); } private void addListeners() { @@ -218,7 +219,7 @@ public class TargetAddUpdateWindowLayout extends CustomComponent { /* display success msg */ uINotification.displaySuccess(i18n.get("message.update.success", new Object[] { latestTarget.getName() })); // publishing through event bus - eventBus.publish(this, new TargetTableEvent(TargetComponentEvent.EDIT_TARGET, latestTarget)); + eventBus.publish(this, new TargetTableEvent(BaseEntityEventType.UPDATED_ENTITY, latestTarget)); /* close the window */ closeThisWindow(); diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/TargetBeanQuery.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/TargetBeanQuery.java index dac50ab0d..e96a9af8e 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/TargetBeanQuery.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/TargetBeanQuery.java @@ -19,6 +19,7 @@ import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.repository.model.TargetFilterQuery; import org.eclipse.hawkbit.repository.model.TargetUpdateStatus; +import org.eclipse.hawkbit.ui.common.UserDetailsFormatter; import org.eclipse.hawkbit.ui.components.ProxyTarget; import org.eclipse.hawkbit.ui.management.state.ManagementUIState; import org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil; @@ -130,8 +131,8 @@ public class TargetBeanQuery extends AbstractBeanQuery { prxyTarget.setLastModifiedDate(SPDateTimeUtil.getFormattedDate(targ.getLastModifiedAt())); prxyTarget.setCreatedDate(SPDateTimeUtil.getFormattedDate(targ.getCreatedAt())); prxyTarget.setCreatedAt(targ.getCreatedAt()); - prxyTarget.setCreatedByUser(HawkbitCommonUtil.getIMUser(targ.getCreatedBy())); - prxyTarget.setModifiedByUser(HawkbitCommonUtil.getIMUser(targ.getLastModifiedBy())); + prxyTarget.setCreatedByUser(UserDetailsFormatter.loadAndFormatCreatedBy(targ)); + prxyTarget.setModifiedByUser(UserDetailsFormatter.loadAndFormatLastModifiedBy(targ)); if (pinnedDistId == null) { prxyTarget.setInstalledDistributionSet(null); diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/TargetDetails.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/TargetDetails.java index a94ed6b5f..8ab4f8b0d 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/TargetDetails.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/TargetDetails.java @@ -10,11 +10,7 @@ package org.eclipse.hawkbit.ui.management.targettable; import java.net.URI; -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; - import org.apache.commons.lang3.StringUtils; -import org.eclipse.hawkbit.repository.SpPermissionChecker; import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.repository.model.Target; @@ -22,15 +18,12 @@ import org.eclipse.hawkbit.ui.common.detailslayout.AbstractTableDetailsLayout; import org.eclipse.hawkbit.ui.common.tagdetails.TargetTagToken; import org.eclipse.hawkbit.ui.components.SPUIComponentProvider; import org.eclipse.hawkbit.ui.management.event.TargetTableEvent; -import org.eclipse.hawkbit.ui.management.event.TargetTableEvent.TargetComponentEvent; import org.eclipse.hawkbit.ui.management.state.ManagementUIState; import org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil; -import org.eclipse.hawkbit.ui.utils.I18N; import org.eclipse.hawkbit.ui.utils.SPDateTimeUtil; import org.eclipse.hawkbit.ui.utils.SPUIComponetIdProvider; import org.eclipse.hawkbit.ui.utils.SPUIDefinitions; import org.springframework.beans.factory.annotation.Autowired; -import org.vaadin.spring.events.EventBus; import org.vaadin.spring.events.EventScope; import org.vaadin.spring.events.annotation.EventBusListenerMethod; @@ -50,25 +43,13 @@ import com.vaadin.ui.themes.ValoTheme; /** * Target details layout. - * - * - * */ @SpringComponent @ViewScope -public class TargetDetails extends AbstractTableDetailsLayout { +public class TargetDetails extends AbstractTableDetailsLayout { private static final long serialVersionUID = 4571732743399605843L; - @Autowired - private I18N i18n; - - @Autowired - private transient EventBus.SessionEventBus eventBus; - - @Autowired - private SpPermissionChecker permChecker; - @Autowired private ManagementUIState managementUIState; @@ -78,36 +59,29 @@ public class TargetDetails extends AbstractTableDetailsLayout { @Autowired private TargetTagToken targetTagToken; - private Target selectedTarget = null; - private VerticalLayout assignedDistLayout; private VerticalLayout installedDistLayout; - /** - * Initialize the Target details. - */ @Override - @PostConstruct public void init() { super.init(); targetAddUpdateWindowLayout.init(); - eventBus.subscribe(this); } @Override protected String getDefaultCaption() { - return i18n.get("target.details.header"); + return getI18n().get("target.details.header"); } @Override protected void addTabs(final TabSheet detailsTab) { - detailsTab.addTab(createDetailsLayout(), i18n.get("caption.tab.details"), null); - detailsTab.addTab(createDescriptionLayout(), i18n.get("caption.tab.description"), null); - detailsTab.addTab(createAttributesLayout(), i18n.get("caption.attributes.tab"), null); - detailsTab.addTab(createAssignedDistLayout(), i18n.get("header.target.assigned"), null); - detailsTab.addTab(createInstalledDistLayout(), i18n.get("header.target.installed"), null); - detailsTab.addTab(createTagsLayout(), i18n.get("caption.tags.tab"), null); - detailsTab.addTab(createLogLayout(), i18n.get("caption.logs.tab"), null); + detailsTab.addTab(createDetailsLayout(), getI18n().get("caption.tab.details"), null); + detailsTab.addTab(createDescriptionLayout(), getI18n().get("caption.tab.description"), null); + detailsTab.addTab(createAttributesLayout(), getI18n().get("caption.attributes.tab"), null); + detailsTab.addTab(createAssignedDistLayout(), getI18n().get("header.target.assigned"), null); + detailsTab.addTab(createInstalledDistLayout(), getI18n().get("header.target.installed"), null); + detailsTab.addTab(createTagsLayout(), getI18n().get("caption.tags.tab"), null); + detailsTab.addTab(createLogLayout(), getI18n().get("caption.logs.tab"), null); } @@ -129,13 +103,14 @@ public class TargetDetails extends AbstractTableDetailsLayout { @Override protected void onEdit(final ClickEvent event) { - if (selectedTarget != null) { - final Window newDistWindow = targetAddUpdateWindowLayout.getWindow(); - targetAddUpdateWindowLayout.populateValuesOfTarget(selectedTarget.getControllerId()); - newDistWindow.setCaption(i18n.get("caption.update.dist")); - UI.getCurrent().addWindow(newDistWindow); - newDistWindow.setVisible(Boolean.TRUE); + if (getSelectedBaseEntity() == null) { + return; } + final Window newDistWindow = targetAddUpdateWindowLayout.getWindow(); + targetAddUpdateWindowLayout.populateValuesOfTarget(getSelectedBaseEntity().getControllerId()); + newDistWindow.setCaption(getI18n().get("caption.update.dist")); + UI.getCurrent().addWindow(newDistWindow); + newDistWindow.setVisible(Boolean.TRUE); } @Override @@ -155,50 +130,24 @@ public class TargetDetails extends AbstractTableDetailsLayout { @Override protected void populateDetailsWidget() { - if (selectedTarget != null) { - setName(getDefaultCaption(), selectedTarget.getName()); - } - populateDetailsWidget(selectedTarget); - } - - private void populateDetailsWidget(final Target target) { - if (target != null) { - setName(getDefaultCaption(), target.getName()); - updateDetailsLayout(target.getControllerId(), target.getTargetInfo().getAddress(), - target.getSecurityToken(), - SPDateTimeUtil.getFormattedDate(target.getTargetInfo().getLastTargetQuery())); - populateDescription(target); - populateDistributionDtls(installedDistLayout, target.getTargetInfo().getInstalledDistributionSet()); - populateDistributionDtls(assignedDistLayout, target.getAssignedDistributionSet()); - updateLogLayout(getLogLayout(), target.getLastModifiedAt(), target.getLastModifiedBy(), - target.getCreatedAt(), target.getCreatedBy(), i18n); - populateAttributes(target); + if (getSelectedBaseEntity() != null) { + updateDetailsLayout(getSelectedBaseEntity().getControllerId(), + getSelectedBaseEntity().getTargetInfo().getAddress(), getSelectedBaseEntity().getSecurityToken(), + SPDateTimeUtil.getFormattedDate(getSelectedBaseEntity().getTargetInfo().getLastTargetQuery())); + populateDistributionDtls(installedDistLayout, + getSelectedBaseEntity().getTargetInfo().getInstalledDistributionSet()); + populateDistributionDtls(assignedDistLayout, getSelectedBaseEntity().getAssignedDistributionSet()); } else { - setName(getDefaultCaption(), HawkbitCommonUtil.SP_STRING_EMPTY); updateDetailsLayout(null, null, null, null); - populateDescription(null); populateDistributionDtls(installedDistLayout, null); populateDistributionDtls(assignedDistLayout, null); - updateLogLayout(getLogLayout(), null, HawkbitCommonUtil.SP_STRING_EMPTY, null, null, i18n); - populateAttributes(null); } + updateAttributesLayout(getSelectedBaseEntity()); } - private void populateAttributes(final Target target) { - if (target != null) { - - updateAttributesLayout(target); - } else { - updateAttributesLayout(null); - } - } - - private void populateDescription(final Target target) { - if (target != null) { - updateDescriptionLayout(i18n.get("label.description"), target.getDescription()); - } else { - updateDescriptionLayout(i18n.get("label.description"), null); - } + @Override + protected String getName() { + return getSelectedBaseEntity().getName(); } private void updateDetailsLayout(final String controllerId, final URI address, final String securityToken, @@ -206,17 +155,18 @@ public class TargetDetails extends AbstractTableDetailsLayout { final VerticalLayout detailsTabLayout = getDetailsLayout(); detailsTabLayout.removeAllComponents(); - final Label controllerLabel = SPUIComponentProvider.createNameValueLabel(i18n.get("label.target.id"), + final Label controllerLabel = SPUIComponentProvider.createNameValueLabel(getI18n().get("label.target.id"), HawkbitCommonUtil.trimAndNullIfEmpty(controllerId) == null ? "" : controllerId); controllerLabel.setId(SPUIComponetIdProvider.TARGET_CONTROLLER_ID); detailsTabLayout.addComponent(controllerLabel); - final Label lastPollDtLabel = SPUIComponentProvider.createNameValueLabel(i18n.get("label.target.lastpolldate"), + final Label lastPollDtLabel = SPUIComponentProvider.createNameValueLabel( + getI18n().get("label.target.lastpolldate"), HawkbitCommonUtil.trimAndNullIfEmpty(lastQueryDate) == null ? "" : lastQueryDate); lastPollDtLabel.setId(SPUIComponetIdProvider.TARGET_LAST_QUERY_DT); detailsTabLayout.addComponent(lastPollDtLabel); - final Label typeLabel = SPUIComponentProvider.createNameValueLabel(i18n.get("label.ip"), + final Label typeLabel = SPUIComponentProvider.createNameValueLabel(getI18n().get("label.ip"), address == null ? StringUtils.EMPTY : address.toString()); typeLabel.setId(SPUIComponetIdProvider.TARGET_IP_ADDRESS); detailsTabLayout.addComponent(typeLabel); @@ -232,7 +182,7 @@ public class TargetDetails extends AbstractTableDetailsLayout { final HorizontalLayout securityTokenLayout = new HorizontalLayout(); final Label securityTableLbl = new Label( - SPUIComponentProvider.getBoldHTMLText(i18n.get("label.target.security.token")), ContentMode.HTML); + SPUIComponentProvider.getBoldHTMLText(getI18n().get("label.target.security.token")), ContentMode.HTML); securityTableLbl.addStyleName(SPUIDefinitions.TEXT_STYLE); securityTableLbl.addStyleName("label-style"); @@ -252,18 +202,17 @@ public class TargetDetails extends AbstractTableDetailsLayout { private void populateDistributionDtls(final VerticalLayout layout, final DistributionSet distributionSet) { layout.removeAllComponents(); - if (distributionSet != null) { - // Display distribution set name - layout.addComponent(SPUIComponentProvider.createNameValueLabel(i18n.get("label.dist.details.name"), - distributionSet.getName())); - - layout.addComponent(SPUIComponentProvider.createNameValueLabel(i18n.get("label.dist.details.version"), - distributionSet.getVersion())); - - /* Module info */ - distributionSet.getModules() - .forEach(module -> layout.addComponent(getSWModlabel(module.getType().getName(), module))); + if (distributionSet == null) { + return; } + layout.addComponent(SPUIComponentProvider.createNameValueLabel(getI18n().get("label.dist.details.name"), + distributionSet.getName())); + + layout.addComponent(SPUIComponentProvider.createNameValueLabel(getI18n().get("label.dist.details.version"), + distributionSet.getVersion())); + + distributionSet.getModules() + .forEach(module -> layout.addComponent(getSWModlabel(module.getType().getName(), module))); } /** @@ -279,42 +228,14 @@ public class TargetDetails extends AbstractTableDetailsLayout { return SPUIComponentProvider.createNameValueLabel(labelName + " : ", swModule.getName(), swModule.getVersion()); } - @Override - protected void clearDetails() { - populateDetailsWidget(null); - } - @Override protected Boolean hasEditPermission() { - return permChecker.hasUpdateTargetPermission(); + return getPermissionChecker().hasUpdateTargetPermission(); } @EventBusListenerMethod(scope = EventScope.SESSION) void onEvent(final TargetTableEvent targetTableEvent) { - // Get the event type - final TargetComponentEvent event = targetTableEvent.getTargetComponentEvent(); - - if (event == TargetComponentEvent.SELECTED_TARGET || event == TargetComponentEvent.EDIT_TARGET) { - UI.getCurrent().access(() -> { - // If selected or edited, populate the fresh details. - if (targetTableEvent.getTarget() != null) { - selectedTarget = targetTableEvent.getTarget(); - } else { - selectedTarget = null; - } - populateData(selectedTarget != null); - - }); - } else if (event == TargetComponentEvent.MINIMIZED) { - UI.getCurrent().access(() -> showLayout()); - } else if (event == TargetComponentEvent.MAXIMIZED) { - UI.getCurrent().access(() -> hideLayout()); - } - } - - @PreDestroy - void destroy() { - eventBus.unsubscribe(this); + onBaseEntityEvent(targetTableEvent); } @Override diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/TargetTable.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/TargetTable.java index 960553a6a..62ad96205 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/TargetTable.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/TargetTable.java @@ -15,13 +15,9 @@ import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; -import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; - import org.eclipse.hawkbit.eventbus.event.TargetCreatedEvent; import org.eclipse.hawkbit.eventbus.event.TargetDeletedEvent; import org.eclipse.hawkbit.eventbus.event.TargetInfoUpdateEvent; @@ -33,9 +29,12 @@ import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.repository.model.TargetFilterQuery; import org.eclipse.hawkbit.repository.model.TargetIdName; import org.eclipse.hawkbit.repository.model.TargetInfo; -import org.eclipse.hawkbit.repository.model.TargetTagAssigmentResult; +import org.eclipse.hawkbit.repository.model.TargetTagAssignmentResult; import org.eclipse.hawkbit.repository.model.TargetUpdateStatus; +import org.eclipse.hawkbit.ui.common.ManagmentEntityState; +import org.eclipse.hawkbit.ui.common.UserDetailsFormatter; import org.eclipse.hawkbit.ui.common.table.AbstractTable; +import org.eclipse.hawkbit.ui.common.table.BaseEntityEventType; import org.eclipse.hawkbit.ui.filter.FilterExpression; import org.eclipse.hawkbit.ui.filter.Filters; import org.eclipse.hawkbit.ui.filter.target.CustomTargetFilter; @@ -53,8 +52,8 @@ import org.eclipse.hawkbit.ui.management.event.TargetTableEvent; import org.eclipse.hawkbit.ui.management.event.TargetTableEvent.TargetComponentEvent; import org.eclipse.hawkbit.ui.management.state.ManagementUIState; import org.eclipse.hawkbit.ui.management.state.TargetTableFilters; +import org.eclipse.hawkbit.ui.utils.AssignInstalledDSTooltipGenerator; import org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil; -import org.eclipse.hawkbit.ui.utils.I18N; import org.eclipse.hawkbit.ui.utils.SPDateTimeUtil; import org.eclipse.hawkbit.ui.utils.SPUIComponetIdProvider; import org.eclipse.hawkbit.ui.utils.SPUIDefinitions; @@ -70,7 +69,6 @@ import org.springframework.data.domain.Sort; import org.vaadin.addons.lazyquerycontainer.BeanQueryFactory; import org.vaadin.addons.lazyquerycontainer.LazyQueryContainer; import org.vaadin.addons.lazyquerycontainer.LazyQueryDefinition; -import org.vaadin.spring.events.EventBus; import org.vaadin.spring.events.EventScope; import org.vaadin.spring.events.annotation.EventBusListenerMethod; @@ -103,24 +101,19 @@ import com.vaadin.ui.themes.ValoTheme; */ @SpringComponent @ViewScope -public class TargetTable extends AbstractTable implements Handler { +public class TargetTable extends AbstractTable implements Handler { + private static final Logger LOG = LoggerFactory.getLogger(TargetTable.class); private static final String TARGET_PINNED = "targetPinned"; private static final long serialVersionUID = -2300392868806614568L; - private static final Logger LOG = LoggerFactory.getLogger(TargetTable.class); - private static final int PROPERTY_DEPT = 3; - private static final String ITEMID = "itemId"; private static final String ACTION_NOT_ALLOWED_MSG = "message.action.not.allowed"; @Autowired private transient TargetManagement targetManagement; - @Autowired - private I18N i18n; - @Autowired private ManagementUIState managementUIState; @@ -130,9 +123,6 @@ public class TargetTable extends AbstractTable implements Handler { @Autowired private UINotification notification; - @Autowired - private transient EventBus.SessionEventBus eventBus; - @Autowired private ManagementViewAcceptCriteria managementViewAcceptCriteria; @@ -141,23 +131,14 @@ public class TargetTable extends AbstractTable implements Handler { private Boolean isTargetPinned = Boolean.FALSE; private ShortcutAction actionSelectAll; private ShortcutAction actionUnSelectAll; - - @Override - @PostConstruct protected void init() { super.init(); addActionHandler(this); actionSelectAll = new ShortcutAction(i18n.get("action.target.table.selectall")); actionUnSelectAll = new ShortcutAction(i18n.get("action.target.table.clear")); - eventBus.subscribe(this); - setNoDataAvailable(); - } - - @PreDestroy - void destroy() { - eventBus.unsubscribe(this); + setItemDescriptionGenerator(new AssignInstalledDSTooltipGenerator()); } /** @@ -203,9 +184,10 @@ public class TargetTable extends AbstractTable implements Handler { @EventBusListenerMethod(scope = EventScope.SESSION) void addOrEditEvent(final TargetAddUpdateWindowEvent targetUIEvent) { - if (targetUIEvent.getTargetComponentEvent() == TargetComponentEvent.EDIT_TARGET) { - UI.getCurrent().access(() -> updateTarget(targetUIEvent.getTarget())); + if (BaseEntityEventType.UPDATED_ENTITY != targetUIEvent.getEventType()) { + return; } + UI.getCurrent().access(() -> updateTarget(targetUIEvent.getEntity())); } @EventBusListenerMethod(scope = EventScope.SESSION) @@ -243,33 +225,14 @@ public class TargetTable extends AbstractTable implements Handler { @EventBusListenerMethod(scope = EventScope.SESSION) void onEvent(final TargetTableEvent event) { - if (event.getTargetComponentEvent() == TargetComponentEvent.MINIMIZED) { - UI.getCurrent().access(() -> applyMinTableSettings()); - } else if (event.getTargetComponentEvent() == TargetComponentEvent.MAXIMIZED) { - UI.getCurrent().access(() -> applyMaxTableSettings()); - } else if (event.getTargetComponentEvent() == TargetComponentEvent.EDIT_TARGET) { - UI.getCurrent().access(() -> updateTarget(event.getTarget())); - } + onBaseEntityEvent(event); } - /* - * (non-Javadoc) - * - * @see - * org.eclipse.hawkbit.server.ui.common.table.AbstractTable#getTableId() - */ @Override protected String getTableId() { return SPUIComponetIdProvider.TARGET_TABLE_ID; } - /* - * (non-Javadoc) - * - * @see - * org.eclipse.hawkbit.server.ui.common.table.AbstractTable#createContainer( - * ) - */ @Override protected Container createContainer() { // ADD all the filters to the query config @@ -315,12 +278,6 @@ public class TargetTable extends AbstractTable implements Handler { } } - /* - * (non-Javadoc) - * - * @see org.eclipse.hawkbit.server.ui.common.table.AbstractTable# - * addCustomGeneratedColumns () - */ @Override protected void addCustomGeneratedColumns() { addGeneratedColumn(SPUIDefinitions.TARGET_STATUS_PIN_TOGGLE_ICON, @@ -329,100 +286,57 @@ public class TargetTable extends AbstractTable implements Handler { (source, itemId, columnId) -> getTagetPollTime(itemId)); } - /* - * (non-Javadoc) - * - * @see org.eclipse.hawkbit.server.ui.common.table.AbstractTable# - * isFirstRowSelectedOnLoad () - */ @Override protected boolean isFirstRowSelectedOnLoad() { return !managementUIState.getSelectedTargetIdName().isPresent() || managementUIState.getSelectedTargetIdName().get().isEmpty(); } - /* - * (non-Javadoc) - * - * @see hawkbit.server.ui.common.table.AbstractTable#getItemIdToSelect() - */ @Override protected Object getItemIdToSelect() { if (managementUIState.getSelectedTargetIdName().isPresent()) { - setCurrentPageFirstItemId(managementUIState.getLastSelectedTargetIdName()); return managementUIState.getSelectedTargetIdName().get(); } return null; } - /* - * (non-Javadoc) - * - * @see - * org.eclipse.hawkbit.server.ui.common.table.AbstractTable#onValueChange() - */ @Override - protected void onValueChange() { - eventBus.publish(this, DragEvent.HIDE_DROP_HINT); - @SuppressWarnings("unchecked") - final Set values = HawkbitCommonUtil.getSelectedTargetDetails(this); - if (values != null && !values.isEmpty()) { - final TargetIdName lastSelectedItem = getLastSelectedItem(values); - managementUIState.setSelectedTargetIdName(values); - managementUIState.setLastSelectedTargetIdName(lastSelectedItem); - final Target target = targetManagement - .findTargetByControllerIDWithDetails(lastSelectedItem.getControllerId()); - eventBus.publish(this, new TargetTableEvent(TargetComponentEvent.SELECTED_TARGET, target)); - } else { - managementUIState.setSelectedTargetIdName(null); - managementUIState.setLastSelectedTargetIdName(null); - eventBus.publish(this, new TargetTableEvent(TargetComponentEvent.SELECTED_TARGET, (Target) null)); - } + protected void publishEntityAfterValueChange(final Target selectedLastEntity) { + eventBus.publish(this, new TargetTableEvent(BaseEntityEventType.SELECTED_ENTITY, selectedLastEntity)); + } + + @Override + protected Target findEntityByTableValue(final TargetIdName lastSelectedId) { + return targetManagement.findTargetByControllerIDWithDetails(lastSelectedId.getControllerId()); + } + + @Override + protected void setManagementEntitiyStateValues(final Set values, final TargetIdName lastId) { + managementUIState.setSelectedTargetIdName(values); + managementUIState.setLastSelectedTargetIdName(lastId); + } + + @Override + protected ManagmentEntityState getManagmentEntityState() { + return null; } - /* - * (non-Javadoc) - * - * @see - * org.eclipse.hawkbit.server.ui.common.table.AbstractTable#isMaximized() - */ @Override protected boolean isMaximized() { return managementUIState.isTargetTableMaximized(); } - /* - * (non-Javadoc) - * - * @see hawkbit.server.ui.common.table.AbstractTable#getTableVisibleColumns - * () - */ @Override protected List getTableVisibleColumns() { - final List columnList = new ArrayList<>(); - if (isMaximized()) { - columnList.add(new TableColumn(SPUILabelDefinitions.VAR_NAME, i18n.get("header.name"), 0.2f)); - columnList.add(new TableColumn(SPUILabelDefinitions.VAR_CREATED_BY, i18n.get("header.createdBy"), 0.1f)); - columnList - .add(new TableColumn(SPUILabelDefinitions.VAR_CREATED_DATE, i18n.get("header.createdDate"), 0.1f)); - columnList.add( - new TableColumn(SPUILabelDefinitions.VAR_LAST_MODIFIED_BY, i18n.get("header.modifiedBy"), 0.1f)); - columnList.add(new TableColumn(SPUILabelDefinitions.VAR_LAST_MODIFIED_DATE, i18n.get("header.modifiedDate"), - 0.1f)); - columnList.add(new TableColumn(SPUILabelDefinitions.VAR_DESC, i18n.get("header.description"), 0.2f)); - } else { - columnList.add(new TableColumn(SPUILabelDefinitions.VAR_NAME, i18n.get("header.name"), 0.8f)); - columnList.add(new TableColumn(SPUIDefinitions.TARGET_STATUS_POLL_TIME, "", 0.0f)); - columnList.add(new TableColumn(SPUIDefinitions.TARGET_STATUS_PIN_TOGGLE_ICON, "", 0.0f)); - } + final List columnList = super.getTableVisibleColumns(); + if (!isMaximized()) { + columnList.add(new TableColumn(SPUIDefinitions.TARGET_STATUS_POLL_TIME, "", 0.0F)); + columnList.add(new TableColumn(SPUIDefinitions.TARGET_STATUS_PIN_TOGGLE_ICON, "", 0.0F)); + } return columnList; + } - /* - * (non-Javadoc) - * - * @see hawkbit.server.ui.common.table.AbstractTable#getTableDropHandler() - */ @Override protected DropHandler getTableDropHandler() { return new DropHandler() { @@ -453,13 +367,29 @@ public class TargetTable extends AbstractTable implements Handler { } else { shouldRefreshTargets = true; } - unselect(targetIdName); } + if (shouldRefreshTargets) { refreshOnDelete(); } else { targetContainer.commit(); - selectRow(); + } + reSelectItemsAfterDeletionEvent(); + } + + private void reSelectItemsAfterDeletionEvent() { + Set values = new HashSet<>(); + if (isMultiSelect()) { + values = new HashSet<>((Set) getValue()); + } else { + values.add(getValue()); + } + unSelectAll(); + + for (final Object value : values) { + if (getVisibleItemIds().contains(value)) { + select(value); + } } } @@ -648,7 +578,7 @@ public class TargetTable extends AbstractTable implements Handler { private void tagAssignment(final DragAndDropEvent event) { final com.vaadin.event.dd.TargetDetails taregtDet = event.getTargetDetails(); final Table targetTable = (Table) taregtDet.getTarget(); - final Set targetSelected = HawkbitCommonUtil.getSelectedTargetDetails(targetTable); + final Set targetSelected = getTableValue(targetTable); final Set targetList = new HashSet<>(); final AbstractSelectTargetDetails dropData = (AbstractSelectTargetDetails) event.getTargetDetails(); final Object targetItemId = dropData.getItemIdOver(); @@ -659,10 +589,10 @@ public class TargetTable extends AbstractTable implements Handler { } final String targTagName = HawkbitCommonUtil.removePrefix(event.getTransferable().getSourceComponent().getId(), SPUIDefinitions.TARGET_TAG_ID_PREFIXS); - final TargetTagAssigmentResult result = targetManagement.toggleTagAssignment(targetList, targTagName); + final TargetTagAssignmentResult result = targetManagement.toggleTagAssignment(targetList, targTagName); final List tagsClickedList = managementUIState.getTargetTableFilters().getClickedTargetTags(); - notification.displaySuccess(HawkbitCommonUtil.getTargetTagAssigmentMsg(targTagName, result, i18n)); + notification.displaySuccess(HawkbitCommonUtil.createAssignmentMessage(targTagName, result, i18n)); if (result.getUnassigned() >= 1 && !tagsClickedList.isEmpty()) { refreshFilter(); } @@ -706,14 +636,9 @@ public class TargetTable extends AbstractTable implements Handler { private static Set getDraggedDistributionSet(final TableTransferable transferable, final Table source) { - final Set distSelected = HawkbitCommonUtil.getSelectedDSDetails(source); - final Set distributionIdSet = new HashSet<>(); - if (!distSelected.contains(transferable.getData(ITEMID))) { - distributionIdSet.add((DistributionSetIdName) transferable.getData(ITEMID)); - } else { - distributionIdSet.addAll(distSelected); - } - return distributionIdSet; + @SuppressWarnings("unchecked") + final AbstractTable distTable = (AbstractTable) source; + return distTable.getDeletedEntityByTransferable(transferable); } private Boolean validateDragAndDropWrapper(final Component compsource) { @@ -817,7 +742,7 @@ public class TargetTable extends AbstractTable implements Handler { .setValue(updatedTarget.getTargetInfo().getLastTargetQuery()); item.getItemProperty(SPUILabelDefinitions.VAR_LAST_MODIFIED_BY) - .setValue(HawkbitCommonUtil.getIMUser(updatedTarget.getLastModifiedBy())); + .setValue(UserDetailsFormatter.loadAndFormatLastModifiedBy(updatedTarget)); item.getItemProperty(SPUILabelDefinitions.VAR_LAST_MODIFIED_DATE) .setValue(SPDateTimeUtil.getFormattedDate(updatedTarget.getLastModifiedAt())); item.getItemProperty(SPUILabelDefinitions.VAR_DESC).setValue(updatedTarget.getDescription()); @@ -930,6 +855,7 @@ public class TargetTable extends AbstractTable implements Handler { eventBus.publish(this, new TargetTableEvent(TargetComponentEvent.REFRESH_TARGETS)); } + @SuppressWarnings("unchecked") private void updateVisibleItemOnEvent(final TargetInfo targetInfo, final Target target, final TargetIdName targetIdName) { final LazyQueryContainer targetContainer = (LazyQueryContainer) getContainerDataSource(); @@ -952,8 +878,8 @@ public class TargetTable extends AbstractTable implements Handler { * @param targetInfoUpdateEvents * list of target info update event */ - @SuppressWarnings("unchecked") private void onTargetInfoUpdateEvents(final List targetInfoUpdateEvents) { + @SuppressWarnings("unchecked") final List visibleItemIds = (List) getVisibleItemIds(); boolean shoulTargetsUpdated = false; Target lastSelectedTarget = null; @@ -980,7 +906,7 @@ public class TargetTable extends AbstractTable implements Handler { refreshTargets(); } if (lastSelectedTarget != null) { - eventBus.publish(this, new TargetTableEvent(TargetComponentEvent.SELECTED_TARGET, lastSelectedTarget)); + eventBus.publish(this, new TargetTableEvent(BaseEntityEventType.SELECTED_ENTITY, lastSelectedTarget)); } } @@ -1038,7 +964,7 @@ public class TargetTable extends AbstractTable implements Handler { final String[] tagArray = tagList.toArray(new String[tagList.size()]); List targetIdList; - targetIdList = targetManagement.findAllTargetIdsByFilters(pageRequest, filterByDistId, statusList, searchText, + targetIdList = targetManagement.findAllTargetIdsByFilters(pageRequest, statusList, searchText, filterByDistId, noTagSelected, tagList.toArray(tagArray)); Collections.reverse(targetIdList); return targetIdList; @@ -1060,13 +986,9 @@ public class TargetTable extends AbstractTable implements Handler { setValue(null); } - private void setNoDataAvailable() { - final int tableSize = getContainerDataSource().size(); - if (tableSize == 0) { - managementUIState.setNoDataAvilableTarget(true); - } else { - managementUIState.setNoDataAvilableTarget(false); - } + @Override + protected void setDataAvailable(final boolean available) { + managementUIState.setNoDataAvilableTarget(!available); } /** diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/TargetTableHeader.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/TargetTableHeader.java index 05b6bfe4d..09c9bf499 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/TargetTableHeader.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettable/TargetTableHeader.java @@ -8,15 +8,12 @@ */ package org.eclipse.hawkbit.ui.management.targettable; -import java.util.HashSet; import java.util.Set; -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; - -import org.eclipse.hawkbit.repository.SpPermissionChecker; import org.eclipse.hawkbit.repository.model.DistributionSetIdName; +import org.eclipse.hawkbit.ui.common.table.AbstractTable; import org.eclipse.hawkbit.ui.common.table.AbstractTableHeader; +import org.eclipse.hawkbit.ui.common.table.BaseEntityEventType; import org.eclipse.hawkbit.ui.components.SPUIComponentProvider; import org.eclipse.hawkbit.ui.decorators.SPUIButtonStyleSmallNoBorder; import org.eclipse.hawkbit.ui.management.event.BulkUploadPopupEvent; @@ -29,7 +26,6 @@ import org.eclipse.hawkbit.ui.management.event.TargetTableEvent; import org.eclipse.hawkbit.ui.management.event.TargetTableEvent.TargetComponentEvent; import org.eclipse.hawkbit.ui.management.state.ManagementUIState; import org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil; -import org.eclipse.hawkbit.ui.utils.I18N; import org.eclipse.hawkbit.ui.utils.SPUIComponetIdProvider; import org.eclipse.hawkbit.ui.utils.SPUITargetDefinitions; import org.eclipse.hawkbit.ui.utils.UINotification; @@ -63,12 +59,6 @@ public class TargetTableHeader extends AbstractTableHeader { private static final long serialVersionUID = -8647521126666320022L; - @Autowired - private I18N i18n; - - @Autowired - private SpPermissionChecker permChecker; - @Autowired private UINotification notification; @@ -90,21 +80,14 @@ public class TargetTableHeader extends AbstractTableHeader { private Boolean isComplexFilterViewDisplayed = Boolean.FALSE; @Override - @PostConstruct protected void init() { super.init(); // creating add window for adding new target targetAddUpdateWindow.init(); targetBulkUpdateWindow.init(); - eventBus.subscribe(this); onLoadRestoreState(); } - @PreDestroy - void destroy() { - eventBus.unsubscribe(this); - } - @EventBusListenerMethod(scope = EventScope.SESSION) void onEvent(final ManagementUIEvent event) { if (event == ManagementUIEvent.HIDE_TARGET_TAG_LAYOUT) { @@ -272,13 +255,13 @@ public class TargetTableHeader extends AbstractTableHeader { @Override public void maximizeTable() { managementUIState.setTargetTableMaximized(Boolean.TRUE); - eventBus.publish(this, new TargetTableEvent(TargetComponentEvent.MAXIMIZED)); + eventBus.publish(this, new TargetTableEvent(BaseEntityEventType.MAXIMIZED,null)); } @Override public void minimizeTable() { managementUIState.setTargetTableMaximized(Boolean.FALSE); - eventBus.publish(this, new TargetTableEvent(TargetComponentEvent.MINIMIZED)); + eventBus.publish(this, new TargetTableEvent(BaseEntityEventType.MINIMIZED,null)); } @Override @@ -395,16 +378,9 @@ public class TargetTableHeader extends AbstractTableHeader { } private Set getDropppedDistributionDetails(final TableTransferable transferable) { - final Set distSelected = HawkbitCommonUtil - .getSelectedDSDetails(transferable.getSourceComponent()); - final Set distributionIdSet = new HashSet<>(); - if (!distSelected.contains(transferable.getData("itemId"))) { - distributionIdSet.add((DistributionSetIdName) transferable.getData("itemId")); - } else { - distributionIdSet.addAll(distSelected); - } - - return distributionIdSet; + @SuppressWarnings("unchecked") + final AbstractTable distTable = (AbstractTable) transferable.getSourceComponent(); + return distTable.getDeletedEntityByTransferable(transferable); } private void addFilterTextField(final DistributionSetIdName distributionSetIdName) { diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettag/CreateUpdateTargetTagLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettag/CreateUpdateTargetTagLayout.java index 51ac77f10..79a44c38c 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettag/CreateUpdateTargetTagLayout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettag/CreateUpdateTargetTagLayout.java @@ -85,16 +85,22 @@ public class CreateUpdateTargetTagLayout extends CreateUpdateTagLayout { } @EventBusListenerMethod(scope = EventScope.SESSION) + // Exception squid:S1172 - event not needed + @SuppressWarnings({ "squid:S1172" }) void onEventTargetTagCreated(final TargetTagCreatedBulkEvent event) { populateTagNameCombo(); } @EventBusListenerMethod(scope = EventScope.SESSION) + // Exception squid:S1172 - event not needed + @SuppressWarnings({ "squid:S1172" }) void onEventTargetDeletedEvent(final TargetTagDeletedEvent event) { populateTagNameCombo(); } @EventBusListenerMethod(scope = EventScope.SESSION) + // Exception squid:S1172 - event not needed + @SuppressWarnings({ "squid:S1172" }) void onEventTargetTagUpdateEvent(final TargetTagUpdateEvent event) { populateTagNameCombo(); } @@ -144,7 +150,7 @@ public class CreateUpdateTargetTagLayout extends CreateUpdateTagLayout { final TargetTag existingTag = tagManagement.findTargetTag(tagName.getValue()); if (optiongroup.getValue().equals(createTagNw)) { if (!checkIsDuplicate(existingTag)) { - crateNewTag(); + createNewTag(); } } else { @@ -182,8 +188,8 @@ public class CreateUpdateTargetTagLayout extends CreateUpdateTagLayout { /** * Create new tag. */ - private void crateNewTag() { - final String colorPicked = getColorPickedSting(); + private void createNewTag() { + final String colorPicked = getColorPickedString(); final String tagNameValue = HawkbitCommonUtil.trimAndNullIfEmpty(tagName.getValue()); final String tagDescValue = HawkbitCommonUtil.trimAndNullIfEmpty(tagDesc.getValue()); if (null != tagNameValue) { @@ -214,7 +220,7 @@ public class CreateUpdateTargetTagLayout extends CreateUpdateTagLayout { if (null != nameUpdateValue) { targetObj.setName(nameUpdateValue); targetObj.setDescription(null != descUpdateValue ? descUpdateValue : null); - targetObj.setColour(getColorPickedSting()); + targetObj.setColour(getColorPickedString()); tagManagement.updateTargetTag(targetObj); uiNotification.displaySuccess(i18n.get("message.update.success", new Object[] { targetObj.getName() })); closeWindow(); @@ -244,7 +250,7 @@ public class CreateUpdateTargetTagLayout extends CreateUpdateTagLayout { * * @return String of color picked value. */ - private String getColorPickedSting() { + private String getColorPickedString() { return "rgb(" + getSelPreview().getColor().getRed() + "," + getSelPreview().getColor().getGreen() + "," + getSelPreview().getColor().getBlue() + ")"; } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettag/TargetTagFilterButtons.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettag/TargetTagFilterButtons.java index 9d93962da..48447f112 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettag/TargetTagFilterButtons.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettag/TargetTagFilterButtons.java @@ -8,23 +8,20 @@ */ package org.eclipse.hawkbit.ui.management.targettag; -import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; -import javax.annotation.PreDestroy; - import org.eclipse.hawkbit.eventbus.event.TargetTagCreatedBulkEvent; import org.eclipse.hawkbit.eventbus.event.TargetTagDeletedEvent; import org.eclipse.hawkbit.eventbus.event.TargetTagUpdateEvent; import org.eclipse.hawkbit.repository.SpPermissionChecker; -import org.eclipse.hawkbit.repository.TagManagement; import org.eclipse.hawkbit.repository.TargetManagement; import org.eclipse.hawkbit.repository.model.TargetIdName; import org.eclipse.hawkbit.repository.model.TargetTag; -import org.eclipse.hawkbit.repository.model.TargetTagAssigmentResult; +import org.eclipse.hawkbit.repository.model.TargetTagAssignmentResult; import org.eclipse.hawkbit.ui.common.filterlayout.AbstractFilterButtons; +import org.eclipse.hawkbit.ui.common.table.AbstractTable; import org.eclipse.hawkbit.ui.management.event.DragEvent; import org.eclipse.hawkbit.ui.management.event.ManagementUIEvent; import org.eclipse.hawkbit.ui.management.event.ManagementViewAcceptCriteria; @@ -39,7 +36,6 @@ import org.eclipse.hawkbit.ui.utils.UINotification; import org.springframework.beans.factory.annotation.Autowired; import org.vaadin.addons.lazyquerycontainer.BeanQueryFactory; import org.vaadin.addons.lazyquerycontainer.LazyQueryContainer; -import org.vaadin.spring.events.EventBus; import org.vaadin.spring.events.EventScope; import org.vaadin.spring.events.annotation.EventBusListenerMethod; @@ -64,15 +60,9 @@ public class TargetTagFilterButtons extends AbstractFilterButtons { private static final long serialVersionUID = 5049554600376508073L; - @Autowired - private transient EventBus.SessionEventBus eventBus; - @Autowired private ManagementUIState managementUIState; - @Autowired - private transient TagManagement tagMgmtService; - @Autowired private ManagementViewAcceptCriteria managementViewAcceptCriteria; @@ -88,8 +78,6 @@ public class TargetTagFilterButtons extends AbstractFilterButtons { @Autowired private transient TargetManagement targetManagement; - private static final String ITEMID = "itemId"; - TargetTagFilterButtonClick filterButtonClickBehaviour; /** @@ -103,12 +91,6 @@ public class TargetTagFilterButtons extends AbstractFilterButtons { this.filterButtonClickBehaviour = filterButtonClickBehaviour; super.init(filterButtonClickBehaviour); addNewTargetTag(new TargetTag("NO TAG")); - eventBus.subscribe(this); - } - - @PreDestroy - void destroy() { - eventBus.unsubscribe(this); } @EventBusListenerMethod(scope = EventScope.SESSION) @@ -139,10 +121,9 @@ public class TargetTagFilterButtons extends AbstractFilterButtons { } @Override - protected boolean isClickedByDefault(final Long buttonId) { - final TargetTag newTagClickedObj = tagMgmtService.findTargetTagById(buttonId); - return managementUIState.getTargetTableFilters().getClickedTargetTags() != null && managementUIState - .getTargetTableFilters().getClickedTargetTags().contains(newTagClickedObj.getName()); + protected boolean isClickedByDefault(final String tagName) { + return managementUIState.getTargetTableFilters().getClickedTargetTags() != null + && managementUIState.getTargetTableFilters().getClickedTargetTags().contains(tagName); } @Override @@ -229,35 +210,46 @@ public class TargetTagFilterButtons extends AbstractFilterButtons { } private void processTargetDrop(final DragAndDropEvent event) { - final com.vaadin.event.dd.TargetDetails targetDetails = event.getTargetDetails(); final TableTransferable transferable = (TableTransferable) event.getTransferable(); - final Table source = transferable.getSourceComponent(); + @SuppressWarnings("unchecked") + final AbstractTable targetTable = (AbstractTable) transferable + .getSourceComponent(); - final Set targetSelected = HawkbitCommonUtil.getSelectedTargetDetails(source); - final Set targetList = new HashSet<>(); - if (transferable.getData(ITEMID) != null) { - if (!targetSelected.contains(transferable.getData(ITEMID))) { - targetList.add(((TargetIdName) transferable.getData(ITEMID)).getControllerId()); - } else { - targetList.addAll(targetSelected.stream().map(t -> t.getControllerId()).collect(Collectors.toList())); - } + final Set targetSelected = targetTable.getDeletedEntityByTransferable(transferable); + final Set targetList = targetSelected.stream().map(t -> t.getControllerId()) + .collect(Collectors.toSet()); - final String targTagName = HawkbitCommonUtil.removePrefix(targetDetails.getTarget().getId(), - SPUIDefinitions.TARGET_TAG_ID_PREFIXS); + final String targTagName = HawkbitCommonUtil.removePrefix(targetDetails.getTarget().getId(), + SPUIDefinitions.TARGET_TAG_ID_PREFIXS); - final List tagsClickedList = managementUIState.getTargetTableFilters().getClickedTargetTags(); + final TargetTagAssignmentResult result = targetManagement.toggleTagAssignment(targetList, targTagName); + notification.displaySuccess(HawkbitCommonUtil.createAssignmentMessage(targTagName, result, i18n)); - final TargetTagAssigmentResult result = targetManagement.toggleTagAssignment(targetList, targTagName); - notification.displaySuccess(HawkbitCommonUtil.getTargetTagAssigmentMsg(targTagName, result, i18n)); + publishAssignTargetTagEvent(result); - if (result.getAssigned() >= 1 && managementUIState.getTargetTableFilters().isNoTagSelected()) { - eventBus.publish(this, ManagementUIEvent.ASSIGN_TARGET_TAG); - } - if (result.getUnassigned() >= 1 && !tagsClickedList.isEmpty() && tagsClickedList.contains(targTagName)) { - eventBus.publish(this, ManagementUIEvent.UNASSIGN_TARGET_TAG); - } + publishUnAssignTargetTagEvent(targTagName, result); + + } + + private void publishUnAssignTargetTagEvent(final String targTagName, final TargetTagAssignmentResult result) { + final List tagsClickedList = managementUIState.getTargetTableFilters().getClickedTargetTags(); + final boolean isTargetTagUnAssigned = result.getUnassigned() >= 1 && !tagsClickedList.isEmpty() + && tagsClickedList.contains(targTagName); + + if (!isTargetTagUnAssigned) { + return; } + eventBus.publish(this, ManagementUIEvent.UNASSIGN_TARGET_TAG); + } + + private void publishAssignTargetTagEvent(final TargetTagAssignmentResult result) { + final boolean isNewTargetTagAssigned = result.getAssigned() >= 1 + && managementUIState.getTargetTableFilters().isNoTagSelected(); + if (!isNewTargetTagAssigned) { + return; + } + eventBus.publish(this, ManagementUIEvent.ASSIGN_TARGET_TAG); } private boolean validateIfSourceisTargetTable(final Table source) { @@ -275,16 +267,22 @@ public class TargetTagFilterButtons extends AbstractFilterButtons { } @EventBusListenerMethod(scope = EventScope.SESSION) + // Exception squid:S1172 - event not needed + @SuppressWarnings({ "squid:S1172" }) void onEvent(final TargetTagUpdateEvent event) { refreshContainer(); } @EventBusListenerMethod(scope = EventScope.SESSION) + // Exception squid:S1172 - event not needed + @SuppressWarnings({ "squid:S1172" }) void onEventTargetTagCreated(final TargetTagCreatedBulkEvent event) { refreshContainer(); } @EventBusListenerMethod(scope = EventScope.SESSION) + // Exception squid:S1172 - event not needed + @SuppressWarnings({ "squid:S1172" }) void onEventTargetDeletedEvent(final TargetTagDeletedEvent event) { refreshContainer(); } @@ -304,6 +302,7 @@ public class TargetTagFilterButtons extends AbstractFilterButtons { } } + @SuppressWarnings("unchecked") private void addNewTargetTag(final TargetTag newTargetTag) { final LazyQueryContainer targetTagContainer = (LazyQueryContainer) getContainerDataSource(); final Object addItem = targetTagContainer.addItem(); diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettag/TargetTagFilterHeader.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettag/TargetTagFilterHeader.java index 7d0b5c76c..6093843fd 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettag/TargetTagFilterHeader.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/management/targettag/TargetTagFilterHeader.java @@ -10,14 +10,12 @@ package org.eclipse.hawkbit.ui.management.targettag; import javax.annotation.PostConstruct; -import org.eclipse.hawkbit.repository.SpPermissionChecker; import org.eclipse.hawkbit.ui.common.filterlayout.AbstractFilterHeader; import org.eclipse.hawkbit.ui.management.event.ManagementUIEvent; import org.eclipse.hawkbit.ui.management.state.ManagementUIState; import org.eclipse.hawkbit.ui.utils.I18N; import org.eclipse.hawkbit.ui.utils.SPUIComponetIdProvider; import org.springframework.beans.factory.annotation.Autowired; -import org.vaadin.spring.events.EventBus; import com.vaadin.spring.annotation.SpringComponent; import com.vaadin.spring.annotation.ViewScope; @@ -32,15 +30,9 @@ public class TargetTagFilterHeader extends AbstractFilterHeader { private static final long serialVersionUID = 3046367045669148009L; - @Autowired - private SpPermissionChecker permChecker; - @Autowired private I18N i18n; - @Autowired - private transient EventBus.SessionEventBus eventbus; - @Autowired private CreateUpdateTargetTagLayout createUpdateTargetTagLayout; @@ -58,7 +50,6 @@ public class TargetTagFilterHeader extends AbstractFilterHeader { @Override protected String getHideButtonId() { - return SPUIComponetIdProvider.HIDE_TARGET_TAGS; } @@ -87,7 +78,7 @@ public class TargetTagFilterHeader extends AbstractFilterHeader { @Override protected void hideFilterButtonLayout() { managementUIState.setTargetTagFilterClosed(true); - eventbus.publish(this, ManagementUIEvent.HIDE_TARGET_TAG_LAYOUT); + eventBus.publish(this, ManagementUIEvent.HIDE_TARGET_TAG_LAYOUT); } @Override diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/menu/DashboardMenu.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/menu/DashboardMenu.java index bbbba8cec..8699f8a87 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/menu/DashboardMenu.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/menu/DashboardMenu.java @@ -18,23 +18,20 @@ import java.util.List; import java.util.Optional; import java.util.stream.Collectors; +import org.apache.commons.lang3.StringUtils; import org.eclipse.hawkbit.HawkbitServerProperties; import org.eclipse.hawkbit.im.authentication.PermissionService; -import org.eclipse.hawkbit.im.authentication.UserPrincipal; import org.eclipse.hawkbit.ui.UiProperties; +import org.eclipse.hawkbit.ui.common.UserDetailsFormatter; import org.eclipse.hawkbit.ui.components.SPUIComponentProvider; import org.eclipse.hawkbit.ui.menu.DashboardEvent.PostViewChangeEvent; import org.eclipse.hawkbit.ui.utils.I18N; import org.eclipse.hawkbit.ui.utils.SPUIComponetIdProvider; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.core.context.SecurityContext; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.security.web.context.HttpSessionSecurityContextRepository; import com.vaadin.server.FontAwesome; import com.vaadin.server.Page; import com.vaadin.server.ThemeResource; -import com.vaadin.server.VaadinService; import com.vaadin.shared.ui.label.ContentMode; import com.vaadin.spring.annotation.SpringComponent; import com.vaadin.spring.annotation.UIScope; @@ -115,9 +112,9 @@ public final class DashboardMenu extends CustomComponent { final VerticalLayout links = buildLinksAndVersion(); menus.addComponent(links); menus.setComponentAlignment(links, Alignment.BOTTOM_CENTER); - menus.setExpandRatio(links, 1.0f); + menus.setExpandRatio(links, 1.0F); menuContent.addComponent(menus); - menuContent.setExpandRatio(menus, 1.0f); + menuContent.setExpandRatio(menus, 1.0F); dashboardMenuLayout.addComponent(menuContent); return dashboardMenuLayout; @@ -139,7 +136,7 @@ public final class DashboardMenu extends CustomComponent { final Label logo = new Label("" + i18n.get("menu.title") + "", ContentMode.HTML); logo.setSizeUndefined(); final HorizontalLayout logoWrapper = new HorizontalLayout(logo); - logoWrapper.setComponentAlignment(logo, Alignment.MIDDLE_CENTER); + logoWrapper.setComponentAlignment(logo, Alignment.TOP_CENTER); logoWrapper.addStyleName("valo-menu-title"); return logoWrapper; } @@ -151,7 +148,7 @@ public final class DashboardMenu extends CustomComponent { final String linkStyle = "v-link"; if (!uiProperties.getLinks().getDocumentation().getRoot().isEmpty()) { - final Link docuLink = SPUIComponentProvider.getLink(SPUIComponetIdProvider.LINK_DOCUMENATION, + final Link docuLink = SPUIComponentProvider.getLink(SPUIComponetIdProvider.LINK_DOCUMENTATION, i18n.get("link.documentation.name"), uiProperties.getLinks().getDocumentation().getRoot(), FontAwesome.QUESTION_CIRCLE, "_blank", linkStyle, true); docuLink.setDescription(i18n.get("link.documentation.name")); @@ -189,63 +186,27 @@ public final class DashboardMenu extends CustomComponent { return links; } - private UserDetails getCurrentUser() { - final SecurityContext context = (SecurityContext) VaadinService.getCurrentRequest().getWrappedSession() - .getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY); - return (UserDetails) context.getAuthentication().getPrincipal(); - } - private Component buildUserMenu() { final MenuBar settings = new MenuBar(); settings.addStyleName("user-menu"); - final UserDetails user = getCurrentUser(); + settings.setHtmlContentAllowed(true); final MenuItem settingsItem = settings.addItem("", new ThemeResource("images/profile-pic-57px.jpg"), null); - if (user instanceof UserPrincipal - && (((UserPrincipal) user).getFirstname() != null || ((UserPrincipal) user).getLastname() != null)) { - settingsItem.setText(trimTanent(((UserPrincipal) user).getTenant()) + "\n" - + concateFNameLName(((UserPrincipal) user).getFirstname(), ((UserPrincipal) user).getLastname())); - settingsItem.setDescription( - ((UserPrincipal) user).getFirstname() + " / " + ((UserPrincipal) user).getLastname()); - } else if (user instanceof UserPrincipal) { - if (((UserPrincipal) user).getLoginname().length() > 10) { - settingsItem.setText(trimTanent(((UserPrincipal) user).getTenant()) + "\n" - + ((UserPrincipal) user).getLoginname().substring(0, 10) + ".."); - } else { - settingsItem.setText( - trimTanent(((UserPrincipal) user).getTenant()) + "\n" + ((UserPrincipal) user).getLoginname()); - } - settingsItem.setDescription(((UserPrincipal) user).getLoginname()); - } else if (user != null) { - settingsItem.setText(user.getUsername()); - settingsItem.setDescription(user.getUsername()); + + final String formattedTenant = UserDetailsFormatter.formatCurrentTenant(); + final String formattedUsername = UserDetailsFormatter.formatCurrentUsername(); + String tenantAndUsernameHtml = ""; + if (!StringUtils.isEmpty(formattedTenant)) { + tenantAndUsernameHtml += formattedTenant + "
    "; } + tenantAndUsernameHtml += formattedUsername; + settingsItem.setText(tenantAndUsernameHtml); + settingsItem.setDescription(formattedUsername); + settingsItem.setStyleName("user-menuitem"); settingsItem.addItem("Sign Out", selectedItem -> Page.getCurrent().setLocation("/UI/logout")); return settings; } - private String concateFNameLName(final String fName, final String lName) { - final StringBuilder userName = new StringBuilder(); - if (fName != null && fName.length() > 6) { - userName.append(fName.substring(0, 6) + ".." + ", "); - } else { - userName.append(fName).append(", "); - } - if (lName != null && lName.length() > 6) { - userName.append(lName.substring(0, 6) + ".."); - } else { - userName.append(lName); - } - return userName.toString(); - } - - private String trimTanent(final String tanent) { - if (tanent != null && tanent.length() > 8) { - return tanent.substring(0, 8) + ".."; - } - return tanent; - } - private Component buildToggleButton() { final Button valoMenuToggleButton = new Button("Menu", (ClickListener) event -> { if (getCompositionRoot().getStyleName().contains(STYLE_VISIBLE)) { @@ -264,7 +225,7 @@ public final class DashboardMenu extends CustomComponent { private VerticalLayout buildMenuItems() { final VerticalLayout menuItemsLayout = new VerticalLayout(); menuItemsLayout.addStyleName("valo-menuitems"); - menuItemsLayout.setHeight(100.0f, Unit.PERCENTAGE); + menuItemsLayout.setHeight(100.0F, Unit.PERCENTAGE); final List accessibleViews = getAccessibleViews(); if (accessibleViews.isEmpty()) { diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/push/DelayedEventBusPushStrategy.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/push/DelayedEventBusPushStrategy.java index 87fcbe922..023979ead 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/push/DelayedEventBusPushStrategy.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/push/DelayedEventBusPushStrategy.java @@ -19,15 +19,9 @@ import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; -import org.eclipse.hawkbit.eventbus.event.DistributionSetTagCreatedBulkEvent; import org.eclipse.hawkbit.eventbus.event.EntityEvent; -import org.eclipse.hawkbit.eventbus.event.RolloutChangeEvent; -import org.eclipse.hawkbit.eventbus.event.RolloutGroupChangeEvent; -import org.eclipse.hawkbit.eventbus.event.TargetCreatedEvent; -import org.eclipse.hawkbit.eventbus.event.TargetDeletedEvent; -import org.eclipse.hawkbit.eventbus.event.TargetInfoUpdateEvent; -import org.eclipse.hawkbit.eventbus.event.TargetTagCreatedBulkEvent; import org.eclipse.hawkbit.im.authentication.TenantAwareAuthenticationDetails; +import org.eclipse.hawkbit.ui.UIEventProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.core.context.SecurityContext; @@ -36,7 +30,6 @@ import org.springframework.security.web.context.HttpSessionSecurityContextReposi import org.vaadin.spring.events.EventBus; import org.vaadin.spring.events.EventBus.SessionEventBus; -import com.google.common.collect.Sets; import com.google.common.eventbus.AllowConcurrentEvents; import com.google.common.eventbus.Subscribe; import com.vaadin.server.VaadinSession; @@ -49,15 +42,15 @@ import com.vaadin.ui.UI; * {@link com.google.common.eventbus.EventBus} and store them first in an queue * where they will dispatched every 2 seconds to the {@link EventBus} in a * Vaadin access thread {@link UI#access(Runnable)}. - * + * * This strategy avoids blocking UIs when too many events are fired and * dispatched to the UI thread. The UI will freeze in the time. To avoid that * all events are collected first and same events are merged to a list of events * before they dispatched to the UI thread. - * + * * The strategy also verifies the current tenant in the session with the tenant * in the event and only forwards event from the right tenant to the UI. - * + * */ public class DelayedEventBusPushStrategy implements EventPushStrategy { @@ -71,16 +64,11 @@ public class DelayedEventBusPushStrategy implements EventPushStrategy { private ScheduledFuture jobHandle; - /** - * only events defined in the set are dispatched to the session event bus. - */ - private static final Set> UI_EVENTS = Sets.newHashSet(TargetInfoUpdateEvent.class, - TargetCreatedEvent.class, TargetDeletedEvent.class, RolloutChangeEvent.class, RolloutGroupChangeEvent.class, - TargetTagCreatedBulkEvent.class, DistributionSetTagCreatedBulkEvent.class); + private final UIEventProvider eventProvider; /** * Constructor. - * + * * @param eventBus * the session event bus to where the events should be dispatched * @param systemEventBus @@ -88,9 +76,10 @@ public class DelayedEventBusPushStrategy implements EventPushStrategy { * back-end */ public DelayedEventBusPushStrategy(final SessionEventBus eventBus, - final com.google.common.eventbus.EventBus systemEventBus) { + final com.google.common.eventbus.EventBus systemEventBus, final UIEventProvider eventProvider) { this.eventBus = eventBus; this.systemEventBus = systemEventBus; + this.eventProvider = eventProvider; } /** @@ -105,12 +94,22 @@ public class DelayedEventBusPushStrategy implements EventPushStrategy { @AllowConcurrentEvents public void dispatch(final org.eclipse.hawkbit.eventbus.event.Event event) { // to dispatch too many events which are not interested on the UI - if (UI_EVENTS.contains(event.getClass()) && !queue.offer(event)) { + if (!isEventProvided(event)) { + LOG.trace("Event is not supported in the UI!!! Dropped event is {}", event); + return; + } + + if (!queue.offer(event)) { LOG.warn("Deque limit is reached, cannot add more events!!! Dropped event is {}", event); return; } } + private boolean isEventProvided(final org.eclipse.hawkbit.eventbus.event.Event event) { + return eventProvider.getSingleEvents().contains(event.getClass()) + || eventProvider.getBulkEvents().contains(event.getClass()); + } + @Override public void init(final UI vaadinUI) { LOG.debug("Initialize delayed event push strategy"); @@ -131,7 +130,7 @@ public class DelayedEventBusPushStrategy implements EventPushStrategy { /** * Checks if the tenant within the event is equal with the current tenant in * the context. - * + * * @param userContext * the security context of the current session * @param event @@ -206,37 +205,43 @@ public class DelayedEventBusPushStrategy implements EventPushStrategy { final SecurityContext oldContext = SecurityContextHolder.getContext(); try { SecurityContextHolder.setContext(userContext); + vaadinUI.access(() -> { if (vaadinSession.getState() != State.OPEN) { return; } - fowardEvents(events, userContext); - - // send a list of events, because ui performance issues - publishEventAsList(events, userContext, TargetInfoUpdateEvent.class); - publishEventAsList(events, userContext, TargetCreatedEvent.class); - publishEventAsList(events, userContext, TargetDeletedEvent.class); + fowardSingleEvents(events, userContext); + fowardBulkEvents(events, userContext); }); } finally { SecurityContextHolder.setContext(oldContext); } } - private void publishEventAsList(final List events, - final SecurityContext userContext, final Class eventType) { - final List bulkEvents = events.stream() - .filter(event -> DelayedEventBusPushStrategy.this.eventSecurityCheck(userContext, event) - && eventType.isInstance(event)) - .collect(Collectors.toList()); - if (bulkEvents.isEmpty()) { - return; - } - eventBus.publish(vaadinUI, bulkEvents); + private void fowardBulkEvents(final List events, + final SecurityContext userContext) { + final Set> filterBulkEvenTypes = eventProvider.getFilteredBulkEventsType(events); + publishBulkEvent(events, userContext, filterBulkEvenTypes); } - private void fowardEvents(final List events, + private void publishBulkEvent(final List events, + final SecurityContext userContext, final Set> filterBulkEvenTypes) { + for (final Class bulkType : filterBulkEvenTypes) { + final List listBulkEvents = events.stream() + .filter(event -> DelayedEventBusPushStrategy.this.eventSecurityCheck(userContext, event) + && bulkType.isInstance(event)) + .collect(Collectors.toList()); + if (!listBulkEvents.isEmpty()) { + eventBus.publish(vaadinUI, listBulkEvents); + } + } + } + + private void fowardSingleEvents(final List events, final SecurityContext userContext) { - events.stream().filter(event -> DelayedEventBusPushStrategy.this.eventSecurityCheck(userContext, event)) + events.stream() + .filter(event -> DelayedEventBusPushStrategy.this.eventSecurityCheck(userContext, event) + && eventProvider.getSingleEvents().contains(event.getClass())) .forEach(event -> eventBus.publish(vaadinUI, event)); } } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rollout/AddUpdateRolloutWindowLayout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rollout/AddUpdateRolloutWindowLayout.java index e5e86c520..7e8d45e1b 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rollout/AddUpdateRolloutWindowLayout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rollout/AddUpdateRolloutWindowLayout.java @@ -209,6 +209,7 @@ public class AddUpdateRolloutWindowLayout extends CustomComponent { actionTypeOptionGroupLayout, linkToHelp, getSaveDiscardButtonLayout()); mainLayout.setComponentAlignment(linkToHelp, Alignment.BOTTOM_RIGHT); setCompositionRoot(mainLayout); + rolloutName.focus(); } private HorizontalLayout getGroupDetailsLayout() { diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rollout/DistributionBeanQuery.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rollout/DistributionBeanQuery.java index 74daf89d8..75d2741af 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rollout/DistributionBeanQuery.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rollout/DistributionBeanQuery.java @@ -18,6 +18,7 @@ import org.eclipse.hawkbit.repository.DistributionSetFilter; import org.eclipse.hawkbit.repository.DistributionSetFilter.DistributionSetFilterBuilder; import org.eclipse.hawkbit.repository.DistributionSetManagement; import org.eclipse.hawkbit.repository.model.DistributionSet; +import org.eclipse.hawkbit.ui.common.UserDetailsFormatter; import org.eclipse.hawkbit.ui.components.ProxyDistribution; import org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil; import org.eclipse.hawkbit.ui.utils.SPDateTimeUtil; @@ -62,7 +63,8 @@ public class DistributionBeanQuery extends AbstractBeanQuery sort = new Sort(sortStates[0] ? Direction.ASC : Direction.DESC, (String) sortPropertyIds[0]); // Add sort for (int distId = 1; distId < sortPropertyIds.length; distId++) { - sort.and(new Sort(sortStates[distId] ? Direction.ASC : Direction.DESC, (String) sortPropertyIds[distId])); + sort.and(new Sort(sortStates[distId] ? Direction.ASC : Direction.DESC, + (String) sortPropertyIds[distId])); } } } @@ -103,8 +105,8 @@ public class DistributionBeanQuery extends AbstractBeanQuery final List proxyDistributions = new ArrayList<>(); for (final DistributionSet distributionSet : distBeans) { final ProxyDistribution proxyDistribution = new ProxyDistribution(); - proxyDistribution.setName(HawkbitCommonUtil.getFormattedNameVersion(distributionSet.getName(), - distributionSet.getVersion())); + proxyDistribution.setName( + HawkbitCommonUtil.getFormattedNameVersion(distributionSet.getName(), distributionSet.getVersion())); proxyDistribution.setDescription(distributionSet.getDescription()); proxyDistribution.setDistId(distributionSet.getId()); proxyDistribution.setId(distributionSet.getId()); @@ -112,8 +114,8 @@ public class DistributionBeanQuery extends AbstractBeanQuery proxyDistribution.setCreatedDate(SPDateTimeUtil.getFormattedDate(distributionSet.getCreatedAt())); proxyDistribution.setLastModifiedDate(SPDateTimeUtil.getFormattedDate(distributionSet.getLastModifiedAt())); proxyDistribution.setDescription(distributionSet.getDescription()); - proxyDistribution.setCreatedByUser(HawkbitCommonUtil.getIMUser(distributionSet.getCreatedBy())); - proxyDistribution.setModifiedByUser(HawkbitCommonUtil.getIMUser(distributionSet.getLastModifiedBy())); + proxyDistribution.setCreatedByUser(UserDetailsFormatter.loadAndFormatCreatedBy(distributionSet)); + proxyDistribution.setModifiedByUser(UserDetailsFormatter.loadAndFormatLastModifiedBy(distributionSet)); proxyDistribution.setIsComplete(distributionSet.isComplete()); proxyDistributions.add(proxyDistribution); } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rollout/ProxyRollout.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rollout/ProxyRollout.java index b1309f8b9..04c6659a5 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rollout/ProxyRollout.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rollout/ProxyRollout.java @@ -8,12 +8,16 @@ */ package org.eclipse.hawkbit.ui.rollout.rollout; +import java.util.Set; + import org.eclipse.hawkbit.repository.model.Rollout; +import org.eclipse.hawkbit.repository.model.SoftwareModule; +import org.eclipse.hawkbit.ui.customrenderers.client.renderers.RolloutRendererData; import com.vaadin.server.FontAwesome; /** - * Proxy rollout with suctome properties. + * Proxy rollout with custom properties. * */ public class ProxyRollout extends Rollout { @@ -30,8 +34,92 @@ public class ProxyRollout extends Rollout { private Boolean isActionRecieved = Boolean.FALSE; + private Boolean isRequiredMigrationStep = Boolean.FALSE; + private String totalTargetsCount; - + + private RolloutRendererData rolloutRendererData; + + private String discription; + + private String type; + + private Set swModules; + + /** + * @return the isRequiredMigrationStep + */ + + public Boolean getIsRequiredMigrationStep() { + return isRequiredMigrationStep; + } + + /** + * @param isRequiredMigrationStep + * the isRequiredMigrationStep to set + */ + + public void setIsRequiredMigrationStep(Boolean isRequiredMigrationStep) { + this.isRequiredMigrationStep = isRequiredMigrationStep; + } + + /** + * @return the discription + */ + + public String getDiscription() { + return discription; + } + + /** + * @param discription + * the discription to set + */ + + public void setDiscription(String discription) { + this.discription = discription; + } + + /** + * @return the type + */ + public String getType() { + return type; + } + + /** + * @param type + * the type to set + */ + + public void setType(String type) { + this.type = type; + } + + /** + * + * @return the Set of Software modules + */ + public Set getSwModules() { + return swModules; + } + + /** + * @param swModules + * Set to set + */ + public void setSwModules(Set swModules) { + this.swModules = swModules; + } + + public RolloutRendererData getRolloutRendererData() { + return rolloutRendererData; + } + + public void setRolloutRendererData(RolloutRendererData rendererData) { + this.rolloutRendererData = rendererData; + } + /** * @return the distributionSetNameVersion */ @@ -121,10 +209,9 @@ public class ProxyRollout extends Rollout { public void setTotalTargetsCount(final String totalTargetsCount) { this.totalTargetsCount = totalTargetsCount; } - - - public String getAction() { + + public String getAction() { return FontAwesome.CIRCLE_O.getHtml(); } - + } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rollout/RolloutBeanQuery.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rollout/RolloutBeanQuery.java index 5ab6f6a97..8a9675564 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rollout/RolloutBeanQuery.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rollout/RolloutBeanQuery.java @@ -17,6 +17,8 @@ import org.eclipse.hawkbit.repository.TargetFilterQueryManagement; import org.eclipse.hawkbit.repository.model.DistributionSet; import org.eclipse.hawkbit.repository.model.Rollout; import org.eclipse.hawkbit.repository.model.TotalTargetCountStatus; +import org.eclipse.hawkbit.ui.common.UserDetailsFormatter; +import org.eclipse.hawkbit.ui.customrenderers.client.renderers.RolloutRendererData; import org.eclipse.hawkbit.ui.rollout.state.RolloutUIState; import org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil; import org.eclipse.hawkbit.ui.utils.SPDateTimeUtil; @@ -119,22 +121,29 @@ public class RolloutBeanQuery extends AbstractBeanQuery { proxyRollout.setName(rollout.getName()); proxyRollout.setDescription(rollout.getDescription()); final DistributionSet distributionSet = rollout.getDistributionSet(); - proxyRollout.setDistributionSetNameVersion(HawkbitCommonUtil.getFormattedNameVersion( - distributionSet.getName(), distributionSet.getVersion())); + proxyRollout.setDistributionSetNameVersion( + HawkbitCommonUtil.getFormattedNameVersion(distributionSet.getName(), distributionSet.getVersion())); proxyRollout.setDistributionSet(distributionSet); proxyRollout.setNumberOfGroups(Long.valueOf(rollout.getRolloutGroups().size())); proxyRollout.setCreatedDate(SPDateTimeUtil.getFormattedDate(rollout.getCreatedAt())); proxyRollout.setModifiedDate(SPDateTimeUtil.getFormattedDate(rollout.getLastModifiedAt())); - proxyRollout.setCreatedBy(HawkbitCommonUtil.getIMUser(rollout.getCreatedBy())); - proxyRollout.setLastModifiedBy(HawkbitCommonUtil.getIMUser(rollout.getLastModifiedBy())); + proxyRollout.setCreatedBy(UserDetailsFormatter.loadAndFormatCreatedBy(rollout)); + proxyRollout.setLastModifiedBy(UserDetailsFormatter.loadAndFormatLastModifiedBy(rollout)); proxyRollout.setForcedTime(rollout.getForcedTime()); proxyRollout.setId(rollout.getId()); proxyRollout.setStatus(rollout.getStatus()); + proxyRollout + .setRolloutRendererData(new RolloutRendererData(rollout.getName(), rollout.getStatus().toString())); final TotalTargetCountStatus totalTargetCountActionStatus = rollout.getTotalTargetCountStatus(); proxyRollout.setTotalTargetCountStatus(totalTargetCountActionStatus); proxyRollout.setTotalTargetsCount(String.valueOf(rollout.getTotalTargets())); - + + proxyRollout.setDescription(distributionSet.getDescription()); + proxyRollout.setType(distributionSet.getType().getName()); + proxyRollout.setIsRequiredMigrationStep(distributionSet.isRequiredMigrationStep()); + proxyRollout.setSwModules(distributionSet.getModules()); + proxyRolloutList.add(proxyRollout); } return proxyRolloutList; @@ -148,7 +157,8 @@ public class RolloutBeanQuery extends AbstractBeanQuery { * .util.List, java.util.List, java.util.List) */ @Override - protected void saveBeans(final List arg0, final List arg1, final List arg2) { + protected void saveBeans(final List arg0, final List arg1, + final List arg2) { /** * CRUD operations on Target will be done through repository methods */ 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..7f3877a9a 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 @@ -8,32 +8,36 @@ */ package org.eclipse.hawkbit.ui.rollout.rollout; +import static org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil.HTML_LI_CLOSE_TAG; +import static org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil.HTML_LI_OPEN_TAG; +import static org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil.HTML_UL_CLOSE_TAG; +import static org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil.HTML_UL_OPEN_TAG; + import java.util.ArrayList; import java.util.Arrays; import java.util.EnumMap; import java.util.List; import java.util.Locale; import java.util.Map; - -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; +import java.util.Set; import org.eclipse.hawkbit.eventbus.event.RolloutChangeEvent; import org.eclipse.hawkbit.repository.RolloutManagement; import org.eclipse.hawkbit.repository.SpPermissionChecker; import org.eclipse.hawkbit.repository.model.Rollout; import org.eclipse.hawkbit.repository.model.Rollout.RolloutStatus; +import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.repository.model.TotalTargetCountStatus; import org.eclipse.hawkbit.ui.common.grid.AbstractGrid; +import org.eclipse.hawkbit.ui.customrenderers.client.renderers.RolloutRendererData; import org.eclipse.hawkbit.ui.customrenderers.renderers.HtmlButtonRenderer; import org.eclipse.hawkbit.ui.customrenderers.renderers.HtmlLabelRenderer; -import org.eclipse.hawkbit.ui.customrenderers.renderers.LinkRenderer; +import org.eclipse.hawkbit.ui.customrenderers.renderers.RolloutRenderer; import org.eclipse.hawkbit.ui.rollout.DistributionBarHelper; import org.eclipse.hawkbit.ui.rollout.StatusFontIcon; import org.eclipse.hawkbit.ui.rollout.event.RolloutEvent; import org.eclipse.hawkbit.ui.rollout.state.RolloutUIState; import org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil; -import org.eclipse.hawkbit.ui.utils.I18N; import org.eclipse.hawkbit.ui.utils.SPUIComponetIdProvider; import org.eclipse.hawkbit.ui.utils.SPUIDefinitions; import org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions; @@ -46,7 +50,6 @@ import org.vaadin.addons.lazyquerycontainer.LazyQueryDefinition; import org.vaadin.peter.contextmenu.ContextMenu; import org.vaadin.peter.contextmenu.ContextMenu.ContextMenuItem; import org.vaadin.peter.contextmenu.ContextMenu.ContextMenuItemClickEvent; -import org.vaadin.spring.events.EventBus; import org.vaadin.spring.events.EventScope; import org.vaadin.spring.events.annotation.EventBusListenerMethod; @@ -82,11 +85,13 @@ public class RolloutListGrid extends AbstractGrid { private static final String START_OPTION = "Start"; - @Autowired - private I18N i18n; + private static final String DS_TYPE = "type"; - @Autowired - private transient EventBus.SessionEventBus eventBus; + private static final String SW_MODULES = "swModules"; + + private static final String IS_REQUIRED_MIGRATION_STEP = "isRequiredMigrationStep"; + + private static final String ROLLOUT_RENDERER_DATA = "rolloutRendererData"; @Autowired private transient RolloutManagement rolloutManagement; @@ -105,18 +110,10 @@ public class RolloutListGrid extends AbstractGrid { private transient Map statusIconMap = new EnumMap<>(RolloutStatus.class); - @Override - @PostConstruct - protected void init() { - super.init(); - eventBus.subscribe(this); - } - - @PreDestroy - void destroy() { - eventBus.unsubscribe(this); - } - + /** + * Handles the RolloutEvent to refresh Grid. + * + */ @EventBusListenerMethod(scope = EventScope.SESSION) void onEvent(final RolloutEvent event) { switch (event) { @@ -153,10 +150,16 @@ public class RolloutListGrid extends AbstractGrid { item.getItemProperty(SPUILabelDefinitions.VAR_STATUS).setValue(rollout.getStatus()); item.getItemProperty(SPUILabelDefinitions.VAR_TOTAL_TARGETS_COUNT_STATUS).setValue(totalTargetCountStatus); final Long groupCount = (Long) item.getItemProperty(SPUILabelDefinitions.VAR_NUMBER_OF_GROUPS).getValue(); - if (rollout.getRolloutGroups() != null && groupCount != rollout.getRolloutGroups().size()) { + final int groupsCreated = rollout.getRolloutGroupsCreated(); + if (groupsCreated != 0) { + item.getItemProperty(SPUILabelDefinitions.VAR_NUMBER_OF_GROUPS).setValue(Long.valueOf(groupsCreated)); + } else if (rollout.getRolloutGroups() != null && groupCount != rollout.getRolloutGroups().size()) { item.getItemProperty(SPUILabelDefinitions.VAR_NUMBER_OF_GROUPS) .setValue(Long.valueOf(rollout.getRolloutGroups().size())); } + item.getItemProperty(ROLLOUT_RENDERER_DATA) + .setValue(new RolloutRendererData(rollout.getName(), rollout.getStatus().toString())); + } @Override @@ -170,7 +173,11 @@ public class RolloutListGrid extends AbstractGrid { protected void addContainerProperties() { final LazyQueryContainer rolloutGridContainer = (LazyQueryContainer) getContainerDataSource(); rolloutGridContainer.addContainerProperty(SPUILabelDefinitions.VAR_NAME, String.class, "", false, false); + rolloutGridContainer.addContainerProperty(DS_TYPE, String.class, null, false, false); + rolloutGridContainer.addContainerProperty(SW_MODULES, Set.class, null, false, false); + rolloutGridContainer.addContainerProperty(ROLLOUT_RENDERER_DATA, RolloutRendererData.class, null, false, false); rolloutGridContainer.addContainerProperty(SPUILabelDefinitions.VAR_DESC, String.class, null, false, false); + rolloutGridContainer.addContainerProperty(IS_REQUIRED_MIGRATION_STEP, boolean.class, null, false, false); rolloutGridContainer.addContainerProperty(SPUILabelDefinitions.VAR_STATUS, RolloutStatus.class, null, false, false); rolloutGridContainer.addContainerProperty(SPUILabelDefinitions.VAR_DIST_NAME_VERSION, String.class, null, false, @@ -184,7 +191,7 @@ public class RolloutListGrid extends AbstractGrid { false); rolloutGridContainer.addContainerProperty(SPUILabelDefinitions.VAR_MODIFIED_BY, String.class, null, false, false); - rolloutGridContainer.addContainerProperty(SPUILabelDefinitions.VAR_NUMBER_OF_GROUPS, Integer.class, 0, false, + rolloutGridContainer.addContainerProperty(SPUILabelDefinitions.VAR_NUMBER_OF_GROUPS, Long.class, 0, false, false); rolloutGridContainer.addContainerProperty(SPUILabelDefinitions.VAR_TOTAL_TARGETS, String.class, "0", false, false); @@ -198,8 +205,9 @@ public class RolloutListGrid extends AbstractGrid { @Override protected void setColumnExpandRatio() { - getColumn(SPUILabelDefinitions.VAR_NAME).setMinimumWidth(40); - getColumn(SPUILabelDefinitions.VAR_NAME).setMaximumWidth(150); + + getColumn(ROLLOUT_RENDERER_DATA).setMinimumWidth(40); + getColumn(ROLLOUT_RENDERER_DATA).setMaximumWidth(150); getColumn(SPUILabelDefinitions.VAR_DIST_NAME_VERSION).setMinimumWidth(40); getColumn(SPUILabelDefinitions.VAR_DIST_NAME_VERSION).setMaximumWidth(150); @@ -223,7 +231,10 @@ public class RolloutListGrid extends AbstractGrid { @Override protected void setColumnHeaderNames() { - getColumn(SPUILabelDefinitions.VAR_NAME).setHeaderCaption(i18n.get("header.name")); + getColumn(ROLLOUT_RENDERER_DATA).setHeaderCaption(i18n.get("header.name")); + getColumn(DS_TYPE).setHeaderCaption("Type"); + getColumn(SW_MODULES).setHeaderCaption("swModules"); + getColumn(IS_REQUIRED_MIGRATION_STEP).setHeaderCaption("IsRequiredMigrationStep"); getColumn(SPUILabelDefinitions.VAR_DIST_NAME_VERSION).setHeaderCaption(i18n.get("header.distributionset")); getColumn(SPUILabelDefinitions.VAR_NUMBER_OF_GROUPS).setHeaderCaption(i18n.get("header.numberofgroups")); getColumn(SPUILabelDefinitions.VAR_TOTAL_TARGETS).setHeaderCaption(i18n.get("header.total.targets")); @@ -245,9 +256,12 @@ public class RolloutListGrid extends AbstractGrid { @Override protected void setColumnProperties() { - List columnList = new ArrayList<>(); - columnList.add(SPUILabelDefinitions.VAR_NAME); + final List columnList = new ArrayList<>(); + columnList.add(ROLLOUT_RENDERER_DATA); columnList.add(SPUILabelDefinitions.VAR_DIST_NAME_VERSION); + columnList.add(DS_TYPE); + columnList.add(SW_MODULES); + columnList.add(IS_REQUIRED_MIGRATION_STEP); columnList.add(SPUILabelDefinitions.VAR_STATUS); columnList.add(SPUILabelDefinitions.VAR_TOTAL_TARGETS_COUNT_STATUS); columnList.add(SPUILabelDefinitions.VAR_NUMBER_OF_GROUPS); @@ -265,13 +279,17 @@ public class RolloutListGrid extends AbstractGrid { @Override protected void setHiddenColumns() { - List columnsToBeHidden = new ArrayList<>(); + final List columnsToBeHidden = new ArrayList<>(); + columnsToBeHidden.add(SPUILabelDefinitions.VAR_NAME); columnsToBeHidden.add(SPUILabelDefinitions.VAR_CREATED_DATE); columnsToBeHidden.add(SPUILabelDefinitions.VAR_CREATED_USER); columnsToBeHidden.add(SPUILabelDefinitions.VAR_MODIFIED_DATE); columnsToBeHidden.add(SPUILabelDefinitions.VAR_MODIFIED_BY); columnsToBeHidden.add(SPUILabelDefinitions.VAR_DESC); - for (Object propertyId : columnsToBeHidden) { + columnsToBeHidden.add(IS_REQUIRED_MIGRATION_STEP); + columnsToBeHidden.add(DS_TYPE); + columnsToBeHidden.add(SW_MODULES); + for (final Object propertyId : columnsToBeHidden) { getColumn(propertyId).setHidden(true); } @@ -284,6 +302,8 @@ public class RolloutListGrid extends AbstractGrid { @Override protected void addColumnRenderes() { + getColumn(SPUILabelDefinitions.VAR_NUMBER_OF_GROUPS).setRenderer(new HtmlRenderer(), + new TotalTargetGroupsConverter()); getColumn(SPUILabelDefinitions.VAR_TOTAL_TARGETS_COUNT_STATUS).setRenderer(new HtmlRenderer(), new TotalTargetCountStatusConverter()); @@ -291,7 +311,11 @@ public class RolloutListGrid extends AbstractGrid { getColumn(SPUILabelDefinitions.VAR_STATUS).setRenderer(new HtmlLabelRenderer(), new RolloutStatusConverter()); getColumn(SPUILabelDefinitions.ACTION).setRenderer(new HtmlButtonRenderer(event -> onClickOfActionBtn(event))); - getColumn(SPUILabelDefinitions.VAR_NAME).setRenderer(new LinkRenderer(event -> onClickOfRolloutName(event))); + + final RolloutRenderer customObjectRenderer = new RolloutRenderer(RolloutRendererData.class); + customObjectRenderer.addClickListener(event -> onClickOfRolloutName(event)); + getColumn(ROLLOUT_RENDERER_DATA).setRenderer(customObjectRenderer); + } private void createRolloutStatusToFontMap() { @@ -318,7 +342,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 +351,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 +401,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 +410,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(); @@ -436,17 +448,20 @@ public class RolloutListGrid extends AbstractGrid { ((LazyQueryContainer) getContainerDataSource()).refresh(); } + /** + * Generator to generate fontIcon by String. + */ public final class FontIconGenerator extends PropertyValueGenerator { 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,20 +471,59 @@ 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())) { return SPUILabelDefinitions.ACTION.toLowerCase(); - } else if (SPUILabelDefinitions.VAR_NAME.equals(cell.getPropertyId())) { - return cell.getProperty().getValue().toString(); + } else if (ROLLOUT_RENDERER_DATA.equals(cell.getPropertyId())) { + return ((RolloutRendererData) cell.getProperty().getValue()).getName(); } else if (SPUILabelDefinitions.VAR_TOTAL_TARGETS_COUNT_STATUS.equals(cell.getPropertyId())) { return DistributionBarHelper .getTooltip(((TotalTargetCountStatus) cell.getValue()).getStatusTotalCountMap()); + } else if (SPUILabelDefinitions.VAR_DIST_NAME_VERSION.equals(cell.getPropertyId())) { + return getDSDetails(cell.getItem()); } return null; } + private String getDSDetails(final Item rolloutItem) { + final StringBuilder swModuleNames = new StringBuilder(); + final StringBuilder swModuleVendors = new StringBuilder(); + final Set swModules = (Set) rolloutItem.getItemProperty(SW_MODULES).getValue(); + swModules.forEach(swModule -> { + swModuleNames.append(swModule.getName()); + swModuleNames.append(" , "); + swModuleVendors.append(swModule.getVendor()); + swModuleVendors.append(" , "); + }); + final StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append(HTML_UL_OPEN_TAG); + stringBuilder.append(HTML_LI_OPEN_TAG); + stringBuilder.append(" DistributionSet Description : ") + .append((String) rolloutItem.getItemProperty(SPUILabelDefinitions.VAR_DESC).getValue()); + stringBuilder.append(HTML_LI_CLOSE_TAG); + stringBuilder.append(HTML_LI_OPEN_TAG); + stringBuilder.append(" DistributionSet Type : ") + .append((String) rolloutItem.getItemProperty(DS_TYPE).getValue()); + stringBuilder.append(HTML_LI_CLOSE_TAG); + stringBuilder.append(HTML_LI_OPEN_TAG); + stringBuilder.append("Required Migration step : ") + .append((boolean) rolloutItem.getItemProperty(IS_REQUIRED_MIGRATION_STEP).getValue() ? "Yes" : "No"); + stringBuilder.append(HTML_LI_CLOSE_TAG); + + stringBuilder.append(HTML_LI_OPEN_TAG); + stringBuilder.append("SoftWare Modules : ").append(swModuleNames.toString()); + stringBuilder.append(HTML_LI_CLOSE_TAG); + + stringBuilder.append(HTML_LI_OPEN_TAG); + stringBuilder.append("Vendor(s) : ").append(swModuleVendors.toString()); + stringBuilder.append(HTML_LI_CLOSE_TAG); + + stringBuilder.append(HTML_UL_CLOSE_TAG); + return stringBuilder.toString(); + } + enum ACTION { PAUSE, RESUME, START, UPDATE } @@ -558,6 +612,13 @@ public class RolloutListGrid extends AbstractGrid { public Class getPresentationType() { return String.class; } + + private String convertRolloutStatusToString(final RolloutStatus value) { + final StatusFontIcon statusFontIcon = statusIconMap.get(value); + final String codePoint = HawkbitCommonUtil.getCodePoint(statusFontIcon); + return HawkbitCommonUtil.getStatusLabelDetailsInString(codePoint, statusFontIcon.getStyle(), + SPUIComponetIdProvider.ROLLOUT_STATUS_LABEL_ID); + } } /** @@ -570,14 +631,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()); } @@ -592,4 +655,39 @@ public class RolloutListGrid extends AbstractGrid { } } + /** + * Converter to convert 0 to empty, if total target groups is zero. + * + */ + class TotalTargetGroupsConverter implements Converter { + + private static final long serialVersionUID = 6589305227035220369L; + + @Override + public Long convertToModel(final String value, final Class targetType, final Locale locale) + throws com.vaadin.data.util.converter.Converter.ConversionException { + return null; + } + + @Override + public String convertToPresentation(final Long value, final Class targetType, + final Locale locale) throws com.vaadin.data.util.converter.Converter.ConversionException { + if (value == 0) { + return ""; + } + return value.toString(); + } + + @Override + public Class getModelType() { + return Long.class; + } + + @Override + public Class getPresentationType() { + return String.class; + } + + } + } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rolloutgroup/ProxyRolloutGroup.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rolloutgroup/ProxyRolloutGroup.java index bb802c123..08f2c0a0b 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rolloutgroup/ProxyRolloutGroup.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rolloutgroup/ProxyRolloutGroup.java @@ -9,200 +9,211 @@ package org.eclipse.hawkbit.ui.rollout.rolloutgroup; import org.eclipse.hawkbit.repository.model.RolloutGroup; +import org.eclipse.hawkbit.ui.customrenderers.client.renderers.RolloutRendererData; /** - * Proxy rollout group with suctome properties. + * Proxy rollout group with renderer properties. * */ public class ProxyRolloutGroup extends RolloutGroup { - private static final long serialVersionUID = -2745056813306692356L; + private static final long serialVersionUID = -2745056813306692356L; - private String createdDate; + private String createdDate; - private String modifiedDate; + private String modifiedDate; - private String finishedPercentage; + private String finishedPercentage; - private Long runningTargetsCount; + private Long runningTargetsCount; - private Long scheduledTargetsCount; + private Long scheduledTargetsCount; - private Long cancelledTargetsCount; + private Long cancelledTargetsCount; - private Long errorTargetsCount; + private Long errorTargetsCount; - private Long finishedTargetsCount; + private Long finishedTargetsCount; - private Long notStartedTargetsCount; + private Long notStartedTargetsCount; - private Boolean isActionRecieved = Boolean.FALSE; + private Boolean isActionRecieved = Boolean.FALSE; - private String totalTargetsCount; + private String totalTargetsCount; - /** - * @return the createdDate - */ - public String getCreatedDate() { - return createdDate; - } + private RolloutRendererData rolloutRendererData; - /** - * @param createdDate - * the createdDate to set - */ - public void setCreatedDate(final String createdDate) { - this.createdDate = createdDate; - } + public RolloutRendererData getRolloutRendererData() { + return rolloutRendererData; + } - /** - * @return the modifiedDate - */ - public String getModifiedDate() { - return modifiedDate; - } + public void setRolloutRendererData(RolloutRendererData rendererData) { + this.rolloutRendererData = rendererData; + } - /** - * @param modifiedDate - * the modifiedDate to set - */ - public void setModifiedDate(final String modifiedDate) { - this.modifiedDate = modifiedDate; - } + /** + * @return the createdDate + */ + public String getCreatedDate() { + return createdDate; + } - /** - * @return the finishedPercentage - */ - public String getFinishedPercentage() { - return finishedPercentage; - } + /** + * @param createdDate + * the createdDate to set + */ + public void setCreatedDate(final String createdDate) { + this.createdDate = createdDate; + } - /** - * @param finishedPercentage - * the finishedPercentage to set - */ - public void setFinishedPercentage(final String finishedPercentage) { - this.finishedPercentage = finishedPercentage; - } + /** + * @return the modifiedDate + */ + public String getModifiedDate() { + return modifiedDate; + } - /** - * @return the runningTargetsCount - */ - public Long getRunningTargetsCount() { - return runningTargetsCount; - } + /** + * @param modifiedDate + * the modifiedDate to set + */ + public void setModifiedDate(final String modifiedDate) { + this.modifiedDate = modifiedDate; + } - /** - * @param runningTargetsCount - * the runningTargetsCount to set - */ - public void setRunningTargetsCount(final Long runningTargetsCount) { - this.runningTargetsCount = runningTargetsCount; - } + /** + * @return the finishedPercentage + */ + public String getFinishedPercentage() { + return finishedPercentage; + } - /** - * @return the scheduledTargetsCount - */ - public Long getScheduledTargetsCount() { - return scheduledTargetsCount; - } + /** + * @param finishedPercentage + * the finishedPercentage to set + */ + public void setFinishedPercentage(final String finishedPercentage) { + this.finishedPercentage = finishedPercentage; + } - /** - * @param scheduledTargetsCount - * the scheduledTargetsCount to set - */ - public void setScheduledTargetsCount(final Long scheduledTargetsCount) { - this.scheduledTargetsCount = scheduledTargetsCount; - } + /** + * @return the runningTargetsCount + */ + public Long getRunningTargetsCount() { + return runningTargetsCount; + } - /** - * @return the cancelledTargetsCount - */ - public Long getCancelledTargetsCount() { - return cancelledTargetsCount; - } + /** + * @param runningTargetsCount + * the runningTargetsCount to set + */ + public void setRunningTargetsCount(final Long runningTargetsCount) { + this.runningTargetsCount = runningTargetsCount; + } - /** - * @param cancelledTargetsCount - * the cancelledTargetsCount to set - */ - public void setCancelledTargetsCount(final Long cancelledTargetsCount) { - this.cancelledTargetsCount = cancelledTargetsCount; - } + /** + * @return the scheduledTargetsCount + */ + public Long getScheduledTargetsCount() { + return scheduledTargetsCount; + } - /** - * @return the errorTargetsCount - */ - public Long getErrorTargetsCount() { - return errorTargetsCount; - } + /** + * @param scheduledTargetsCount + * the scheduledTargetsCount to set + */ + public void setScheduledTargetsCount(final Long scheduledTargetsCount) { + this.scheduledTargetsCount = scheduledTargetsCount; + } - /** - * @param errorTargetsCount - * the errorTargetsCount to set - */ - public void setErrorTargetsCount(final Long errorTargetsCount) { - this.errorTargetsCount = errorTargetsCount; - } + /** + * @return the cancelledTargetsCount + */ + public Long getCancelledTargetsCount() { + return cancelledTargetsCount; + } - /** - * @return the finishedTargetsCount - */ - public Long getFinishedTargetsCount() { - return finishedTargetsCount; - } + /** + * @param cancelledTargetsCount + * the cancelledTargetsCount to set + */ + public void setCancelledTargetsCount(final Long cancelledTargetsCount) { + this.cancelledTargetsCount = cancelledTargetsCount; + } - /** - * @param finishedTargetsCount - * the finishedTargetsCount to set - */ - public void setFinishedTargetsCount(final Long finishedTargetsCount) { - this.finishedTargetsCount = finishedTargetsCount; - } + /** + * @return the errorTargetsCount + */ + public Long getErrorTargetsCount() { + return errorTargetsCount; + } - /** - * @return the notStartedTargetsCount - */ - public Long getNotStartedTargetsCount() { - return notStartedTargetsCount; - } + /** + * @param errorTargetsCount + * the errorTargetsCount to set + */ + public void setErrorTargetsCount(final Long errorTargetsCount) { + this.errorTargetsCount = errorTargetsCount; + } - /** - * @param notStartedTargetsCount - * the notStartedTargetsCount to set - */ - public void setNotStartedTargetsCount(final Long notStartedTargetsCount) { - this.notStartedTargetsCount = notStartedTargetsCount; - } + /** + * @return the finishedTargetsCount + */ + public Long getFinishedTargetsCount() { + return finishedTargetsCount; + } - /** - * @return the isActionRecieved - */ - public Boolean getIsActionRecieved() { - return isActionRecieved; - } + /** + * @param finishedTargetsCount + * the finishedTargetsCount to set + */ + public void setFinishedTargetsCount(final Long finishedTargetsCount) { + this.finishedTargetsCount = finishedTargetsCount; + } - /** - * @param isActionRecieved - * the isActionRecieved to set - */ - public void setIsActionRecieved(final Boolean isActionRecieved) { - this.isActionRecieved = isActionRecieved; - } + /** + * @return the notStartedTargetsCount + */ + public Long getNotStartedTargetsCount() { + return notStartedTargetsCount; + } - /** - * @return the totalTargetsCount - */ - public String getTotalTargetsCount() { - return totalTargetsCount; - } + /** + * @param notStartedTargetsCount + * the notStartedTargetsCount to set + */ + public void setNotStartedTargetsCount(final Long notStartedTargetsCount) { + this.notStartedTargetsCount = notStartedTargetsCount; + } - /** - * @param totalTargetsCount - * the totalTargetsCount to set - */ - public void setTotalTargetsCount(final String totalTargetsCount) { - this.totalTargetsCount = totalTargetsCount; - } + /** + * @return the isActionRecieved + */ + public Boolean getIsActionRecieved() { + return isActionRecieved; + } + + /** + * @param isActionRecieved + * the isActionRecieved to set + */ + public void setIsActionRecieved(final Boolean isActionRecieved) { + this.isActionRecieved = isActionRecieved; + } + + /** + * @return the totalTargetsCount + */ + public String getTotalTargetsCount() { + return totalTargetsCount; + } + + /** + * @param totalTargetsCount + * the totalTargetsCount to set + */ + public void setTotalTargetsCount(final String totalTargetsCount) { + this.totalTargetsCount = totalTargetsCount; + } } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rolloutgroup/RolloutGroupBeanQuery.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rolloutgroup/RolloutGroupBeanQuery.java index 0dabb18fc..5a37d1341 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rolloutgroup/RolloutGroupBeanQuery.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rolloutgroup/RolloutGroupBeanQuery.java @@ -15,6 +15,8 @@ import java.util.Map; import org.eclipse.hawkbit.repository.RolloutGroupManagement; import org.eclipse.hawkbit.repository.RolloutManagement; import org.eclipse.hawkbit.repository.model.RolloutGroup; +import org.eclipse.hawkbit.ui.common.UserDetailsFormatter; +import org.eclipse.hawkbit.ui.customrenderers.client.renderers.RolloutRendererData; import org.eclipse.hawkbit.ui.rollout.state.RolloutUIState; import org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil; import org.eclipse.hawkbit.ui.utils.SPDateTimeUtil; @@ -110,8 +112,8 @@ public class RolloutGroupBeanQuery extends AbstractBeanQuery proxyRolloutGroup.setDescription(rolloutGroup.getDescription()); proxyRolloutGroup.setCreatedDate(SPDateTimeUtil.getFormattedDate(rolloutGroup.getCreatedAt())); proxyRolloutGroup.setModifiedDate(SPDateTimeUtil.getFormattedDate(rolloutGroup.getLastModifiedAt())); - proxyRolloutGroup.setCreatedBy(HawkbitCommonUtil.getIMUser(rolloutGroup.getCreatedBy())); - proxyRolloutGroup.setLastModifiedBy(HawkbitCommonUtil.getIMUser(rolloutGroup.getLastModifiedBy())); + proxyRolloutGroup.setCreatedBy(UserDetailsFormatter.loadAndFormatCreatedBy(rolloutGroup)); + proxyRolloutGroup.setLastModifiedBy(UserDetailsFormatter.loadAndFormatLastModifiedBy(rolloutGroup)); proxyRolloutGroup.setId(rolloutGroup.getId()); proxyRolloutGroup.setStatus(rolloutGroup.getStatus()); proxyRolloutGroup.setErrorAction(rolloutGroup.getErrorAction()); @@ -122,6 +124,8 @@ public class RolloutGroupBeanQuery extends AbstractBeanQuery proxyRolloutGroup.setSuccessConditionExp(rolloutGroup.getSuccessConditionExp()); proxyRolloutGroup.setFinishedPercentage(calculateFinishedPercentage(rolloutGroup)); + proxyRolloutGroup.setRolloutRendererData(new RolloutRendererData(rolloutGroup.getName(), null)); + proxyRolloutGroup.setTotalTargetsCount(String.valueOf(rolloutGroup.getTotalTargets())); proxyRolloutGroup.setTotalTargetCountStatus(rolloutGroup.getTotalTargetCountStatus()); 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..f09b02cfc 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 @@ -15,24 +15,22 @@ import java.util.List; import java.util.Locale; import java.util.Map; -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; - import org.eclipse.hawkbit.eventbus.event.RolloutGroupChangeEvent; import org.eclipse.hawkbit.repository.RolloutGroupManagement; +import org.eclipse.hawkbit.repository.RolloutManagement; import org.eclipse.hawkbit.repository.SpPermissionChecker; import org.eclipse.hawkbit.repository.model.RolloutGroup; import org.eclipse.hawkbit.repository.model.RolloutGroup.RolloutGroupStatus; import org.eclipse.hawkbit.repository.model.TotalTargetCountStatus; import org.eclipse.hawkbit.ui.common.grid.AbstractGrid; +import org.eclipse.hawkbit.ui.customrenderers.client.renderers.RolloutRendererData; import org.eclipse.hawkbit.ui.customrenderers.renderers.HtmlLabelRenderer; -import org.eclipse.hawkbit.ui.customrenderers.renderers.LinkRenderer; +import org.eclipse.hawkbit.ui.customrenderers.renderers.RolloutRenderer; import org.eclipse.hawkbit.ui.rollout.DistributionBarHelper; import org.eclipse.hawkbit.ui.rollout.StatusFontIcon; import org.eclipse.hawkbit.ui.rollout.event.RolloutEvent; import org.eclipse.hawkbit.ui.rollout.state.RolloutUIState; import org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil; -import org.eclipse.hawkbit.ui.utils.I18N; import org.eclipse.hawkbit.ui.utils.SPUIComponetIdProvider; import org.eclipse.hawkbit.ui.utils.SPUIDefinitions; import org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions; @@ -41,7 +39,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.vaadin.addons.lazyquerycontainer.BeanQueryFactory; import org.vaadin.addons.lazyquerycontainer.LazyQueryContainer; import org.vaadin.addons.lazyquerycontainer.LazyQueryDefinition; -import org.vaadin.spring.events.EventBus; import org.vaadin.spring.events.EventScope; import org.vaadin.spring.events.annotation.EventBusListenerMethod; @@ -64,15 +61,14 @@ import com.vaadin.ui.renderers.HtmlRenderer; public class RolloutGroupListGrid extends AbstractGrid { private static final long serialVersionUID = 4060904914954370524L; - @Autowired - private I18N i18n; - - @Autowired - private transient EventBus.SessionEventBus eventBus; + private static final String ROLLOUT_RENDERER_DATA = "rolloutRendererData"; @Autowired private transient RolloutGroupManagement rolloutGroupManagement; + @Autowired + private transient RolloutManagement rolloutManagement; + @Autowired private transient RolloutUIState rolloutUIState; @@ -81,18 +77,6 @@ public class RolloutGroupListGrid extends AbstractGrid { private transient Map statusIconMap = new EnumMap<>(RolloutGroupStatus.class); - @Override - @PostConstruct - protected void init() { - super.init(); - eventBus.subscribe(this); - } - - @PreDestroy - void destroy() { - eventBus.unsubscribe(this); - } - @EventBusListenerMethod(scope = EventScope.SESSION) void onEvent(final RolloutEvent event) { if (RolloutEvent.SHOW_ROLLOUT_GROUPS != event) { @@ -126,6 +110,13 @@ public class RolloutGroupListGrid extends AbstractGrid { item.getItemProperty(SPUILabelDefinitions.VAR_STATUS).setValue(rolloutGroup.getStatus()); item.getItemProperty(SPUILabelDefinitions.VAR_TOTAL_TARGETS_COUNT_STATUS) .setValue(rolloutGroup.getTotalTargetCountStatus()); + item.getItemProperty(SPUILabelDefinitions.ROLLOUT_GROUP_INSTALLED_PERCENTAGE) + .setValue(calculateFinishedPercentage(rolloutGroup)); + } + + private String calculateFinishedPercentage(final RolloutGroup rolloutGroup) { + return HawkbitCommonUtil.formattingFinishedPercentage(rolloutGroup, + rolloutManagement.getFinishedPercentForRunningGroup(rolloutGroup.getRollout().getId(), rolloutGroup)); } @Override @@ -139,6 +130,9 @@ public class RolloutGroupListGrid extends AbstractGrid { protected void addContainerProperties() { final LazyQueryContainer rolloutGroupGridContainer = (LazyQueryContainer) getContainerDataSource(); rolloutGroupGridContainer.addContainerProperty(SPUILabelDefinitions.VAR_NAME, String.class, "", false, false); + + rolloutGroupGridContainer.addContainerProperty(ROLLOUT_RENDERER_DATA, RolloutRendererData.class, null, false, + false); rolloutGroupGridContainer.addContainerProperty(SPUILabelDefinitions.VAR_DESC, String.class, null, false, false); rolloutGroupGridContainer.addContainerProperty(SPUILabelDefinitions.VAR_STATUS, RolloutGroupStatus.class, null, false, false); @@ -168,8 +162,8 @@ public class RolloutGroupListGrid extends AbstractGrid { @Override protected void setColumnExpandRatio() { - getColumn(SPUILabelDefinitions.VAR_NAME).setMinimumWidth(40); - getColumn(SPUILabelDefinitions.VAR_NAME).setMaximumWidth(200); + getColumn(ROLLOUT_RENDERER_DATA).setMinimumWidth(40); + getColumn(ROLLOUT_RENDERER_DATA).setMaximumWidth(200); getColumn(SPUILabelDefinitions.VAR_TOTAL_TARGETS).setMinimumWidth(40); getColumn(SPUILabelDefinitions.VAR_TOTAL_TARGETS).setMaximumWidth(100); @@ -193,7 +187,7 @@ public class RolloutGroupListGrid extends AbstractGrid { @Override protected void setColumnHeaderNames() { - getColumn(SPUILabelDefinitions.VAR_NAME).setHeaderCaption(i18n.get("header.name")); + getColumn(ROLLOUT_RENDERER_DATA).setHeaderCaption(i18n.get("header.name")); getColumn(SPUILabelDefinitions.VAR_STATUS).setHeaderCaption(i18n.get("header.status")); getColumn(SPUILabelDefinitions.VAR_TOTAL_TARGETS_COUNT_STATUS) .setHeaderCaption(i18n.get("header.detail.status")); @@ -218,8 +212,8 @@ public class RolloutGroupListGrid extends AbstractGrid { @Override protected void setColumnProperties() { - List columnList = new ArrayList<>(); - columnList.add(SPUILabelDefinitions.VAR_NAME); + final List columnList = new ArrayList<>(); + columnList.add(ROLLOUT_RENDERER_DATA); columnList.add(SPUILabelDefinitions.VAR_STATUS); columnList.add(SPUILabelDefinitions.VAR_TOTAL_TARGETS_COUNT_STATUS); columnList.add(SPUILabelDefinitions.VAR_TOTAL_TARGETS); @@ -240,24 +234,25 @@ 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()) { - getColumn(SPUILabelDefinitions.VAR_NAME) - .setRenderer(new LinkRenderer(event -> onClickOfRolloutGroupName(event))); + getColumn(ROLLOUT_RENDERER_DATA) + .setRenderer(new RolloutRenderer(event -> onClickOfRolloutGroupName(event))); } } @Override protected void setHiddenColumns() { - List columnsToBeHidden = new ArrayList<>(); + final List columnsToBeHidden = new ArrayList<>(); + columnsToBeHidden.add(SPUILabelDefinitions.VAR_NAME); columnsToBeHidden.add(SPUILabelDefinitions.VAR_CREATED_DATE); columnsToBeHidden.add(SPUILabelDefinitions.VAR_CREATED_USER); columnsToBeHidden.add(SPUILabelDefinitions.VAR_MODIFIED_DATE); columnsToBeHidden.add(SPUILabelDefinitions.VAR_MODIFIED_BY); columnsToBeHidden.add(SPUILabelDefinitions.VAR_DESC); - for (Object propertyId : columnsToBeHidden) { + for (final Object propertyId : columnsToBeHidden) { getColumn(propertyId).setHidden(true); } } @@ -267,24 +262,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 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, new StatusFontIcon(FontAwesome.CHECK_CIRCLE, SPUIStyleDefinitions.STATUS_ICON_GREEN)); @@ -298,13 +281,13 @@ 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())) { return SPUILabelDefinitions.ACTION.toLowerCase(); - } else if (SPUILabelDefinitions.VAR_NAME.equals(cell.getPropertyId())) { - return cell.getProperty().getValue().toString(); + } else if (ROLLOUT_RENDERER_DATA.equals(cell.getPropertyId())) { + return ((RolloutRendererData) cell.getProperty().getValue()).getName(); } else if (SPUILabelDefinitions.VAR_TOTAL_TARGETS_COUNT_STATUS.equals(cell.getPropertyId())) { return DistributionBarHelper .getTooltip(((TotalTargetCountStatus) cell.getValue()).getStatusTotalCountMap()); @@ -318,7 +301,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"; @@ -339,14 +322,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()); } @@ -392,5 +377,13 @@ public class RolloutGroupListGrid extends AbstractGrid { return String.class; } + private String convertRolloutGroupStatusToString(final RolloutGroupStatus value) { + 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/rolloutgroup/RolloutGroupsListHeader.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rolloutgroup/RolloutGroupsListHeader.java index 45c16eeed..e85d96d7a 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rolloutgroup/RolloutGroupsListHeader.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rolloutgroup/RolloutGroupsListHeader.java @@ -161,6 +161,7 @@ public class RolloutGroupsListHeader extends AbstractGridHeader { final HorizontalLayout headerCaptionLayout = new HorizontalLayout(); headerCaptionLayout.addComponent(rolloutsListViewLink); headerCaptionLayout.addComponent(new Label(">")); + headerCaption.addStyleName("breadcrumbPaddingLeft"); headerCaptionLayout.addComponent(headerCaption); return headerCaptionLayout; diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rolloutgrouptargets/RolloutGroupTargetsBeanQuery.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rolloutgrouptargets/RolloutGroupTargetsBeanQuery.java index 097e076be..685be685e 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rolloutgrouptargets/RolloutGroupTargetsBeanQuery.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/rollout/rolloutgrouptargets/RolloutGroupTargetsBeanQuery.java @@ -17,6 +17,7 @@ import org.eclipse.hawkbit.repository.RolloutManagement; import org.eclipse.hawkbit.repository.model.RolloutGroup; import org.eclipse.hawkbit.repository.model.Target; import org.eclipse.hawkbit.repository.model.TargetWithActionStatus; +import org.eclipse.hawkbit.ui.common.UserDetailsFormatter; import org.eclipse.hawkbit.ui.components.ProxyTarget; import org.eclipse.hawkbit.ui.rollout.state.RolloutUIState; import org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil; @@ -105,8 +106,8 @@ public class RolloutGroupTargetsBeanQuery extends AbstractBeanQuery prxyTarget.setLastModifiedDate(SPDateTimeUtil.getFormattedDate(targ.getLastModifiedAt())); prxyTarget.setCreatedDate(SPDateTimeUtil.getFormattedDate(targ.getCreatedAt())); prxyTarget.setCreatedAt(targ.getCreatedAt()); - prxyTarget.setCreatedByUser(HawkbitCommonUtil.getIMUser(targ.getCreatedBy())); - prxyTarget.setModifiedByUser(HawkbitCommonUtil.getIMUser(targ.getLastModifiedBy())); + prxyTarget.setCreatedByUser(UserDetailsFormatter.loadAndFormatCreatedBy(targ)); + prxyTarget.setModifiedByUser(UserDetailsFormatter.loadAndFormatLastModifiedBy(targ)); if (targetWithActionStatus.getStatus() != null) { prxyTarget.setStatus(targetWithActionStatus.getStatus()); } 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..2c1a701a1 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 @@ -14,9 +14,6 @@ import java.util.List; import java.util.Locale; import java.util.Map; -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; - import org.eclipse.hawkbit.repository.model.Action.Status; import org.eclipse.hawkbit.repository.model.RolloutGroup; import org.eclipse.hawkbit.repository.model.RolloutGroup.RolloutGroupStatus; @@ -26,7 +23,6 @@ import org.eclipse.hawkbit.ui.rollout.StatusFontIcon; import org.eclipse.hawkbit.ui.rollout.event.RolloutEvent; import org.eclipse.hawkbit.ui.rollout.state.RolloutUIState; import org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil; -import org.eclipse.hawkbit.ui.utils.I18N; import org.eclipse.hawkbit.ui.utils.SPUIComponetIdProvider; import org.eclipse.hawkbit.ui.utils.SPUIDefinitions; import org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions; @@ -35,7 +31,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.vaadin.addons.lazyquerycontainer.BeanQueryFactory; import org.vaadin.addons.lazyquerycontainer.LazyQueryContainer; import org.vaadin.addons.lazyquerycontainer.LazyQueryDefinition; -import org.vaadin.spring.events.EventBus; import org.vaadin.spring.events.EventScope; import org.vaadin.spring.events.annotation.EventBusListenerMethod; @@ -55,29 +50,12 @@ import com.vaadin.spring.annotation.ViewScope; public class RolloutGroupTargetsListGrid extends AbstractGrid { private static final long serialVersionUID = -2244756637458984597L; - - @Autowired - private I18N i18n; - - @Autowired - private transient EventBus.SessionEventBus eventBus; - + @Autowired private transient RolloutUIState rolloutUIState; private transient Map statusIconMap = new EnumMap<>(Status.class); - @Override - @PostConstruct - protected void init() { - super.init(); - eventBus.subscribe(this); - } - - @PreDestroy - void destroy() { - eventBus.unsubscribe(this); - } @EventBusListenerMethod(scope = EventScope.SESSION) void onEvent(final RolloutEvent event) { @@ -158,7 +136,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 +196,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 +214,27 @@ 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); + final String codePoint = HawkbitCommonUtil.getCodePoint(statusFontIcon); + 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); + } + if (rolloutGroup != null && rolloutGroup.getStatus() == RolloutGroupStatus.FINISHED) { + return HawkbitCommonUtil.getStatusLabelDetailsInString( + Integer.toString(FontAwesome.MINUS_CIRCLE.getCodepoint()), "statusIconBlue", null); + } + return HawkbitCommonUtil.getStatusLabelDetailsInString( + Integer.toString(FontAwesome.QUESTION_CIRCLE.getCodepoint()), "statusIconBlue", null); + } + } private void createRolloutStatusToFontMap() { @@ -271,22 +258,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 +268,6 @@ public class RolloutGroupTargetsListGrid extends AbstractGrid { } return cell.getProperty().getValue().toString().toLowerCase(); } - private String getDescriptionWhenNoAction() { final RolloutGroup rolloutGroup = rolloutUIState.getRolloutGroup().isPresent() @@ -304,7 +275,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/AuthenticationConfigurationView.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/AuthenticationConfigurationView.java index 94e852813..329318b0f 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 @@ -11,6 +11,7 @@ package org.eclipse.hawkbit.ui.tenantconfiguration; import javax.annotation.PostConstruct; import org.eclipse.hawkbit.ui.components.SPUIComponentProvider; +import org.eclipse.hawkbit.ui.tenantconfiguration.authentication.AnonymousDownloadAuthenticationConfigurationItem; import org.eclipse.hawkbit.ui.tenantconfiguration.authentication.AuthenticationConfigurationItem; import org.eclipse.hawkbit.ui.tenantconfiguration.authentication.CertificateAuthenticationConfigurationItem; import org.eclipse.hawkbit.ui.tenantconfiguration.authentication.GatewaySecurityTokenAuthenticationConfigurationItem; @@ -30,9 +31,6 @@ import com.vaadin.ui.VerticalLayout; /** * View to configure the authentication mode. - * - * - * */ @SpringComponent @ViewScope @@ -55,12 +53,17 @@ public class AuthenticationConfigurationView extends BaseConfigurationView @Autowired private GatewaySecurityTokenAuthenticationConfigurationItem gatewaySecurityTokenAuthenticationConfigurationItem; + @Autowired + private AnonymousDownloadAuthenticationConfigurationItem anonymousDownloadAuthenticationConfigurationItem; + private CheckBox gatewaySecTokenCheckBox; private CheckBox targetSecTokenCheckBox; private CheckBox certificateAuthCheckbox; + private CheckBox downloadAnonymousCheckBox; + /** * Initialize Authentication Configuration layout. */ @@ -80,7 +83,7 @@ public class AuthenticationConfigurationView extends BaseConfigurationView headerDisSetType.addStyleName("config-panel-header"); vLayout.addComponent(headerDisSetType); - final GridLayout gridLayout = new GridLayout(2, 3); + final GridLayout gridLayout = new GridLayout(2, 4); gridLayout.setSpacing(true); gridLayout.setImmediate(true); gridLayout.setColumnExpandRatio(1, 1.0F); @@ -108,6 +111,14 @@ public class AuthenticationConfigurationView extends BaseConfigurationView gridLayout.addComponent(gatewaySecTokenCheckBox, 0, 2); gridLayout.addComponent(gatewaySecurityTokenAuthenticationConfigurationItem, 1, 2); + downloadAnonymousCheckBox = SPUIComponentProvider.getCheckBox("", DIST_CHECKBOX_STYLE, null, false, ""); + downloadAnonymousCheckBox.setId("downloadanonymouscheckbox"); + downloadAnonymousCheckBox.setValue(anonymousDownloadAuthenticationConfigurationItem.isConfigEnabled()); + downloadAnonymousCheckBox.addValueChangeListener(this); + anonymousDownloadAuthenticationConfigurationItem.addChangeListener(this); + gridLayout.addComponent(downloadAnonymousCheckBox, 0, 3); + gridLayout.addComponent(anonymousDownloadAuthenticationConfigurationItem, 1, 3); + vLayout.addComponent(gridLayout); rootPanel.setContent(vLayout); setCompositionRoot(rootPanel); @@ -118,6 +129,7 @@ public class AuthenticationConfigurationView extends BaseConfigurationView certificateAuthenticationConfigurationItem.save(); targetSecurityTokenAuthenticationConfigurationItem.save(); gatewaySecurityTokenAuthenticationConfigurationItem.save(); + anonymousDownloadAuthenticationConfigurationItem.save(); } @Override @@ -125,9 +137,11 @@ public class AuthenticationConfigurationView extends BaseConfigurationView certificateAuthenticationConfigurationItem.undo(); targetSecurityTokenAuthenticationConfigurationItem.undo(); gatewaySecurityTokenAuthenticationConfigurationItem.undo(); + anonymousDownloadAuthenticationConfigurationItem.undo(); certificateAuthCheckbox.setValue(certificateAuthenticationConfigurationItem.isConfigEnabled()); targetSecTokenCheckBox.setValue(targetSecurityTokenAuthenticationConfigurationItem.isConfigEnabled()); gatewaySecTokenCheckBox.setValue(gatewaySecurityTokenAuthenticationConfigurationItem.isConfigEnabled()); + downloadAnonymousCheckBox.setValue(anonymousDownloadAuthenticationConfigurationItem.isConfigEnabled()); } @Override @@ -153,6 +167,8 @@ public class AuthenticationConfigurationView extends BaseConfigurationView configurationItem = targetSecurityTokenAuthenticationConfigurationItem; } else if (checkBox == certificateAuthCheckbox) { configurationItem = certificateAuthenticationConfigurationItem; + } else if (checkBox == downloadAnonymousCheckBox) { + configurationItem = anonymousDownloadAuthenticationConfigurationItem; } else { return; } 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/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 8a22064ab..d021254bc 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 @@ -73,7 +70,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() { @@ -154,13 +151,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/AbstractAuthenticationTenantConfigurationItem.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/authentication/AbstractAuthenticationTenantConfigurationItem.java index 0907ebf9e..4f222f080 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/authentication/AbstractAuthenticationTenantConfigurationItem.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/authentication/AbstractAuthenticationTenantConfigurationItem.java @@ -14,7 +14,9 @@ import java.util.List; import org.eclipse.hawkbit.repository.TenantConfigurationManagement; 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.ui.VerticalLayout; @@ -30,6 +32,9 @@ abstract class AbstractAuthenticationTenantConfigurationItem extends VerticalLay private static final long serialVersionUID = 1L; + @Autowired + private I18N i18n; + private final TenantConfigurationKey configurationKey; private final transient TenantConfigurationManagement tenantConfigurationManagement; @@ -53,7 +58,7 @@ abstract class AbstractAuthenticationTenantConfigurationItem extends VerticalLay */ protected void init(final String labelText) { setImmediate(true); - addComponent(SPUIComponentProvider.getLabel(labelText, SPUILabelDefinitions.SP_LABEL_SIMPLE)); + addComponent(SPUIComponentProvider.getLabel(i18n.get(labelText), SPUILabelDefinitions.SP_LABEL_SIMPLE)); } @Override diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/authentication/AnonymousDownloadAuthenticationConfigurationItem.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/authentication/AnonymousDownloadAuthenticationConfigurationItem.java new file mode 100644 index 000000000..1180eba64 --- /dev/null +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/tenantconfiguration/authentication/AnonymousDownloadAuthenticationConfigurationItem.java @@ -0,0 +1,72 @@ +/** + * 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.authentication; + +import javax.annotation.PostConstruct; + +import org.eclipse.hawkbit.repository.TenantConfigurationManagement; +import org.eclipse.hawkbit.tenancy.configuration.TenantConfigurationKey; +import org.springframework.beans.factory.annotation.Autowired; + +import com.vaadin.spring.annotation.SpringComponent; +import com.vaadin.spring.annotation.ViewScope; + +/** + * This class represents the UI item for the anonymous download by in the + * authentication configuration view. + */ +@SpringComponent +@ViewScope +public class AnonymousDownloadAuthenticationConfigurationItem extends AbstractAuthenticationTenantConfigurationItem { + + private static final long serialVersionUID = 1L; + + private boolean configurationEnabled = false; + private boolean configurationEnabledChange = false; + + @Autowired + public AnonymousDownloadAuthenticationConfigurationItem( + final TenantConfigurationManagement tenantConfigurationManagement) { + super(TenantConfigurationKey.ANONYMOUS_DOWNLOAD_MODE_ENABLED, tenantConfigurationManagement); + } + + @PostConstruct + public void init() { + super.init("label.configuration.anonymous.download"); + configurationEnabled = isConfigEnabled(); + } + + @Override + public void configEnable() { + configurationEnabledChange = !configurationEnabled; + configurationEnabled = true; + } + + @Override + public void configDisable() { + configurationEnabledChange = configurationEnabled; + configurationEnabled = false; + } + + @Override + public void save() { + if (!configurationEnabledChange) { + return; + } + getTenantConfigurationManagement().addOrUpdateConfiguration(getConfigurationKey(), configurationEnabled); + } + + @Override + public void undo() { + configurationEnabledChange = false; + configurationEnabled = getTenantConfigurationManagement() + .getConfigurationValue(getConfigurationKey(), Boolean.class).getValue(); + } + +} 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..438917072 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 @@ -13,7 +13,6 @@ import javax.annotation.PostConstruct; import org.eclipse.hawkbit.repository.TenantConfigurationManagement; 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; @@ -26,21 +25,15 @@ 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 - private I18N i18n; - private boolean configurationEnabled = false; private boolean configurationEnabledChange = false; private boolean configurationCaRootAuthorityChanged = false; @@ -59,11 +52,11 @@ public class CertificateAuthenticationConfigurationItem extends AbstractAuthenti } /** - * init mehotd called by spring. + * Init mehotd called by spring. */ @PostConstruct public void init() { - super.init(i18n.get("label.configuration.auth.header")); + super.init("label.configuration.auth.header"); configurationEnabled = isConfigEnabled(); detailLayout = new VerticalLayout(); @@ -94,12 +87,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 +97,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 +106,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 +118,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..3fa87538c 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 @@ -15,7 +15,6 @@ import org.eclipse.hawkbit.security.SecurityTokenGenerator; import org.eclipse.hawkbit.tenancy.configuration.TenantConfigurationKey; import org.eclipse.hawkbit.ui.components.SPUIComponentProvider; import org.eclipse.hawkbit.ui.decorators.SPUIButtonStyleSmall; -import org.eclipse.hawkbit.ui.utils.I18N; import org.eclipse.hawkbit.ui.utils.SPUILabelDefinitions; import org.springframework.beans.factory.annotation.Autowired; @@ -30,22 +29,17 @@ 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 private transient SecurityTokenGenerator securityTokenGenerator; - @Autowired - private I18N i18n; private TextField gatewayTokenNameTextField; @@ -70,12 +64,12 @@ public class GatewaySecurityTokenAuthenticationConfigurationItem extends Abstrac } /** - * init mehotd called by spring. + * Init mehotd called by spring. */ @PostConstruct public void init() { - super.init(i18n.get("label.configuration.auth.gatewaytoken")); + super.init("label.configuration.auth.gatewaytoken"); configurationEnabled = isConfigEnabled(); detailLayout = new VerticalLayout(); @@ -135,12 +129,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..9ca82e7ea 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 @@ -12,29 +12,21 @@ import javax.annotation.PostConstruct; import org.eclipse.hawkbit.repository.TenantConfigurationManagement; import org.eclipse.hawkbit.tenancy.configuration.TenantConfigurationKey; -import org.eclipse.hawkbit.ui.utils.I18N; import org.springframework.beans.factory.annotation.Autowired; 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 - private I18N i18n; - private boolean configurationEnabled = false; private boolean configurationEnabledChange = false; @@ -49,20 +41,14 @@ public class TargetSecurityTokenAuthenticationConfigurationItem extends Abstract } /** - * init mehotd called by spring. + * Init mehotd called by spring. */ @PostConstruct public void init() { - super.init(i18n.get("label.configuration.auth.targettoken")); + super.init("label.configuration.auth.targettoken"); configurationEnabled = isConfigEnabled(); } - /* - * (non-Javadoc) - * - * @see org.eclipse.hawkbit.server.ui.tenantconfiguration. - * TenantConfigurationItem# configEnable() - */ @Override public void configEnable() { if (!configurationEnabled) { @@ -71,12 +57,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) { 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..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 @@ -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() { diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/AssignInstalledDSTooltipGenerator.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/AssignInstalledDSTooltipGenerator.java new file mode 100644 index 000000000..c4e78b3e5 --- /dev/null +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/AssignInstalledDSTooltipGenerator.java @@ -0,0 +1,83 @@ +/** + * 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.utils; + +import static org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil.HTML_LI_CLOSE_TAG; +import static org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil.HTML_LI_OPEN_TAG; +import static org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil.HTML_UL_CLOSE_TAG; +import static org.eclipse.hawkbit.ui.utils.HawkbitCommonUtil.HTML_UL_OPEN_TAG; + +import java.util.Set; + +import org.eclipse.hawkbit.repository.model.DistributionSet; +import org.eclipse.hawkbit.repository.model.SoftwareModule; + +import com.vaadin.data.Item; +import com.vaadin.ui.AbstractSelect.ItemDescriptionGenerator; +import com.vaadin.ui.Component; +import com.vaadin.ui.Table; + +public class AssignInstalledDSTooltipGenerator implements ItemDescriptionGenerator { + private static final long serialVersionUID = 688730421728162456L; + + private static final String ASSIGN_DIST_SET = "assignedDistributionSet"; + private static final String INSTALL_DIST_SET = "installedDistributionSet"; + + @Override + public String generateDescription(final Component source, final Object itemId, final Object propertyId) { + final DistributionSet distributionSet; + final Item item = ((Table) source).getItem(itemId); + if (propertyId != null) { + if (propertyId.equals(SPUILabelDefinitions.ASSIGNED_DISTRIBUTION_NAME_VER)) { + distributionSet = (DistributionSet) item.getItemProperty(ASSIGN_DIST_SET).getValue(); + return getDSDetails(distributionSet); + } else if (propertyId.equals(SPUILabelDefinitions.INSTALLED_DISTRIBUTION_NAME_VER)) { + distributionSet = (DistributionSet) item.getItemProperty(INSTALL_DIST_SET).getValue(); + return getDSDetails(distributionSet); + } + } + return null; + } + + private String getDSDetails(final DistributionSet distributionSet) { + if (distributionSet == null) { + return null; + } + final StringBuilder swModuleNames = new StringBuilder(); + final StringBuilder swModuleVendors = new StringBuilder(); + final Set swModules = distributionSet.getModules(); + swModules.forEach(swModule -> { + swModuleNames.append(swModule.getName()); + swModuleNames.append(" , "); + swModuleVendors.append(swModule.getVendor()); + swModuleVendors.append(" , "); + }); + final StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append(HTML_UL_OPEN_TAG); + stringBuilder.append(HTML_LI_OPEN_TAG); + stringBuilder.append(" DistributionSet Description : ").append(distributionSet.getDescription()); + stringBuilder.append(HTML_LI_CLOSE_TAG); + stringBuilder.append(HTML_LI_OPEN_TAG); + stringBuilder.append(" DistributionSet Type : ").append((distributionSet.getType()).getName()); + stringBuilder.append(HTML_LI_CLOSE_TAG); + stringBuilder.append(HTML_LI_OPEN_TAG); + stringBuilder.append(" Required Migration step : ") + .append(distributionSet.isRequiredMigrationStep() ? "Yes" : "No"); + stringBuilder.append(HTML_LI_CLOSE_TAG); + stringBuilder.append(HTML_LI_OPEN_TAG); + stringBuilder.append("SoftWare Modules : ").append(swModuleNames.toString()); + stringBuilder.append(HTML_LI_CLOSE_TAG); + stringBuilder.append(HTML_LI_OPEN_TAG); + stringBuilder.append("Vendor(s) : ").append(swModuleVendors.toString()); + stringBuilder.append(HTML_LI_CLOSE_TAG); + stringBuilder.append(HTML_UL_CLOSE_TAG); + return stringBuilder.toString(); + } +} 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..a1091cd8a 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 @@ -14,34 +14,26 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; -import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; -import java.util.Set; import java.util.TimeZone; import org.apache.commons.lang3.StringUtils; -import org.eclipse.hawkbit.im.authentication.UserPrincipal; import org.eclipse.hawkbit.repository.SoftwareManagement; -import org.eclipse.hawkbit.repository.model.DistributionSetIdName; -import org.eclipse.hawkbit.repository.model.DistributionSetTagAssigmentResult; +import org.eclipse.hawkbit.repository.model.AssignmentResult; +import org.eclipse.hawkbit.repository.model.DistributionSet; +import org.eclipse.hawkbit.repository.model.NamedEntity; import org.eclipse.hawkbit.repository.model.RolloutGroup; import org.eclipse.hawkbit.repository.model.SoftwareModule; import org.eclipse.hawkbit.repository.model.SoftwareModuleType; -import org.eclipse.hawkbit.repository.model.TargetIdName; import org.eclipse.hawkbit.repository.model.TargetInfo.PollStatus; -import org.eclipse.hawkbit.repository.model.TargetTagAssigmentResult; import org.eclipse.hawkbit.repository.model.TargetUpdateStatus; 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; -import org.springframework.security.core.userdetails.UserDetailsService; -import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.vaadin.addons.lazyquerycontainer.AbstractBeanQuery; import org.vaadin.addons.lazyquerycontainer.BeanQueryFactory; import org.vaadin.addons.lazyquerycontainer.LazyQueryContainer; @@ -81,6 +73,11 @@ public final class HawkbitCommonUtil { */ public static final String SPAN_CLOSE = ""; + public static final String HTML_LI_CLOSE_TAG = ""; + public static final String HTML_LI_OPEN_TAG = "
  • "; + public static final String HTML_UL_CLOSE_TAG = ""; + public static final String HTML_UL_OPEN_TAG = "
      "; + private static final Logger LOG = LoggerFactory.getLogger(HawkbitCommonUtil.class); private static final String JS_DRAG_COUNT_REM_CHILD = " if(x) { document.head.removeChild(x); } "; @@ -95,8 +92,6 @@ public final class HawkbitCommonUtil { private static final String COUNT_STYLE = " countStyle = document.createElement('style'); "; private static final String COUNT_STYLE_ID = " countStyle.id=\"sp-drag-count\"; "; private static final String APPEND_CHILD = " document.head.appendChild(countStyle);"; - private static final String HEADER_VERSION = "header.version"; - private static final String HEADER_NAME = "header.name"; private static final String SM_HIGHLIGHT_CREATE_SCRIPT = "smHighlight = document.createElement('style'); smHighlight.id=\"sm-table-highlight\"; document.head.appendChild(smHighlight); "; private static final String SM_HIGHLIGHT_REMOVE_SCRIPT = "var y = document.getElementById('sm-table-highlight'); if(y) { document.head.removeChild(y); } "; private static final String SM_HIGHLIGHT_RESET_SCRIPT = SM_HIGHLIGHT_REMOVE_SCRIPT + SM_HIGHLIGHT_CREATE_SCRIPT @@ -114,6 +109,9 @@ public final class HawkbitCommonUtil { private static final String DELETE_DROP_CREATE_SCRIPT = "var q = document.getElementById('show-delete-drop-hint'); if(q) { } else { showDeleteDrop = document.createElement('style'); showDeleteDrop.id=\"show-delete-drop-hint\"; document.head.appendChild(showDeleteDrop); }"; private static final String DELETE_TAG_DROP_REMOVE_SCRIPT = "var o = document.getElementById('show-delete-drop-hint'); if(o) { document.head.removeChild(o); } "; + private static final String ASSIGN_DIST_SET = "assignedDistributionSet"; + private static final String INSTALL_DIST_SET = "installedDistributionSet"; + /** * Define empty string. */ @@ -433,27 +431,7 @@ public final class HawkbitCommonUtil { return trimAndNullIfEmpty(orgText) == null ? SPUIDefinitions.SPACE : orgText; } - /** - * Format the lengthy text. - * - * @param orgText - * text to be formatted - * @return String formatted text - */ - public static String getFormattedText(final String orgText) { - if (orgText == null) { - return StringUtils.EMPTY; - } - - final int txtLengthAllowed = SPUIDefinitions.NAME_DESCRIPTION_LENGTH; - if (orgText.length() > txtLengthAllowed) { - return new StringBuilder(orgText.substring(0, txtLengthAllowed)).append("...").toString(); - } - - return orgText; - } - - /** + /** * Find extra height required to increase by all the components to utilize * the full height of browser for the responsive UI. * @@ -612,31 +590,6 @@ public final class HawkbitCommonUtil { return requiredExtraWidth + minTableWidth; } - /** - * get formatted name - lastname,firstname. - * - * @param user - * user name - * @return String formatted name - */ - public static String getFormattedName(final UserDetails user) { - final StringBuilder formattedName = new StringBuilder(); - if (user instanceof UserPrincipal) { - if (trimAndNullIfEmpty(((UserPrincipal) user).getLastname()) != null) { - formattedName.append(((UserPrincipal) user).getLastname()); - } - if (trimAndNullIfEmpty(((UserPrincipal) user).getFirstname()) != null) { - if (formattedName.length() > 0) { - formattedName.append(", "); - } - formattedName.append(((UserPrincipal) user).getFirstname()); - } - } else if (user != null) { - formattedName.append(user.getUsername()); - } - return formattedName.toString(); - } - /** * get the Last sequence of string which is after last dot in String. * @@ -693,30 +646,6 @@ public final class HawkbitCommonUtil { return exeJS.toString(); } - /** - * Get IM User for user UUID. - * - * @param uuid - * @return imReslovedUser user details - */ - public static String getIMUser(final String uuid) { - // Get modifed user - String imReslovedUser = HawkbitCommonUtil.SP_STRING_SPACE; - if (HawkbitCommonUtil.trimAndNullIfEmpty(uuid) != null) { - final UserDetailsService idManagement = SpringContextHelper.getBean(UserDetailsService.class); - try { - imReslovedUser = HawkbitCommonUtil.getFormattedName(idManagement.loadUserByUsername(uuid)); - } catch (final UsernameNotFoundException e) { // NOSONAR - // nope not need to handle - } - // If Null display the UID - if (HawkbitCommonUtil.trimAndNullIfEmpty(imReslovedUser) == null) { - imReslovedUser = uuid; - } - } - return imReslovedUser; - } - /** * Get formatted label.Appends ellipses if content does not fit the label. * @@ -802,13 +731,16 @@ public final class HawkbitCommonUtil { * as string * @param version * as string + * @param type + * key as string * @return boolean as flag */ - public static boolean isDuplicate(final String name, final String version) { + public static boolean isDuplicate(final String name, final String version, final String type) { final SoftwareManagement swMgmtService = SpringContextHelper.getBean(SoftwareManagement.class); - final List swModulesList = swMgmtService.findSoftwareModuleByNameAndVersion(name, version); + final SoftwareModule swModule = swMgmtService.findSoftwareModuleByNameAndVersion(name, version, + swMgmtService.findSoftwareModuleTypeByName(type)); boolean duplicate = false; - if (swModulesList != null && !swModulesList.isEmpty()) { + if (swModule != null) { duplicate = true; } return duplicate; @@ -865,7 +797,7 @@ public final class HawkbitCommonUtil { /** * Display Target Tag action message. * - * @param targTagName + * @param tagName * as tag name * @param result * as TargetTagAssigmentResult @@ -875,8 +807,8 @@ public final class HawkbitCommonUtil { * I18N * @return message */ - public static String getTargetTagAssigmentMsg(final String targTagName, final TargetTagAssigmentResult result, - final I18N i18n) { + public static String createAssignmentMessage(final String tagName, + final AssignmentResult result, final I18N i18n) { final StringBuilder formMsg = new StringBuilder(); final int assignedCount = result.getAssigned(); final int alreadyAssignedCount = result.getAlreadyAssigned(); @@ -884,10 +816,10 @@ public final class HawkbitCommonUtil { if (assignedCount == 1) { formMsg.append(i18n.get("message.target.assigned.one", - new Object[] { result.getAssignedTargets().get(0).getName(), targTagName })).append("
      "); + new Object[] { result.getAssignedEntity().get(0).getName(), tagName })).append("
      "); } else if (assignedCount > 1) { - formMsg.append(i18n.get("message.target.assigned.many", new Object[] { assignedCount, targTagName })) + formMsg.append(i18n.get("message.target.assigned.many", new Object[] { assignedCount, tagName })) .append("
      "); if (alreadyAssignedCount > 0) { @@ -899,55 +831,10 @@ public final class HawkbitCommonUtil { if (unassignedCount == 1) { formMsg.append(i18n.get("message.target.unassigned.one", - new Object[] { result.getUnassignedTargets().get(0).getName(), targTagName })).append("
      "); + new Object[] { result.getUnassignedEntity().get(0).getName(), tagName })).append("
      "); } else if (unassignedCount > 1) { - formMsg.append(i18n.get("message.target.unassigned.many", new Object[] { unassignedCount, targTagName })) - .append("
      "); - } - return formMsg.toString(); - } - - /** - * Get message to be displayed after distribution tag assignment. - * - * @param targTagName - * tag name - * @param result - * DistributionSetTagAssigmentResult - * @param tagsClickedList - * list of clicked tags - * @param i18n - * I18N - * @return message - */ - public static String getDistributionTagAssignmentMsg(final String targTagName, - final DistributionSetTagAssigmentResult result, final I18N i18n) { - final StringBuilder formMsg = new StringBuilder(); - final int assignedCount = result.getAssigned(); - final int alreadyAssignedCount = result.getAlreadyAssigned(); - final int unassignedCount = result.getUnassigned(); - - if (assignedCount == 1) { - formMsg.append(i18n.get("message.target.assigned.one", - new Object[] { result.getAssignedDs().get(0).getName(), targTagName })).append("
      "); - - } else if (assignedCount > 1) { - formMsg.append(i18n.get("message.target.assigned.many", new Object[] { assignedCount, targTagName })) - .append("
      "); - - if (alreadyAssignedCount > 0) { - final String alreadyAssigned = i18n.get("message.target.alreadyAssigned", - new Object[] { alreadyAssignedCount }); - formMsg.append(alreadyAssigned).append("
      "); - } - } - - if (unassignedCount == 1) { - formMsg.append(i18n.get("message.target.unassigned.one", - new Object[] { result.getUnassignedDs().get(0).getName(), targTagName })).append("
      "); - } else if (unassignedCount > 1) { - formMsg.append(i18n.get("message.target.unassigned.many", new Object[] { unassignedCount, targTagName })) + formMsg.append(i18n.get("message.target.unassigned.many", new Object[] { unassignedCount, tagName })) .append("
      "); } return formMsg.toString(); @@ -1001,43 +888,6 @@ public final class HawkbitCommonUtil { lqc.addContainerProperty(SPUILabelDefinitions.VAR_LAST_MODIFIED_DATE, String.class, null, false, true); } - /** - * Get visible columns in table. - * - * @param isMaximized - * true if table is maximized - * @param isShowPinColumn - * if true pin column will be displayed. - * @param i18n - * I18N - * @return List list of columns to be displayed. - */ - public static List getTableVisibleColumns(final Boolean isMaximized, final Boolean isShowPinColumn, - final I18N i18n) { - final List columnList = new ArrayList<>(); - if (isMaximized) { - columnList.add(new TableColumn(SPUILabelDefinitions.VAR_NAME, i18n.get(HEADER_NAME), 0.2f)); - columnList.add(new TableColumn(SPUILabelDefinitions.VAR_VERSION, i18n.get(HEADER_VERSION), 0.1f)); - columnList.add(new TableColumn(SPUILabelDefinitions.VAR_CREATED_BY, i18n.get("header.createdBy"), 0.1f)); - columnList - .add(new TableColumn(SPUILabelDefinitions.VAR_CREATED_DATE, i18n.get("header.createdDate"), 0.1f)); - columnList.add( - new TableColumn(SPUILabelDefinitions.VAR_LAST_MODIFIED_BY, i18n.get("header.modifiedBy"), 0.1f)); - columnList.add(new TableColumn(SPUILabelDefinitions.VAR_LAST_MODIFIED_DATE, i18n.get("header.modifiedDate"), - 0.1f)); - columnList.add(new TableColumn(SPUILabelDefinitions.VAR_DESC, i18n.get("header.description"), 0.2f)); - } else if (isShowPinColumn) { - columnList.add(new TableColumn(SPUILabelDefinitions.VAR_NAME, i18n.get(HEADER_NAME), 0.7f)); - columnList.add(new TableColumn(SPUILabelDefinitions.VAR_VERSION, i18n.get(HEADER_VERSION), 0.2f)); - columnList.add(new TableColumn(SPUILabelDefinitions.PIN_COLUMN, SP_STRING_EMPTY, 0.1f)); - } else { - columnList.add(new TableColumn(SPUILabelDefinitions.VAR_NAME, i18n.get(HEADER_NAME), 0.8f)); - columnList.add(new TableColumn(SPUILabelDefinitions.VAR_VERSION, i18n.get(HEADER_VERSION), 0.2f)); - } - return columnList; - - } - /** * Reset the software module table rows highlight css. * @@ -1144,36 +994,6 @@ public final class HawkbitCommonUtil { return DELETE_TAG_DROP_REMOVE_SCRIPT; } - /** - * Get the details of selected rows of {@link TargetTable}. - * - * @param sourceTable - * @return set of {@link TargetIdName} - */ - public static Set getSelectedTargetDetails(final Table sourceTable) { - Set targetSelected = null; - if (sourceTable.getValue() != null) { - targetSelected = new LinkedHashSet<>((Set) sourceTable.getValue()); - targetSelected.remove(null); - } - return targetSelected; - } - - /** - * Get the details of selected rows of {@link DistributionTable}. - * - * @param sourceTable - * @return set of {@link DistributionSetIdName} - */ - public static Set getSelectedDSDetails(final Table sourceTable) { - Set distSelected = null; - if (sourceTable.getValue() != null) { - distSelected = new LinkedHashSet<>((Set) sourceTable.getValue()); - distSelected.remove(null); - } - return distSelected; - } - /** * * Add target table container properties. @@ -1206,6 +1026,10 @@ public final class HawkbitCommonUtil { targetTableContainer.addContainerProperty(SPUILabelDefinitions.VAR_POLL_STATUS_TOOL_TIP, String.class, null, false, true); targetTableContainer.addContainerProperty(SPUILabelDefinitions.VAR_DESC, String.class, "", false, true); + + targetTableContainer.addContainerProperty(ASSIGN_DIST_SET, DistributionSet.class, null, false, true); + targetTableContainer.addContainerProperty(INSTALL_DIST_SET, DistributionSet.class, null, false, true); + } /** @@ -1359,12 +1183,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 +1206,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 +1218,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; + } + } diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/SPDateTimeUtil.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/SPDateTimeUtil.java index 532dd010d..49bae86e1 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/SPDateTimeUtil.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/SPDateTimeUtil.java @@ -15,7 +15,9 @@ import java.util.HashMap; import java.util.Map; import java.util.TimeZone; +import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.time.DurationFormatUtils; +import org.eclipse.hawkbit.repository.model.BaseEntity; import com.vaadin.server.WebBrowser; @@ -80,14 +82,45 @@ public final class SPDateTimeUtil { * @param lastQueryDate * @return String formatted date */ - public static String getFormattedDate(final Long lastQueryDate) { + return formatDate(lastQueryDate, null); + } + + /** + * Get formatted date 'created at' by entity. + * + * @param baseEntity + * the entity + * @return String formatted date + */ + public static String formatCreatedAt(final BaseEntity baseEntity) { + if (baseEntity == null) { + return StringUtils.EMPTY; + } + return formatDate(baseEntity.getCreatedAt(), StringUtils.EMPTY); + } + + /** + * Get formatted date 'last modified at' by entity. + * + * @param baseEntity + * the entity + * @return String formatted date + */ + public static String formatLastModifiedAt(final BaseEntity baseEntity) { + if (baseEntity == null) { + return StringUtils.EMPTY; + } + return formatDate(baseEntity.getLastModifiedAt(), StringUtils.EMPTY); + } + + private static String formatDate(final Long lastQueryDate, final String defaultString) { if (lastQueryDate != null) { final SimpleDateFormat format = new SimpleDateFormat(SPUIDefinitions.LAST_QUERY_DATE_FORMAT); format.setTimeZone(getBrowserTimeZone()); return format.format(new Date(lastQueryDate)); } - return null; + return defaultString; } /** 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..fa1b6759d 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 @@ -75,6 +75,11 @@ public final class SPUIComponetIdProvider { */ public static final String TARGET_TEXT_FIELD = "target.search.textfield"; + /** + * ID for add target filter icon + */ + public static final String TARGET_FILTER_ADD_ICON_ID = "target.filter.add.id"; + /** * ID-Dist. */ @@ -501,6 +506,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. */ @@ -594,7 +604,7 @@ public final class SPUIComponetIdProvider { /** * Documentation Link in Login view and menu. */ - public static final String LINK_DOCUMENATION = "link.documentation"; + public static final String LINK_DOCUMENTATION = "link.documentation"; /** * Demo Link in Login view and menu. @@ -827,7 +837,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 +877,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 . */ diff --git a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/SPUIDefinitions.java b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/SPUIDefinitions.java index b29283ef8..75ea912a9 100644 --- a/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/SPUIDefinitions.java +++ b/hawkbit-ui/src/main/java/org/eclipse/hawkbit/ui/utils/SPUIDefinitions.java @@ -922,6 +922,11 @@ public final class SPUIDefinitions { */ public static final String CUSTOM_FILTER_ASSIGNED_DS = "Assigned DS"; + /** + * TARGET_FILTER_MANAGEMENT - header caption . + */ + public static final String TARGET_FILTER_LIST_HEADER_CAPTION = "Custom Filters"; + /** * CUSTOM_FILTER_STATUS. */ @@ -1001,7 +1006,6 @@ public final class SPUIDefinitions { */ public static final String ROLLOUT_GROUP_STARTED_DATE = "Started date"; - /** * Rollout group status column property. */ diff --git a/hawkbit-ui/src/main/resources/VAADIN/themes/hawkbit/customstyles/common.scss b/hawkbit-ui/src/main/resources/VAADIN/themes/hawkbit/customstyles/common.scss index 87ea5b0b9..beb405c30 100644 --- a/hawkbit-ui/src/main/resources/VAADIN/themes/hawkbit/customstyles/common.scss +++ b/hawkbit-ui/src/main/resources/VAADIN/themes/hawkbit/customstyles/common.scss @@ -143,9 +143,15 @@ .valo-menu-title { line-height: 1.2; } + .v-menubar-user-menu:after { display: none; } + + .v-menubar-menuitem-user-menuitem { + width: 100%; + } + .v-menubar-user-menu > .v-menubar-menuitem { white-space: normal !important; .v-icon { diff --git a/hawkbit-ui/src/main/resources/VAADIN/themes/hawkbit/customstyles/others.scss b/hawkbit-ui/src/main/resources/VAADIN/themes/hawkbit/customstyles/others.scss index 879fb8dd6..d327baa94 100644 --- a/hawkbit-ui/src/main/resources/VAADIN/themes/hawkbit/customstyles/others.scss +++ b/hawkbit-ui/src/main/resources/VAADIN/themes/hawkbit/customstyles/others.scss @@ -228,4 +228,8 @@ .v-tooltip{ max-width:43em; } + + .breadcrumbPaddingLeft{ + padding-left: 3px !important; + } } diff --git a/hawkbit-ui/src/main/resources/VAADIN/themes/hawkbit/customstyles/rollout.scss b/hawkbit-ui/src/main/resources/VAADIN/themes/hawkbit/customstyles/rollout.scss index 712e04ec1..b9049068e 100644 --- a/hawkbit-ui/src/main/resources/VAADIN/themes/hawkbit/customstyles/rollout.scss +++ b/hawkbit-ui/src/main/resources/VAADIN/themes/hawkbit/customstyles/rollout.scss @@ -19,20 +19,32 @@ } } + .v-context-menu .v-context-menu-item-basic-icon-container{ height:0px !important; width:0px !important; } - .v-context-menu, .v-context-menu .v-context-menu-item-basic{ + .v-context-menu .v-context-menu-item-basic{ background-color: #feffff !important; border-radius: 4px; + font-family : $app-font-family; + font-size : $app-text-font-size; + font-weight : normal; + font-style : normal; } + + .v-context-menu{ + background-color: #feffff !important; + border-radius: 4px; + } + .v-context-menu .v-context-menu-item-basic:focus, .v-context-menu .v-context-menu-item-basic-submenu:focus, .v-context-menu .v-context-menu-item-basic-open { @include valo-gradient($color: $hawkbit-primary-color); background-color: $hawkbit-primary-color !important; color: #e8eef3; + height: 30px; text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.05); } @@ -77,5 +89,9 @@ border-left: $v-grid-border-size solid $widget-border-color ; } + .v-button-boldhide{ + text-decoration:none; + } + } \ No newline at end of file diff --git a/hawkbit-ui/src/main/resources/VAADIN/themes/hawkbit/customstyles/target-filter-query.scss b/hawkbit-ui/src/main/resources/VAADIN/themes/hawkbit/customstyles/target-filter-query.scss index b29483da1..33ae2dd85 100644 --- a/hawkbit-ui/src/main/resources/VAADIN/themes/hawkbit/customstyles/target-filter-query.scss +++ b/hawkbit-ui/src/main/resources/VAADIN/themes/hawkbit/customstyles/target-filter-query.scss @@ -28,12 +28,12 @@ .error-icon{ color:$success-icon-color !important; - padding:2px; + padding-left:2px !important; } .success-icon{ color:$error-icon-color !important; - padding:2px; + padding-left:2px !important; } .on-focus-no-border:focus::after{ diff --git a/hawkbit-ui/src/main/resources/VAADIN/themes/hawkbit/hawkbittheme.scss b/hawkbit-ui/src/main/resources/VAADIN/themes/hawkbit/hawkbittheme.scss index a344cb5ae..128c66e55 100644 --- a/hawkbit-ui/src/main/resources/VAADIN/themes/hawkbit/hawkbittheme.scss +++ b/hawkbit-ui/src/main/resources/VAADIN/themes/hawkbit/hawkbittheme.scss @@ -132,4 +132,12 @@ $v-included-components: remove($v-included-components, form); left: 50%; margin-left: -20px; } + .v-generated-body &.v-app { + background-image: $app-background-image, linear-gradient(to bottom, $app-background-image-gradient) !important; + background-image: $app-background-image, -webkit-linear-gradient(top, $app-background-image-gradient) !important; + background-image: $app-background-image, -moz-linear-gradient(top, $app-background-image-gradient) !important; + background-position: bottom; + background-repeat: no-repeat; + } + } diff --git a/hawkbit-ui/src/main/resources/VAADIN/themes/hawkbit/images/profile-pic-300px.jpg b/hawkbit-ui/src/main/resources/VAADIN/themes/hawkbit/images/profile-pic-300px.jpg deleted file mode 100644 index 664afaa35..000000000 Binary files a/hawkbit-ui/src/main/resources/VAADIN/themes/hawkbit/images/profile-pic-300px.jpg and /dev/null differ diff --git a/hawkbit-ui/src/main/resources/messages.properties b/hawkbit-ui/src/main/resources/messages.properties index 27103a0b9..0f65ebe13 100644 --- a/hawkbit-ui/src/main/resources/messages.properties +++ b/hawkbit-ui/src/main/resources/messages.properties @@ -161,6 +161,7 @@ label.tag.name = Tag name label.configuration.auth.header = Allow targets to authenticate via a certificate authenticated by an reverse proxy label.configuration.auth.gatewaytoken = Allow a gateway to authenticate and manage multiple targets through a gateway security token label.configuration.auth.targettoken = Allow targets to authenticate directly with their target security token +label.configuration.anonymous.download = Allow targets to download artifacts without security credentials label.unsupported.browser.ie=Sorry! current browser is not supported. Please use Internet Explorer 11 and above # Checkbox label prefix with - checkbox @@ -486,3 +487,6 @@ message.error.starting.rollout = Server error. Error starting rollout. Please co #Menu menu.title = Software Provisioning + +#Target Filter Management +breadcrumb.target.filter.custom.filters = Custom Filters diff --git a/hawkbit-ui/src/main/resources/messages_de.properties b/hawkbit-ui/src/main/resources/messages_de.properties index 9ff2e5e75..12f04048a 100644 --- a/hawkbit-ui/src/main/resources/messages_de.properties +++ b/hawkbit-ui/src/main/resources/messages_de.properties @@ -159,6 +159,7 @@ label.tag.name = Tag name label.configuration.auth.header = Allow targets to authenticate via a certificate authenticated by an reverse proxy label.configuration.auth.gatewaytoken = Allow a gateway to authenticate and manage multiple targets through a gateway security token label.configuration.auth.targettoken = Allow targets to authenticate directly with their target security token +label.configuration.anonymous.download = Allow targets to download artifacts without security credentials label.unsupported.browser.ie=Sorry! current browser is not supported. Please use Internet Explorer 11 and above # Checkbox label prefix with - checkbox @@ -389,6 +390,7 @@ configuration.defaultdistributionset.select.label=Wahl des default Distribution configuration.savebutton.tooltip=Konfigurationen speichern configuration.cancellbutton.tooltip=Konfigurationen zur�cksetzen configuration.authentication.title=Authentifikationseinstellungen + #Calendar calendar.year=Jahr calendar.years=Jahre @@ -471,3 +473,6 @@ label.target.per.group = Targets per group : message.dist.already.assigned = Distribution {0} is already assigned to target message.error.creating.rollout = Server error. Error creating rollout. Please contact the administrator message.error.starting.rollout = Server error. Error starting rollout. Please contact the administrator + +#Target Filter Management +breadcrumb.target.filter.custom.filters = Custom Filters diff --git a/hawkbit-ui/src/main/resources/messages_en.properties b/hawkbit-ui/src/main/resources/messages_en.properties index 74f50f378..23b8149e3 100644 --- a/hawkbit-ui/src/main/resources/messages_en.properties +++ b/hawkbit-ui/src/main/resources/messages_en.properties @@ -160,6 +160,7 @@ label.tag.name = Tag name label.configuration.auth.header = Allow targets to authenticate via a certificate authenticated by an reverse proxy label.configuration.auth.gatewaytoken = Allow a gateway to authenticate and manage multiple targets through a gateway security token label.configuration.auth.targettoken = Allow targets to authenticate directly with their target security token +label.configuration.anonymous.download = Allow targets to download artifacts without security credentials label.unsupported.browser.ie=Sorry! current browser is not supported. Please use Internet Explorer 11 and above # Checkbox label prefix with - checkbox @@ -463,3 +464,6 @@ label.target.per.group = Targets per group : message.dist.already.assigned = Distribution {0} is already assigned to target message.error.creating.rollout = Server error. Error creating rollout. Please contact the administrator message.error.starting.rollout = Server error. Error starting rollout. Please contact the administrator + +#Target Filter Management +breadcrumb.target.filter.custom.filters = Custom Filters diff --git a/pom.xml b/pom.xml index 2415b9935..0e4fec71d 100644 --- a/pom.xml +++ b/pom.xml @@ -8,8 +8,7 @@ http://www.eclipse.org/legal/epl-v10.html --> - + 4.0.0 @@ -25,15 +24,19 @@ hawkBit :: Parent - hawkbit-dmf-api - hawkbit-rest-api hawkbit-core hawkbit-security-core - hawkbit-repository + hawkbit-rest-core + hawkbit-mgmt-api + hawkbit-mgmt-resource + hawkbit-ddi-api + hawkbit-ddi-dl-api + hawkbit-ddi-resource + hawkbit-dmf-api hawkbit-dmf-amqp + hawkbit-repository hawkbit-security-integration hawkbit-http-security - hawkbit-rest-resource hawkbit-ui hawkbit-artifact-repository-mongo hawkbit-autoconfigure @@ -74,7 +77,7 @@ 1.0.0 0.0.6.RELEASE - 7.6.3 + 7.6.5 ${vaadin.version} 7.4.0.1 2.2.0 @@ -84,6 +87,7 @@ + 1.1.0.Final 1.4 2.0M10 1.4.22 @@ -93,7 +97,7 @@ 0.9.1 1.8.5 19.0 - 1.3.5 + 1.4.3 1.50.2 1.18.1 2.2.4 @@ -163,6 +167,7 @@ **/*.sql eclipse_codeformatter.xml **/addons.scss + **/VAADIN/widgetsets/** JAVADOC_STYLE @@ -243,7 +248,7 @@ - + @@ -257,7 +262,7 @@ - + @@ -419,6 +424,11 @@ + + javax.validation + validation-api + ${validation-api.version} + javax.el javax.el-api @@ -439,39 +449,16 @@ org.springframework.boot spring-boot-starter-actuator ${spring.boot.version} - - - org.springframework.boot - spring-boot-starter-logging - - - - - org.springframework.boot - spring-boot-starter-log4j2 - ${spring.boot.version} org.springframework.boot spring-boot-starter-web ${spring.boot.version} - - - org.springframework.boot - spring-boot-starter-logging - - org.springframework.boot spring-boot-starter ${spring.boot.version} - - - org.springframework.boot - spring-boot-starter-logging - - org.springframework.boot @@ -542,13 +529,11 @@ - org.apache.commons commons-lang3 ${commons-lang3.version} - org.springframework.boot spring-boot-starter-test @@ -620,4 +605,4 @@ - + \ No newline at end of file