diff --git a/README.md b/README.md index b655e703770..e14cafdf6ab 100644 --- a/README.md +++ b/README.md @@ -14,8 +14,11 @@ ![GitHub Actions CI](https://img.shields.io/github/actions/workflow/status/eclipse/kapua/kapua-ci.yaml)
-[Eclipse Kapua™](http://eclipse.org/kapua) is a modular platform providing the services required to manage IoT gateways and smart edge devices. Kapua provides a core integration framework and an -initial set of core IoT services including a device registry, device management services, messaging services, data management, and application enablement. +[Eclipse Kapua™](http://eclipse.org/kapua) is a modular platform providing the +services required to manage IoT gateways and smart edge devices. Kapua provides a core +integration framework and an +initial set of core IoT services including a device registry, device management services, +messaging services, data management, and application enablement. ## Quick Start Guide @@ -33,7 +36,8 @@ Two more backend services are required that implement the data tier: * The SQL database * The NoSQL datastore -Eclipse Kapua™ can be deployed in a variety of modes. A practical way for running a local demo is through Docker containers. +Eclipse Kapua™ can be deployed in a variety of modes. A practical way for running a +local demo is through Docker containers. ### Requirements @@ -41,17 +45,22 @@ Before starting, check that your environment has the following prerequisites: * 64 bit architecture * Docker Version 1.2+ - * Docker compose V2 for release >= 1.6.12 (present in latest docker desktop versions) + * Docker compose V2 for release >= 1.6.12 (present in latest docker desktop versions) * Internet Access (needed to download the artifacts) ### Demo Setup -The team maintains some docker images in a Docker Hub repository at [Kapua Repository](https://hub.docker.com/r/kapua/). Check the repo to view the list of available images, if you haven't found one -fitting your needs you may create your own. Please refer to the paragraph [More deployment info](#more-deployment-info) to find more about creating your own images and/or alternative demo deployment +The team maintains some docker images in a Docker Hub repository +at [Kapua Repository](https://hub.docker.com/r/kapua/). Check the repo to view the list of +available images, if you haven't found one +fitting your needs you may create your own. Please refer to the +paragraph [More deployment info](#more-deployment-info) to find more about creating your +own images and/or alternative demo deployment scenarios. *** -**Note:** the Docker Hub repository mentioned above is not the official project repository from Eclipse Foundation. +**Note:** the Docker Hub repository mentioned above is not the official project repository +from Eclipse Foundation. *** Suppose the target is the released version V (for example, 1.6.7). @@ -59,22 +68,30 @@ Suppose the target is the released version V (for example, 1.6.7). * Clone Eclipse Kapua™ into a local directory * Open an OS shell and move to Kapua project root directory * Start Docker runtime -* Perform a checkout to the related git tag for version V. For the proposed example, the command is: +* Perform a checkout to the related git tag for version V. For the proposed example, the + command is: + git checkout 1.6.7 - git checkout 1.6.7 +* Set the `IMAGE_VERSION` environment variable with a value equal to the target version. + For the proposed example: -* Set the `IMAGE_VERSION` environment variable with a value equal to the target version. For the proposed example: + export IMAGE_VERSION=1.6.7 +The repository mentioned above hosts only images of released versions. If your target is a +SNAPSHOT version, a local build is required +in order to create the docker images and proceed to the next +step. [Here you can found instructions for building](docs/developer-guide/en/building.md) - export IMAGE_VERSION=1.6.7 +*** +**A note regarding Docker Compose:** starting from Kapua 1.6.12, the project migrated to +Docker Compose V2. This means that, +depending on your terget version V, your Docker Desktop version should be aligned +accordingly in order to smoothly deploy the application. If you are trying to deploy a +version BEFORE 1.6.12, make sure to have a Docker Desktop version released before july -The repository mentioned above hosts only images of released versions. If your target is a SNAPSHOT version, a local build is required -in order to create the docker images and proceed to the next step. [Here you can found instructions for building](docs/developer-guide/en/building.md) +2023. Otherwise, the latest should be fine.** -*** -**A note regarding Docker Compose:** starting from Kapua 1.6.12, the project migrated to Docker Compose V2. This means that, -depending on your terget version V, your Docker Desktop version should be aligned accordingly in order to smoothly deploy the application. If you are trying to deploy a version BEFORE 1.6.12, make sure to have a Docker Desktop version released before july 2023. Otherwise, the latest should be fine.** *** * Start Kapua: @@ -117,31 +134,41 @@ On Windows (PowerShell): ### Access -Once the containers are running, the Kapua services can be accessed. Eclipse Kapua™ is a multi tenant -system. The demo installation comes with one default tenant, called _kapua-sys_, which is also the root tenant. +Once the containers are running, the Kapua services can be accessed. Eclipse Kapua™ +is a multi tenant +system. The demo installation comes with one default tenant, called _kapua-sys_, which is +also the root tenant. In Eclipse Kapua™ a _tenant_ is commonly referred to as an _account_. #### The console -The administration console is available at [http://localhost:8080/](http://localhost:8080/). -Copy paste the URL above to a Web browser, as the login screen appears, type the following credentials: +The administration console is available +at [http://localhost:8080/](http://localhost:8080/). +Copy paste the URL above to a Web browser, as the login screen appears, type the following +credentials: * Username: `kapua-sys` * Password: `kapua-password` Press _Login_ button and start working with the console. -**Note**: If you are using Docker on Windows the hostname will most likely not be `localhost` but +**Note**: If you are using Docker on Windows the hostname will most likely not be +`localhost` but the IP address of your docker instance. #### RESTful APIs -The documentation of RESTful API is available at [http://localhost:8081/doc/](http://localhost:8081/doc/) while the mount points are available at [http://localhost:8081/v1/](http://localhost:8081/v1/) +The documentation of RESTful API is available +at [http://localhost:8081/doc/](http://localhost:8081/doc/) while the mount points are +available at [http://localhost:8081/v1/](http://localhost:8081/v1/) . -The documentation is available through Swagger UI which greatly helps testing and exploring the exposed services. +The documentation is available through Swagger UI which greatly helps testing and +exploring the exposed services. -In order to get access a REST resource through an API, an authentication token is needed. Fortunately the token can be easily obtained by executing the authentication API. There are several ways to +In order to get access a REST resource through an API, an authentication token is needed. +Fortunately the token can be easily obtained by executing the authentication API. There +are several ways to invoke the API, an easy one is by using the Swagger UI: * Open the URL http://localhost:8081/doc/ @@ -158,7 +185,8 @@ invoke the API, an easy one is by using the Swagger UI: } ``` -**Note:** as an alternative to the previous, if curl is available on your machine, execute the following from the shell: +**Note:** as an alternative to the previous, if curl is available on your machine, execute +the following from the shell: ```bash curl -X POST 'http://localhost:8081/v1/authentication/user' --header 'Content-Type: application/json' --header 'Accept: application/json' -d '{ @@ -174,17 +202,24 @@ The system will return a JSON object. * Copy the value of the field _tokenId_ * Paste the value in the box labelled _api\_key_ at the top of the web page -Swagger will automatically add the authentication token to each subsequent request done using the Swagger UI. You're ready to try executing the documented APIs. +Swagger will automatically add the authentication token to each subsequent request done +using the Swagger UI. You're ready to try executing the documented APIs. -**Note**: If you are using Docker on Windows the hostname will most likely not be `localhost` but +**Note**: If you are using Docker on Windows the hostname will most likely not be +`localhost` but the IP address of your docker instance. #### The Broker -The broker container exposes an [Mqtt](http://mqtt.org/) end point at tcp://localhost:1883/. -The broker can be accessed through either [Eclipse Kura™](http://www.eclipse.org/kura/) or a plain Mqtt client like, for example, [Eclipse Paho™](http://www.eclipse.org/paho/). +The broker container exposes an [Mqtt](http://mqtt.org/) end point at tcp://localhost: +1883/. +The broker can be accessed through +either [Eclipse Kura™](http://www.eclipse.org/kura/) or a plain Mqtt client like, +for example, [Eclipse Paho™](http://www.eclipse.org/paho/). -In order for a client to establish a Mqtt connection with the broker, a client must provide a valid identity. The _kapua-sys_ account provides the user named _kapua-broker_ which has been pre-seeded +In order for a client to establish a Mqtt connection with the broker, a client must +provide a valid identity. The _kapua-sys_ account provides the user named _kapua-broker_ +which has been pre-seeded and profiled for the purpose. The credentials for the user kapua-broker are the following: @@ -194,7 +229,8 @@ The credentials for the user kapua-broker are the following: **Note:** do not use the user `kapua-sys` to establish Mqtt connections. -**Note**: If you are using Docker on Windows the hostname will most likely not be `localhost` but +**Note**: If you are using Docker on Windows the hostname will most likely not be +`localhost` but the IP address of your docker instance. ### Connecting Kura to Kapua @@ -203,19 +239,24 @@ the IP address of your docker instance. #### Simulation -Kapua comes with a framework that you can use to simulate Kura gateways. It can be used to test your Kapua deployments easily. See [Simulator documentation](docs/user-manual/en/simulator.md) for more +Kapua comes with a framework that you can use to simulate Kura gateways. It can be used to +test your Kapua deployments easily. +See [Simulator documentation](docs/user-manual/en/simulator.md) for more info. #### More deployment info -Installing and running a demo using Docker is easy, but it's not the only way. There are other scenarios that the users may be interested in. We provide advanced setup scenarios in the following +Installing and running a demo using Docker is easy, but it's not the only way. There are +other scenarios that the users may be interested in. We provide advanced setup scenarios +in the following guides: * [Running with Docker](deployment/docker/README.md) * [Running with OpenShift](docs/developer-guide/en/running.md#openshift) * [Running with Minishift](docs/developer-guide/en/running.md#minishift) -They will provide more advanced deployment scenarios. For example, if you are interested in having debugging/logging capabilities we recommend you to consult them. +They will provide more advanced deployment scenarios. For example, if you are interested +in having debugging/logging capabilities we recommend you to consult them. ### User & Developer guides @@ -224,7 +265,8 @@ They will provide more advanced deployment scenarios. For example, if you are in ### Contributing -If you're interested to get involved in IoT and Eclipse Kapua™ project, join the community and give your contribution to the project, please +If you're interested to get involved in IoT and Eclipse Kapua™ project, join the +community and give your contribution to the project, please read [how to contribute to Eclipse Kapua™](https://github.com/eclipse/kapua/blob/develop/CONTRIBUTING.md). ### Community diff --git a/UPGRADE_NOTES.md b/UPGRADE_NOTES.md index b407ad52303..dae85e037c6 100644 --- a/UPGRADE_NOTES.md +++ b/UPGRADE_NOTES.md @@ -1,79 +1,95 @@ -# Upgrade Notes v 2.1.0-SNAPSHOT +# Upgrade Notes v 2.1.0-FALSE_EXTENSIONS-SNAPSHOT -Below are described most important changes, features, additions and bugfixes that needs attention while performing the upgrade from the previous version. +Below are described most important changes, features, additions and bugfixes that needs +attention while performing the upgrade from the previous version. -This report is only partial for Eclipse Kapua release 2.1.0-SNAPSHOT, since we started to maintain it mid-release development. +This report is only partial for Eclipse Kapua release 2.1.0-FALSE_EXTENSIONS-SNAPSHOT, +since we started to maintain it mid-release development. ## Changes -### Deprecation of `db.pool.size.min` and `db.pool.size.max` sizing options [[#4112](https://github.com/eclipse/kapua/pull/4112)] +### Deprecation of `db.pool.size.min` and -Deprecated `commons.db.pool.size.min` and `commons.db.pool.size.max` settings, switching to a new `commons.db.pool.size.fixed` setting which will configure the database connection pool to a fixed size with a default value of `5`. +`db.pool.size.max` sizing options [[#4112](https://github.com/eclipse/kapua/pull/4112)] -Backward compatibility is granted by `db.pool.size.strategy`. Default value is `fixed`, but it can be changed to `range` to continue use of a variable database connection pool. Be aware that at some point `range` strategy will be removed and only fixed size will be available. +Deprecated `commons.db.pool.size.min` and `commons.db.pool.size.max` settings, switching +to a new `commons.db.pool.size.fixed` setting which will configure the database connection +pool to a fixed size with a default value of `5`. +Backward compatibility is granted by `db.pool.size.strategy`. Default value is `fixed`, +but it can be changed to `range` to continue use of a variable database connection pool. +Be aware that at some point `range` strategy will be removed and only fixed size will be +available. ### Duplicate Name Exception is now returned as a 409 error [[#4133](https://github.com/eclipse/kapua/pull/4112)] -Fixed the HTTP response code when a `KapuaDuplicateNameException` occurs from `500 Internal error` to the correct `409 Conflict`. +Fixed the HTTP response code when a `KapuaDuplicateNameException` occurs from +`500 Internal error` to the correct `409 Conflict`. The body of the response will contain additional information on the error. - ### Introduction of un-scoped entities for Job Step Definitions [[#3996](https://github.com/eclipse/kapua/pull/3996)] Introduced the concept of "Un-scoped entities" as opposite of "Scoped entities". -Normally entities belongs to a certain scope. For example: Users, Tags, Devices belongs to an Account. -There are some entities that are available for all Accounts because of their nature and usage. For example: JobStepDefinitions are available to all scopes. - -With this feature we changed the way this "availability" was implemented and made it available at the core of the Service API. +Normally entities belongs to a certain scope. For example: Users, Tags, Devices belongs to +an Account. +There are some entities that are available for all Accounts because of their nature and +usage. For example: JobStepDefinitions are available to all scopes. -User is not required to perform any action to the existing data and the migration of the Job Step Definitions will be performed by the Job Step Definition Aligner that will reflect any change to the Job Step Definitions coded into the Database. +With this feature we changed the way this "availability" was implemented and made it +available at the core of the Service API. +User is not required to perform any action to the existing data and the migration of the +Job Step Definitions will be performed by the Job Step Definition Aligner that will +reflect any change to the Job Step Definitions coded into the Database. ### Invalid Trigger Exceptions are now returned as a 400 error [[#4147](https://github.com/eclipse/kapua/pull/4147)] -Fixed the HTTP response code when a `TriggerInvalidDatesException` or `TriggerInvalidSchedulingException` occurs from `500 Internal error` to the correct `400 Bad Request`. +Fixed the HTTP response code when a `TriggerInvalidDatesException` or +`TriggerInvalidSchedulingException` occurs from `500 Internal error` to the correct +`400 Bad Request`. The body of the response will contain additional information on the error. - ### Max Number Of Entity Reached exception is now returned as a 403 error [[#4154](https://github.com/eclipse/kapua/pull/4154)] -Fixed the HTTP response code when a `KapuaMaxNumberOfItemsReachedException` occurs from `500 Internal error` to the correct `403 Forbidden`. +Fixed the HTTP response code when a `KapuaMaxNumberOfItemsReachedException` occurs from +`500 Internal error` to the correct `403 Forbidden`. The body of the response will contain additional information on the error. - ### Job Step Property value now supports JSON format for complex types [[#4161](https://github.com/eclipse/kapua/pull/4161)] -Allowed complex objects to be inserted with JSON format. Before only XML format was allowed. +Allowed complex objects to be inserted with JSON format. Before only XML format was +allowed. +### Datastore search APIs will now allow multiple -### Datastore search APIs will now allow multiple `clientId` to be specified [[#4130](https://github.com/eclipse/kapua/pull/4130)] +`clientId` to be specified [[#4130](https://github.com/eclipse/kapua/pull/4130)] -Allowed the following REST API resources to accept more than one `clientId` as query parameter. +Allowed the following REST API resources to accept more than one `clientId` as query +parameter. - `GET /{scopeId}/data/messages` - `GET /{scopeId}/data/metric` - `GET /{scopeId}/data/clients` - `GET /{scopeId}/data/channels` - ## DB Changes ### New column in MFA Option table [[#4115](https://github.com/eclipse/kapua/pull/4115)] New `has_trust_me` column has been added to the `atht_mfa_option`. -New column defaults to `null` and doesn't need any migration. The code itself will populate the column accordingly on first update. +New column defaults to `null` and doesn't need any migration. The code itself will +populate the column accordingly on first update. For large `atht_mfa_option` tables it might take sometime to be added. - ### New column in Trigger Definition Property table [[#4134](https://github.com/eclipse/kapua/pull/4134)] -New `description` column has been added to `schdl_trigger_properties` and `schdl_trigger_definition_properties`. - -The column default to `null` and the migration/population procedure will be performed by the Trigger Definition Aligner at application startup. +New `description` column has been added to `schdl_trigger_properties` and +`schdl_trigger_definition_properties`. +The column default to `null` and the migration/population procedure will be performed by +the Trigger Definition Aligner at application startup. diff --git a/assembly/api/pom.xml b/assembly/api/pom.xml index 9456d579902..6d75e61c94f 100644 --- a/assembly/api/pom.xml +++ b/assembly/api/pom.xml @@ -19,7 +19,7 @@ kapua-assembly org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT pom diff --git a/assembly/broker-artemis/pom.xml b/assembly/broker-artemis/pom.xml index 1b31a7e22b8..b8929e96970 100644 --- a/assembly/broker-artemis/pom.xml +++ b/assembly/broker-artemis/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-assembly - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT pom diff --git a/assembly/console/pom.xml b/assembly/console/pom.xml index dc884af515d..4d3893c373d 100644 --- a/assembly/console/pom.xml +++ b/assembly/console/pom.xml @@ -19,7 +19,7 @@ org.eclipse.kapua kapua-assembly - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT pom diff --git a/assembly/consumer/lifecycle/entrypoint/run-consumer-lifecycle b/assembly/consumer/lifecycle/entrypoint/run-consumer-lifecycle index 1366bf64936..58582f536a1 100644 --- a/assembly/consumer/lifecycle/entrypoint/run-consumer-lifecycle +++ b/assembly/consumer/lifecycle/entrypoint/run-consumer-lifecycle @@ -13,4 +13,4 @@ JAVA_OPTS="${JAVA_OPTS} --add-opens java.base/java.lang=ALL-UNNAMED" -java ${JAVA_OPTS} ${DEBUG_OPTS} ${JMX_OPTS} -jar kapua-consumer-lifecycle-2.1.0-SNAPSHOT-app.jar +java ${JAVA_OPTS} ${DEBUG_OPTS} ${JMX_OPTS} -jar kapua-consumer-lifecycle-2.1.0-FALSE_EXTENSIONS-SNAPSHOT-app.jar diff --git a/assembly/consumer/lifecycle/pom.xml b/assembly/consumer/lifecycle/pom.xml index aa5d0253a28..f6b0a6098b0 100644 --- a/assembly/consumer/lifecycle/pom.xml +++ b/assembly/consumer/lifecycle/pom.xml @@ -17,7 +17,7 @@ kapua-assembly-consumer org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT 4.0.0 diff --git a/assembly/consumer/pom.xml b/assembly/consumer/pom.xml index 962e069b04c..9e1078d194f 100644 --- a/assembly/consumer/pom.xml +++ b/assembly/consumer/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-assembly - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT pom diff --git a/assembly/consumer/telemetry/entrypoint/run-consumer-telemetry b/assembly/consumer/telemetry/entrypoint/run-consumer-telemetry index 513000dd51d..60e607c3233 100644 --- a/assembly/consumer/telemetry/entrypoint/run-consumer-telemetry +++ b/assembly/consumer/telemetry/entrypoint/run-consumer-telemetry @@ -13,4 +13,4 @@ JAVA_OPTS="${JAVA_OPTS} --add-opens java.base/java.lang=ALL-UNNAMED" -java ${JAVA_OPTS} ${DEBUG_OPTS} ${JMX_OPTS} -jar kapua-consumer-telemetry-2.1.0-SNAPSHOT-app.jar +java ${JAVA_OPTS} ${DEBUG_OPTS} ${JMX_OPTS} -jar kapua-consumer-telemetry-2.1.0-FALSE_EXTENSIONS-SNAPSHOT-app.jar diff --git a/assembly/consumer/telemetry/pom.xml b/assembly/consumer/telemetry/pom.xml index 36c7539ee24..6fc8c14e3a9 100644 --- a/assembly/consumer/telemetry/pom.xml +++ b/assembly/consumer/telemetry/pom.xml @@ -18,7 +18,7 @@ kapua-assembly-consumer org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT 4.0.0 diff --git a/assembly/events-broker/pom.xml b/assembly/events-broker/pom.xml index 1427e85fc05..6b9204355c3 100644 --- a/assembly/events-broker/pom.xml +++ b/assembly/events-broker/pom.xml @@ -19,7 +19,7 @@ org.eclipse.kapua kapua-assembly - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT pom diff --git a/assembly/java-base/pom.xml b/assembly/java-base/pom.xml index d6858d39f88..fb4c57a4d27 100644 --- a/assembly/java-base/pom.xml +++ b/assembly/java-base/pom.xml @@ -19,7 +19,7 @@ org.eclipse.kapua kapua-assembly - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT pom diff --git a/assembly/jetty-base/pom.xml b/assembly/jetty-base/pom.xml index 9da71c65329..456b639c0eb 100644 --- a/assembly/jetty-base/pom.xml +++ b/assembly/jetty-base/pom.xml @@ -19,7 +19,7 @@ org.eclipse.kapua kapua-assembly - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT pom diff --git a/assembly/job-engine/pom.xml b/assembly/job-engine/pom.xml index bb22db4c737..30906b9db5e 100644 --- a/assembly/job-engine/pom.xml +++ b/assembly/job-engine/pom.xml @@ -19,7 +19,7 @@ kapua-assembly org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-assembly-job-engine diff --git a/assembly/pom.xml b/assembly/pom.xml index 3fd129198ed..199b402dc02 100644 --- a/assembly/pom.xml +++ b/assembly/pom.xml @@ -19,7 +19,7 @@ org.eclipse.kapua kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-assembly diff --git a/assembly/service/authentication/entrypoint/run-service-authentication b/assembly/service/authentication/entrypoint/run-service-authentication index 2ce1430c6f7..54b5ad695af 100644 --- a/assembly/service/authentication/entrypoint/run-service-authentication +++ b/assembly/service/authentication/entrypoint/run-service-authentication @@ -11,4 +11,4 @@ # Eurotech ################################################################################ -java ${JAVA_OPTS} ${DEBUG_OPTS} ${JMX_OPTS} -jar kapua-service-authentication-2.1.0-SNAPSHOT-app.jar +java ${JAVA_OPTS} ${DEBUG_OPTS} ${JMX_OPTS} -jar kapua-service-authentication-2.1.0-FALSE_EXTENSIONS-SNAPSHOT-app.jar diff --git a/assembly/service/authentication/pom.xml b/assembly/service/authentication/pom.xml index 0c3a490be95..b2b7e914d95 100644 --- a/assembly/service/authentication/pom.xml +++ b/assembly/service/authentication/pom.xml @@ -17,7 +17,7 @@ kapua-assembly-service org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT 4.0.0 diff --git a/assembly/service/pom.xml b/assembly/service/pom.xml index 5b48874dc3e..572b0d4aed2 100644 --- a/assembly/service/pom.xml +++ b/assembly/service/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-assembly - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT pom diff --git a/assembly/sql/pom.xml b/assembly/sql/pom.xml index a6816d92c48..94ee4f6aff0 100644 --- a/assembly/sql/pom.xml +++ b/assembly/sql/pom.xml @@ -19,7 +19,7 @@ org.eclipse.kapua kapua-assembly - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT pom diff --git a/broker/artemis/plugin/pom.xml b/broker/artemis/plugin/pom.xml index 2274a9986d1..fda9f63267b 100644 --- a/broker/artemis/plugin/pom.xml +++ b/broker/artemis/plugin/pom.xml @@ -17,7 +17,7 @@ org.eclipse.kapua kapua-broker-artemis - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-broker-artemis-plugin diff --git a/broker/artemis/pom.xml b/broker/artemis/pom.xml index 271cfcc9e91..a4b946549c0 100644 --- a/broker/artemis/pom.xml +++ b/broker/artemis/pom.xml @@ -19,7 +19,7 @@ kapua-broker org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT pom diff --git a/broker/pom.xml b/broker/pom.xml index b8f203b1427..7fb781c787d 100644 --- a/broker/pom.xml +++ b/broker/pom.xml @@ -19,7 +19,7 @@ kapua org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT pom diff --git a/build-tools/pom.xml b/build-tools/pom.xml index 78e34c5fd02..90c91f2a810 100644 --- a/build-tools/pom.xml +++ b/build-tools/pom.xml @@ -24,7 +24,7 @@ org.eclipse.kapua.build kapua-build-tools - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT UTF-8 diff --git a/client/gateway/api/pom.xml b/client/gateway/api/pom.xml index a38e71c86e8..a20288cc566 100644 --- a/client/gateway/api/pom.xml +++ b/client/gateway/api/pom.xml @@ -19,7 +19,7 @@ org.eclipse.kapua kapua-client-gateway - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT .. diff --git a/client/gateway/features/karaf/pom.xml b/client/gateway/features/karaf/pom.xml index bb463b7e51c..8616672159a 100644 --- a/client/gateway/features/karaf/pom.xml +++ b/client/gateway/features/karaf/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-client-gateway-features - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT .. diff --git a/client/gateway/features/pom.xml b/client/gateway/features/pom.xml index 6d29f6689ba..6df7e0afa6e 100644 --- a/client/gateway/features/pom.xml +++ b/client/gateway/features/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-client-gateway - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT Eclipse Kapua :: Gateway Client :: Features diff --git a/client/gateway/pom.xml b/client/gateway/pom.xml index dcaf727bd4e..f18d61cbefa 100644 --- a/client/gateway/pom.xml +++ b/client/gateway/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-client - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-client-gateway diff --git a/client/gateway/profile/kura/pom.xml b/client/gateway/profile/kura/pom.xml index e5714293224..fa57223a768 100644 --- a/client/gateway/profile/kura/pom.xml +++ b/client/gateway/profile/kura/pom.xml @@ -20,7 +20,7 @@ org.eclipse.kapua kapua-client-gateway - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT ../.. diff --git a/client/gateway/provider/fuse/pom.xml b/client/gateway/provider/fuse/pom.xml index f4d783b5eaf..a6c1c43a898 100644 --- a/client/gateway/provider/fuse/pom.xml +++ b/client/gateway/provider/fuse/pom.xml @@ -19,7 +19,7 @@ org.eclipse.kapua kapua-client-gateway-provider - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT .. diff --git a/client/gateway/provider/mqtt/pom.xml b/client/gateway/provider/mqtt/pom.xml index 31595da4d0b..29b12ee5649 100644 --- a/client/gateway/provider/mqtt/pom.xml +++ b/client/gateway/provider/mqtt/pom.xml @@ -19,7 +19,7 @@ org.eclipse.kapua kapua-client-gateway-provider - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT .. diff --git a/client/gateway/provider/paho/pom.xml b/client/gateway/provider/paho/pom.xml index 93204d7be97..392b0639b68 100644 --- a/client/gateway/provider/paho/pom.xml +++ b/client/gateway/provider/paho/pom.xml @@ -19,7 +19,7 @@ org.eclipse.kapua kapua-client-gateway-provider - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT .. diff --git a/client/gateway/provider/pom.xml b/client/gateway/provider/pom.xml index 6164b5d73e8..f7810ea5a0c 100644 --- a/client/gateway/provider/pom.xml +++ b/client/gateway/provider/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-client-gateway - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT .. diff --git a/client/gateway/spi/pom.xml b/client/gateway/spi/pom.xml index 9ebf960c420..1772a83a2e5 100644 --- a/client/gateway/spi/pom.xml +++ b/client/gateway/spi/pom.xml @@ -19,7 +19,7 @@ org.eclipse.kapua kapua-client-gateway - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT .. diff --git a/client/pom.xml b/client/pom.xml index 560f29ff189..85650b14e00 100644 --- a/client/pom.xml +++ b/client/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-client diff --git a/client/security/pom.xml b/client/security/pom.xml index 2680c5c78dd..bd9f13446dd 100644 --- a/client/security/pom.xml +++ b/client/security/pom.xml @@ -17,7 +17,7 @@ org.eclipse.kapua kapua-client - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-client-security diff --git a/commons-rest/errors/pom.xml b/commons-rest/errors/pom.xml index 910d050272e..7e4a4452964 100644 --- a/commons-rest/errors/pom.xml +++ b/commons-rest/errors/pom.xml @@ -18,7 +18,7 @@ kapua-commons-rest org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-commons-rest-errors diff --git a/commons-rest/filters/pom.xml b/commons-rest/filters/pom.xml index 2b6ecc524bb..ec61b8322cd 100644 --- a/commons-rest/filters/pom.xml +++ b/commons-rest/filters/pom.xml @@ -18,7 +18,7 @@ kapua-commons-rest org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-commons-rest-filters diff --git a/commons-rest/filters/src/main/java/org/eclipse/kapua/commons/rest/filters/CORSResponseFilter.java b/commons-rest/filters/src/main/java/org/eclipse/kapua/commons/rest/filters/CORSResponseFilter.java index 83bc0c0b3dc..e510d42317d 100644 --- a/commons-rest/filters/src/main/java/org/eclipse/kapua/commons/rest/filters/CORSResponseFilter.java +++ b/commons-rest/filters/src/main/java/org/eclipse/kapua/commons/rest/filters/CORSResponseFilter.java @@ -12,10 +12,25 @@ *******************************************************************************/ package org.eclipse.kapua.commons.rest.filters; -import com.google.common.base.Strings; -import com.google.common.collect.HashMultimap; -import com.google.common.collect.Multimap; -import com.google.common.net.HttpHeaders; +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.Collection; +import java.util.List; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; + +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.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + import org.apache.shiro.web.util.WebUtils; import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.commons.rest.filters.settings.KapuaRestFiltersSetting; @@ -23,35 +38,20 @@ import org.eclipse.kapua.commons.security.KapuaSecurityUtils; import org.eclipse.kapua.locator.KapuaLocator; import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.account.AccountFactory; +import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.service.account.AccountListResult; -import org.eclipse.kapua.service.account.AccountQuery; import org.eclipse.kapua.service.account.AccountService; import org.eclipse.kapua.service.endpoint.EndpointInfo; -import org.eclipse.kapua.service.endpoint.EndpointInfoFactory; import org.eclipse.kapua.service.endpoint.EndpointInfoListResult; import org.eclipse.kapua.service.endpoint.EndpointInfoQuery; import org.eclipse.kapua.service.endpoint.EndpointInfoService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -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.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.Collection; -import java.util.List; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.TimeUnit; +import com.google.common.base.Strings; +import com.google.common.collect.HashMultimap; +import com.google.common.collect.Multimap; +import com.google.common.net.HttpHeaders; /** * CORS {@link Filter} implementation. @@ -66,9 +66,7 @@ public class CORSResponseFilter implements Filter { private final KapuaLocator locator = KapuaLocator.getInstance(); private final AccountService accountService = locator.getService(AccountService.class); - private final AccountFactory accountFactory = locator.getFactory(AccountFactory.class); private final EndpointInfoService endpointInfoService = locator.getService(EndpointInfoService.class); - private final EndpointInfoFactory endpointInfoFactory = locator.getFactory(EndpointInfoFactory.class); private final KapuaRestFiltersSetting kapuaRestFiltersSetting = locator.getComponent(KapuaRestFiltersSetting.class); private final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); private ScheduledFuture refreshTask; @@ -107,7 +105,8 @@ public void doFilter(ServletRequest request, ServletResponse response, FilterCha String errorMessage = null; if (Strings.isNullOrEmpty(fetchSite)) { - logger.warn("Sec-Fetch-Site' header not present in request: {} {}. CORSResponseFilter may produce false positives for this request. User-Agent is: {}", httpRequest.getMethod(), httpRequest.getPathInfo(), httpRequest.getHeader(HttpHeaders.USER_AGENT)); + logger.warn("Sec-Fetch-Site' header not present in request: {} {}. CORSResponseFilter may produce false positives for this request. User-Agent is: {}", httpRequest.getMethod(), + httpRequest.getPathInfo(), httpRequest.getHeader(HttpHeaders.USER_AGENT)); } if (Strings.isNullOrEmpty(origin)) { logger.warn("'Origin' header not present in request: {} {}. User-Agent is: {}", httpRequest.getMethod(), httpRequest.getPathInfo(), httpRequest.getHeader(HttpHeaders.USER_AGENT)); @@ -130,7 +129,8 @@ public void doFilter(ServletRequest request, ServletResponse response, FilterCha logger.error(errorMessage); } } else { - logger.debug("HTTP sec-fetch-site same-origin detected and allowed. Request: {} {}. User-Agent is: {}", httpRequest.getMethod(), httpRequest.getPathInfo(), httpRequest.getHeader(HttpHeaders.USER_AGENT)); + logger.debug("HTTP sec-fetch-site same-origin detected and allowed. Request: {} {}. User-Agent is: {}", httpRequest.getMethod(), httpRequest.getPathInfo(), + httpRequest.getHeader(HttpHeaders.USER_AGENT)); } } int errorCode = httpResponse.getStatus(); @@ -152,12 +152,12 @@ private String getExplicitOrigin(String origin) throws MalformedURLException { } switch (originUrl.getProtocol()) { - case "http": - return origin + ":80"; - case "https": - return origin + ":443"; - default: - return origin; + case "http": + return origin + ":80"; + case "https": + return origin + ":443"; + default: + return origin; } } @@ -191,10 +191,10 @@ private synchronized void refreshOrigins() { logger.info("Refreshing list of origins..."); Multimap newAllowedOrigins = HashMultimap.create(); - AccountQuery accounts = accountFactory.newQuery(null); + final KapuaQuery accounts = new KapuaQuery((KapuaId) null); AccountListResult accountListResult = KapuaSecurityUtils.doPrivileged(() -> accountService.query(accounts)); accountListResult.getItems().forEach(account -> { - EndpointInfoQuery endpointInfoQuery = endpointInfoFactory.newQuery(account.getId()); + EndpointInfoQuery endpointInfoQuery = new EndpointInfoQuery(account.getId()); try { EndpointInfoListResult endpointInfoListResult = KapuaSecurityUtils.doPrivileged(() -> endpointInfoService.query(endpointInfoQuery, EndpointInfo.ENDPOINT_TYPE_CORS)); endpointInfoListResult.getItems().forEach(endpointInfo -> newAllowedOrigins.put(endpointInfo.toStringURI(), account.getId())); diff --git a/commons-rest/model/pom.xml b/commons-rest/model/pom.xml index 64f4cfbf14a..6405dfb2b50 100644 --- a/commons-rest/model/pom.xml +++ b/commons-rest/model/pom.xml @@ -19,7 +19,7 @@ kapua-commons-rest org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-commons-rest-model diff --git a/commons-rest/pom.xml b/commons-rest/pom.xml index cd3a20cdbf7..32b90b3169f 100644 --- a/commons-rest/pom.xml +++ b/commons-rest/pom.xml @@ -18,7 +18,7 @@ kapua org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-commons-rest diff --git a/commons/pom.xml b/commons/pom.xml index ce7f4dee901..4398e34ddd2 100644 --- a/commons/pom.xml +++ b/commons/pom.xml @@ -19,7 +19,7 @@ org.eclipse.kapua kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-commons diff --git a/commons/src/main/java/org/eclipse/kapua/commons/CommonsModule.java b/commons/src/main/java/org/eclipse/kapua/commons/CommonsModule.java index 215ad405a8f..f5534b0a241 100644 --- a/commons/src/main/java/org/eclipse/kapua/commons/CommonsModule.java +++ b/commons/src/main/java/org/eclipse/kapua/commons/CommonsModule.java @@ -32,7 +32,6 @@ import org.eclipse.kapua.commons.model.domains.Domains; import org.eclipse.kapua.commons.model.mappers.KapuaBaseMapper; import org.eclipse.kapua.commons.model.mappers.KapuaBaseMapperImpl; -import org.eclipse.kapua.commons.model.query.QueryFactoryImpl; import org.eclipse.kapua.commons.service.event.store.api.EventStoreRecordCreator; import org.eclipse.kapua.commons.service.event.store.api.EventStoreRecordRepository; import org.eclipse.kapua.commons.service.event.store.api.EventStoreService; @@ -48,7 +47,6 @@ import org.eclipse.kapua.model.domain.Actions; import org.eclipse.kapua.model.domain.Domain; import org.eclipse.kapua.model.domain.DomainEntry; -import org.eclipse.kapua.model.query.QueryFactory; import com.google.inject.Provides; import com.google.inject.multibindings.Multibinder; @@ -63,7 +61,6 @@ public class CommonsModule extends AbstractKapuaModule { @Override protected void configureModule() { - bind(QueryFactory.class).to(QueryFactoryImpl.class).in(Singleton.class); bind(CryptoSettings.class).toInstance(new CryptoSettings()); bind(CryptoUtil.class).to(CryptoUtilImpl.class).in(Singleton.class); bind(QRCodeBuilder.class).to(QRCodeBuilderImpl.class).in(Singleton.class); diff --git a/commons/src/main/java/org/eclipse/kapua/commons/configuration/AbstractKapuaConfigurableResourceLimitedService.java b/commons/src/main/java/org/eclipse/kapua/commons/configuration/AbstractKapuaConfigurableResourceLimitedService.java index 719a0a0addf..cf195a5fe42 100644 --- a/commons/src/main/java/org/eclipse/kapua/commons/configuration/AbstractKapuaConfigurableResourceLimitedService.java +++ b/commons/src/main/java/org/eclipse/kapua/commons/configuration/AbstractKapuaConfigurableResourceLimitedService.java @@ -12,6 +12,9 @@ *******************************************************************************/ package org.eclipse.kapua.commons.configuration; +import java.util.Map; +import java.util.Optional; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.KapuaMaxNumberOfItemsReachedException; import org.eclipse.kapua.commons.configuration.exception.ServiceConfigurationLimitExceededException; @@ -33,12 +36,8 @@ import org.eclipse.kapua.service.KapuaService; import org.eclipse.kapua.service.account.Account; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; import org.eclipse.kapua.service.config.KapuaConfigurableService; -import java.util.Map; -import java.util.Optional; - /** * Base {@code abstract} {@link KapuaConfigurableService} implementation for services that have a max number of entities allowed. *

@@ -48,28 +47,27 @@ *

  • maxNumberChildEntities
  • * * - * @param The {@link KapuaEntity} type. - * @param The {@link KapuaEntityCreator} type. - * @param The {@link KapuaEntityService} type. - * @param The {@link KapuaListResult} type. - * @param The {@link KapuaQuery} type. - * @param The {@link KapuaEntityFactory} type. + * @param + * The {@link KapuaEntity} type. + * @param + * The {@link KapuaEntityCreator} type. + * @param + * The {@link KapuaEntityService} type. + * @param + * The {@link KapuaEntityFactory} type. * @since 1.0.0 * @deprecated since 2.0.0, in favour of separate configuration component - see {@link ServiceConfigurationManager} and implementations for more details */ @Deprecated public abstract class AbstractKapuaConfigurableResourceLimitedService< E extends KapuaEntity, - C extends KapuaEntityCreator, + C extends KapuaEntityCreator, S extends KapuaEntityService, - L extends KapuaListResult, - Q extends KapuaQuery, - F extends KapuaEntityFactory + F extends KapuaEntityFactory > extends AbstractKapuaConfigurableService implements KapuaEntityService { - //TODO: make final as soon as deprecated constructors are removed private AccountRelativeFinder accountRelativeFinder; private F factory; @@ -79,11 +77,16 @@ public abstract class AbstractKapuaConfigurableResourceLimitedService< /** * Constructor. * - * @param pid The {@link KapuaConfigurableService} id. - * @param domain The {@link Domain} on which check access. - * @param entityManagerFactory The {@link EntityManagerFactory} that handles persistence unit - * @param serviceClass The {@link KapuaService} type. - * @param factoryClass The {@link KapuaEntityFactory} type. + * @param pid + * The {@link KapuaConfigurableService} id.KapuaEntit + * @param domain + * The {@link Domain} on which check access. + * @param entityManagerFactory + * The {@link EntityManagerFactory} that handles persistence unit + * @param serviceClass + * The {@link KapuaService} type. + * @param factoryClass + * The {@link KapuaEntityFactory} type. * @deprecated Since 1.2.0. This constructor will be removed in a next release (may be) */ @Deprecated @@ -104,12 +107,18 @@ protected AbstractKapuaConfigurableResourceLimitedService( /** * Constructor. * - * @param pid The {@link KapuaConfigurableService} id. - * @param domain The {@link Domain} on which check access. - * @param entityManagerFactory The {@link EntityManagerFactory} that handles persistence unit - * @param abstractCacheFactory The {@link CacheFactory} that handles caching of the entities + * @param pid + * The {@link KapuaConfigurableService} id. + * @param domain + * The {@link Domain} on which check access. + * @param entityManagerFactory + * The {@link EntityManagerFactory} that handles persistence unit + * @param abstractCacheFactory + * The {@link CacheFactory} that handles caching of the entities * @since 1.2.0 - * @deprecated Since 2.0.0. Please use {@link #AbstractKapuaConfigurableResourceLimitedService(String, Domain, EntityManagerFactory, EntityCacheFactory, KapuaEntityFactory, PermissionFactory, AuthorizationService, AccountRelativeFinder, RootUserTester)} This constructor may be removed in a next release + * @deprecated Since 2.0.0. Please use + * {@link #AbstractKapuaConfigurableResourceLimitedService(String, Domain, EntityManagerFactory, EntityCacheFactory, KapuaEntityFactory, AuthorizationService, AccountRelativeFinder, + * RootUserTester)} This constructor may be removed in a next release */ @Deprecated protected AbstractKapuaConfigurableResourceLimitedService( @@ -119,7 +128,7 @@ protected AbstractKapuaConfigurableResourceLimitedService( EntityCacheFactory abstractCacheFactory, Class serviceClass, Class factoryClass) { - super(pid, domain, entityManagerFactory, abstractCacheFactory, null, null, null); + super(pid, domain, entityManagerFactory, abstractCacheFactory, null, null); /* These should be provided by the Locator, but in most cases when this class is instantiated through this constructor the Locator is not yet ready, @@ -133,25 +142,30 @@ protected AbstractKapuaConfigurableResourceLimitedService( /** * Constructor. * - * @param pid The {@link KapuaConfigurableService} id. - * @param domain The {@link Domain} on which check access. - * @param entityManagerFactory The {@link EntityManagerFactory} that handles persistence unit - * @param abstractCacheFactory The {@link CacheFactory} that handles caching of the entities - * @param factory The {@link KapuaEntityFactory} instance. - * @param permissionFactory The {@link PermissionFactory} instance. - * @param authorizationService The {@link AuthorizationService} instance. - * @param rootUserTester The {@link RootUserTester} instance. + * @param pid + * The {@link KapuaConfigurableService} id. + * @param domain + * The {@link Domain} on which check access. + * @param entityManagerFactory + * The {@link EntityManagerFactory} that handles persistence unit + * @param abstractCacheFactory + * The {@link CacheFactory} that handles caching of the entities + * @param factory + * The {@link KapuaEntityFactory} instance. + * @param authorizationService + * The {@link AuthorizationService} instance. + * @param rootUserTester + * The {@link RootUserTester} instance. */ protected AbstractKapuaConfigurableResourceLimitedService(String pid, - Domain domain, - EntityManagerFactory entityManagerFactory, - EntityCacheFactory abstractCacheFactory, - F factory, - PermissionFactory permissionFactory, - AuthorizationService authorizationService, - AccountRelativeFinder accountRelativeFinder, - RootUserTester rootUserTester) { - super(pid, domain, entityManagerFactory, abstractCacheFactory, permissionFactory, authorizationService, rootUserTester); + Domain domain, + EntityManagerFactory entityManagerFactory, + EntityCacheFactory abstractCacheFactory, + F factory, + AuthorizationService authorizationService, + AccountRelativeFinder accountRelativeFinder, + RootUserTester rootUserTester) { + super(pid, domain, entityManagerFactory, abstractCacheFactory, authorizationService, rootUserTester); this.factory = factory; this.factoryClass = null; //TODO: not needed for this construction path, remove as soon as the deprecated constructor is removed this.accountRelativeFinder = accountRelativeFinder; @@ -180,8 +194,10 @@ protected boolean validateNewConfigValuesCoherence(KapuaTocd ocd, Map * The exclusion of the scope is required when updating a limit for a target account. * - * @param scopeId The scope {@link KapuaId}. - * @param targetScopeId The excluded scope {@link KapuaId}. + * @param scopeId + * The scope {@link KapuaId}. + * @param targetScopeId + * The excluded scope {@link KapuaId}. * @return The number of entities remaining for the given scope * @throws KapuaException * @since 1.0.0 @@ -220,14 +239,16 @@ private long allowedChildEntities(KapuaId scopeId, KapuaId targetScopeId) throws } /** - * Gets the number of remaining allowed entity for the given scope, according to the given {@link KapuaConfigurableService} - * excluding a specific scope when checking resources available. + * Gets the number of remaining allowed entity for the given scope, according to the given {@link KapuaConfigurableService} excluding a specific scope when checking resources available. *

    * The exclusion of the scope is required when updating a limit for a target account. * - * @param scopeId The scope {@link KapuaId}. - * @param targetScopeId The excluded scope {@link KapuaId}. - * @param configuration The configuration to be checked. If not provided will be read from the current service configuration + * @param scopeId + * The scope {@link KapuaId}. + * @param targetScopeId + * The excluded scope {@link KapuaId}. + * @param configuration + * The configuration to be checked. If not provided will be read from the current service configuration * @return The number of entities remaining for the given scope * @throws KapuaException * @since 1.0.0 @@ -239,7 +260,7 @@ private long allowedChildEntities(KapuaId scopeId, KapuaId targetScopeId, Map { - Q countQuery = getFactory().newQuery(scopeId); + KapuaQuery countQuery = new KapuaQuery(scopeId); // Current used entities long currentUsedEntities = this.count(countQuery); @@ -263,10 +284,9 @@ private long allowedChildEntities(KapuaId scopeId, KapuaId targetScopeId, Map d.getName()).orElse(null), Actions.read, scopeId)); + getAuthorizationService().checkPermission(new Permission(Optional.ofNullable(domain).map(d -> d.getName()).orElse(null), Actions.read, scopeId)); // Get the Tocd // Keep distinct values for service PID, Scope ID and disabled properties included/excluded from AD Triple cacheKey = Triple.of(pid, scopeId, excludeDisabled); @@ -525,9 +521,9 @@ protected Map getConfigValues(KapuaId scopeId, boolean excludeDi // Argument validation ArgumentValidator.notNull(scopeId, "scopeId"); // Check access - getAuthorizationService().checkPermission(getPermissionFactory().newPermission(Optional.ofNullable(domain).map(d -> d.getName()).orElse(null), Actions.read, scopeId)); + getAuthorizationService().checkPermission(new Permission(Optional.ofNullable(domain).map(d -> d.getName()).orElse(null), Actions.read, scopeId)); // Get configuration values - ServiceConfigQueryImpl query = new ServiceConfigQueryImpl(scopeId); + KapuaQuery query = new KapuaQuery(scopeId); query.setPredicate( query.andPredicate( @@ -537,7 +533,7 @@ protected Map getConfigValues(KapuaId scopeId, boolean excludeDi ); ServiceConfigListResult result = entityManagerSession.doAction(EntityManagerContainer.create() - .onResultHandler(em -> ServiceDAO.query(em, ServiceConfig.class, ServiceConfigImpl.class, new ServiceConfigListResultImpl(), query)) + .onResultHandler(em -> ServiceDAO.query(em, ServiceConfig.class, ServiceConfigImpl.class, new ServiceConfigListResult(), query)) .onBeforeHandler(() -> (ServiceConfigListResult) PRIVATE_ENTITY_CACHE.getList(scopeId, pid)) .onAfterHandler(entity -> PRIVATE_ENTITY_CACHE.putList(scopeId, pid, entity))); @@ -579,11 +575,11 @@ public void setConfigValues(KapuaId scopeId, KapuaId parentId, Map d.getName()).orElse(null), Actions.write, scopeId)); + getAuthorizationService().checkPermission(new Permission(Optional.ofNullable(domain).map(d -> d.getName()).orElse(null), Actions.write, scopeId)); validateConfigurations(ocd, values, scopeId, parentId); - ServiceConfigQueryImpl query = new ServiceConfigQueryImpl(scopeId); + KapuaQuery query = new KapuaQuery(scopeId); query.setPredicate( query.andPredicate( query.attributePredicate(ServiceConfigAttributes.SERVICE_ID, pid), @@ -592,7 +588,7 @@ public void setConfigValues(KapuaId scopeId, KapuaId parentId, Mapcreate(). - onResultHandler(em -> ServiceDAO.query(em, ServiceConfig.class, ServiceConfigImpl.class, new ServiceConfigListResultImpl(), query)) + onResultHandler(em -> ServiceDAO.query(em, ServiceConfig.class, ServiceConfigImpl.class, new ServiceConfigListResult(), query)) ); Properties props = toProperties(values); @@ -638,20 +634,6 @@ public String getServicePid() { return pid; } - /** - * PermissionFactory should be provided by the Locator, but in most cases when this class is instantiated through this constructor the Locator is not yet ready, therefore fetching of the required - * instance is demanded to this artificial getter. - * - * @return The instantiated (hopefully) {@link PermissionFactory} instance - */ - //TODO: Remove as soon as deprecated constructors are removed, use field directly instead. - protected PermissionFactory getPermissionFactory() { - if (permissionFactory == null) { - permissionFactory = KapuaLocator.getInstance().getFactory(PermissionFactory.class); - } - return permissionFactory; - } - /** * AuthorizationService should be provided by the Locator, but in most cases when this class is instantiated through the deprecated constructor the Locator is not yet ready, therefore fetching of * the required instance is demanded to this artificial getter. diff --git a/commons/src/main/java/org/eclipse/kapua/commons/configuration/KapuaConfigurableServiceBase.java b/commons/src/main/java/org/eclipse/kapua/commons/configuration/KapuaConfigurableServiceBase.java index be0698d338d..61fb8ea46f0 100644 --- a/commons/src/main/java/org/eclipse/kapua/commons/configuration/KapuaConfigurableServiceBase.java +++ b/commons/src/main/java/org/eclipse/kapua/commons/configuration/KapuaConfigurableServiceBase.java @@ -18,13 +18,12 @@ import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.commons.util.ArgumentValidator; -import org.eclipse.kapua.model.config.metatype.EmptyTocd; import org.eclipse.kapua.model.config.metatype.KapuaTocd; import org.eclipse.kapua.model.domain.Actions; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.KapuaService; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; +import org.eclipse.kapua.service.authorization.permission.Permission; import org.eclipse.kapua.service.config.KapuaConfigurableService; import org.eclipse.kapua.storage.TxManager; @@ -46,19 +45,16 @@ public class KapuaConfigurableServiceBase protected final ServiceConfigurationManager serviceConfigurationManager; private final String domain; protected final AuthorizationService authorizationService; - protected final PermissionFactory permissionFactory; public KapuaConfigurableServiceBase( TxManager txManager, ServiceConfigurationManager serviceConfigurationManager, String authorizationDomain, - AuthorizationService authorizationService, - PermissionFactory permissionFactory) { + AuthorizationService authorizationService) { this.txManager = txManager; this.serviceConfigurationManager = serviceConfigurationManager; this.domain = authorizationDomain; this.authorizationService = authorizationService; - this.permissionFactory = permissionFactory; } @Override @@ -75,9 +71,9 @@ public KapuaTocd getConfigMetadata(KapuaId scopeId) throws KapuaException { ArgumentValidator.notNull(scopeId, "scopeId"); // Check access - if (!authorizationService.isPermitted(permissionFactory.newPermission(domain, Actions.read, scopeId))) { + if (!authorizationService.isPermitted(new Permission(domain, Actions.read, scopeId))) { //Temporary, use Optional instead - return new EmptyTocd(); + return KapuaTocd.empty(); } return serviceConfigurationManager.getConfigMetadata(scopeId, true).orElse(null); } @@ -88,7 +84,7 @@ public Map getConfigValues(KapuaId scopeId) throws KapuaExceptio ArgumentValidator.notNull(scopeId, "scopeId"); // Check access - if (!authorizationService.isPermitted(permissionFactory.newPermission(domain, Actions.read, scopeId))) { + if (!authorizationService.isPermitted(new Permission(domain, Actions.read, scopeId))) { return Collections.emptyMap(); } return serviceConfigurationManager.getConfigValues(scopeId, true); @@ -100,7 +96,7 @@ public void setConfigValues(KapuaId scopeId, KapuaId parentId, Map { +public class ServiceConfigCreator extends KapuaUpdatableEntityCreator { + + private static final long serialVersionUID = 7508550960304732465L; + + @XmlElement(name = "pid") + private String pid; + + @XmlElement(name = "configurations") + private Properties configurations; + + public ServiceConfigCreator() { + } + + public ServiceConfigCreator(KapuaId scopeId) { + super(scopeId); + } + + public ServiceConfigCreator(KapuaEntityCreator entityCreator) { + super(entityCreator); + } /** * Return service pid * * @return */ - public String getPid(); + public String getPid() { + return pid; + } /** * Set service pid * * @param pid */ - public void setPid(String pid); + public void setPid(String pid) { + this.pid = pid; + } /** * Return service configurations * * @return - * @throws KapuaException */ - public Properties getConfigurations() throws KapuaException; + public Properties getConfigurations() { + return this.configurations; + } /** * Set service configurations * * @param configurations - * @throws KapuaException */ - public void setConfigurations(Properties configurations) throws KapuaException; + public void setConfigurations(Properties configurations) { + this.configurations = configurations; + } } diff --git a/commons/src/main/java/org/eclipse/kapua/commons/configuration/ServiceConfigCreatorImpl.java b/commons/src/main/java/org/eclipse/kapua/commons/configuration/ServiceConfigCreatorImpl.java deleted file mode 100644 index 8713525270a..00000000000 --- a/commons/src/main/java/org/eclipse/kapua/commons/configuration/ServiceConfigCreatorImpl.java +++ /dev/null @@ -1,67 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.commons.configuration; - -import java.util.Properties; - -import javax.xml.bind.annotation.XmlElement; - -import org.eclipse.kapua.commons.model.AbstractKapuaUpdatableEntityCreator; -import org.eclipse.kapua.model.id.KapuaId; - -/** - * Service configuration creator reference implementation. - * - * @since 1.0 - * - */ -public class ServiceConfigCreatorImpl extends AbstractKapuaUpdatableEntityCreator - implements ServiceConfigCreator { - - private static final long serialVersionUID = 7508550960304732465L; - - @XmlElement(name = "pid") - private String pid; - - @XmlElement(name = "configurations") - private Properties configurations; - - /** - * Constructor - * - * @param scopeId - */ - protected ServiceConfigCreatorImpl(KapuaId scopeId) { - super(scopeId); - } - - @Override - public String getPid() { - return pid; - } - - @Override - public void setPid(String pid) { - this.pid = pid; - } - - @Override - public Properties getConfigurations() { - return this.configurations; - } - - @Override - public void setConfigurations(Properties configurations) { - this.configurations = configurations; - } -} diff --git a/commons/src/main/java/org/eclipse/kapua/commons/configuration/ServiceConfigImpl.java b/commons/src/main/java/org/eclipse/kapua/commons/configuration/ServiceConfigImpl.java index 7ad7c0b71c7..42ace129aa8 100644 --- a/commons/src/main/java/org/eclipse/kapua/commons/configuration/ServiceConfigImpl.java +++ b/commons/src/main/java/org/eclipse/kapua/commons/configuration/ServiceConfigImpl.java @@ -27,8 +27,8 @@ import javax.xml.bind.annotation.XmlType; import org.eclipse.kapua.KapuaException; +import org.eclipse.kapua.PropertiesUtils; import org.eclipse.kapua.commons.model.AbstractKapuaUpdatableEntity; -import org.eclipse.kapua.commons.util.PropertiesUtils; import org.eclipse.kapua.model.id.KapuaId; @XmlRootElement diff --git a/commons/src/main/java/org/eclipse/kapua/commons/configuration/ServiceConfigImplJpaRepository.java b/commons/src/main/java/org/eclipse/kapua/commons/configuration/ServiceConfigImplJpaRepository.java index 31b63e33cab..d94c39e0e56 100644 --- a/commons/src/main/java/org/eclipse/kapua/commons/configuration/ServiceConfigImplJpaRepository.java +++ b/commons/src/main/java/org/eclipse/kapua/commons/configuration/ServiceConfigImplJpaRepository.java @@ -16,18 +16,19 @@ import org.eclipse.kapua.commons.jpa.KapuaJpaRepositoryConfiguration; import org.eclipse.kapua.commons.jpa.KapuaUpdatableEntityJpaRepository; import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.storage.TxContext; public class ServiceConfigImplJpaRepository extends KapuaUpdatableEntityJpaRepository implements ServiceConfigRepository { public ServiceConfigImplJpaRepository(KapuaJpaRepositoryConfiguration jpaRepoConfig) { - super(ServiceConfigImpl.class, ServiceConfig.TYPE, () -> new ServiceConfigListResultImpl(), jpaRepoConfig); + super(ServiceConfigImpl.class, ServiceConfig.TYPE, () -> new ServiceConfigListResult(), jpaRepoConfig); } @Override public ServiceConfigListResult findByScopeAndPid(TxContext txContext, KapuaId scopeId, String pid) throws KapuaException { - final ServiceConfigQueryImpl query = new ServiceConfigQueryImpl(scopeId); + final KapuaQuery query = new KapuaQuery(scopeId); query.setPredicate( query.andPredicate( diff --git a/commons/src/main/java/org/eclipse/kapua/commons/configuration/ServiceConfigListResult.java b/commons/src/main/java/org/eclipse/kapua/commons/configuration/ServiceConfigListResult.java index 5701270b445..22229c46b19 100644 --- a/commons/src/main/java/org/eclipse/kapua/commons/configuration/ServiceConfigListResult.java +++ b/commons/src/main/java/org/eclipse/kapua/commons/configuration/ServiceConfigListResult.java @@ -18,7 +18,9 @@ * Service configuration result list definition. * * @since 1.0 - * */ -public interface ServiceConfigListResult extends KapuaListResult { +public class ServiceConfigListResult extends KapuaListResult { + + private static final long serialVersionUID = -2550359084026132096L; + } diff --git a/commons/src/main/java/org/eclipse/kapua/commons/configuration/ServiceConfigListResultImpl.java b/commons/src/main/java/org/eclipse/kapua/commons/configuration/ServiceConfigListResultImpl.java deleted file mode 100644 index 79136d21865..00000000000 --- a/commons/src/main/java/org/eclipse/kapua/commons/configuration/ServiceConfigListResultImpl.java +++ /dev/null @@ -1,26 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.commons.configuration; - -import org.eclipse.kapua.commons.model.query.KapuaListResultImpl; - -/** - * Service configuration result list reference implementation. - * - * @since 1.0 - * - */ -public class ServiceConfigListResultImpl extends KapuaListResultImpl implements ServiceConfigListResult { - - private static final long serialVersionUID = -2550359084026132096L; -} diff --git a/commons/src/main/java/org/eclipse/kapua/commons/configuration/ServiceConfigQuery.java b/commons/src/main/java/org/eclipse/kapua/commons/configuration/ServiceConfigQuery.java deleted file mode 100644 index a933f50e6fb..00000000000 --- a/commons/src/main/java/org/eclipse/kapua/commons/configuration/ServiceConfigQuery.java +++ /dev/null @@ -1,24 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.commons.configuration; - -import org.eclipse.kapua.model.query.KapuaQuery; - -/** - * {@link ServiceConfig} {@link KapuaQuery} definition. - * - * @see KapuaQuery - * @since 1.0.0 - */ -public interface ServiceConfigQuery extends KapuaQuery { -} diff --git a/commons/src/main/java/org/eclipse/kapua/commons/configuration/ServiceConfigQueryImpl.java b/commons/src/main/java/org/eclipse/kapua/commons/configuration/ServiceConfigQueryImpl.java deleted file mode 100644 index aff2e0593bd..00000000000 --- a/commons/src/main/java/org/eclipse/kapua/commons/configuration/ServiceConfigQueryImpl.java +++ /dev/null @@ -1,44 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.commons.configuration; - -import org.eclipse.kapua.commons.model.query.AbstractKapuaQuery; -import org.eclipse.kapua.model.id.KapuaId; - -/** - * {@link ServiceConfigQuery} implementation. - * - * @since 1.0.0 - */ -public class ServiceConfigQueryImpl extends AbstractKapuaQuery implements ServiceConfigQuery { - - /** - * Constructor. - * - * @since 1.0.0 - */ - private ServiceConfigQueryImpl() { - super(); - } - - /** - * Constructor. - * - * @param scopeId The {@link #getScopeId()}. - * @since 1.0.0 - */ - public ServiceConfigQueryImpl(KapuaId scopeId) { - this(); - setScopeId(scopeId); - } -} diff --git a/commons/src/main/java/org/eclipse/kapua/commons/configuration/ServiceConfigurationManagerImpl.java b/commons/src/main/java/org/eclipse/kapua/commons/configuration/ServiceConfigurationManagerImpl.java index 7dd2137e2c7..f8e2d439d84 100644 --- a/commons/src/main/java/org/eclipse/kapua/commons/configuration/ServiceConfigurationManagerImpl.java +++ b/commons/src/main/java/org/eclipse/kapua/commons/configuration/ServiceConfigurationManagerImpl.java @@ -36,6 +36,7 @@ import org.eclipse.kapua.model.config.metatype.KapuaTmetadata; import org.eclipse.kapua.model.config.metatype.KapuaTocd; import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.service.config.KapuaConfigurableService; import org.eclipse.kapua.service.config.ServiceComponentConfiguration; import org.eclipse.kapua.storage.TxContext; @@ -160,7 +161,7 @@ public void setConfigValues(KapuaId scopeId, Optional parentId, Map, ServiceConfigurationManager> serviceConfigurationManagersByServiceClass; private final Map serviceConfigurationManagersByServiceClassName; protected final AuthorizationService authorizationService; - protected final PermissionFactory permissionFactory; protected final AccountService accountService; @Inject public ServiceConfigurationsFacadeImpl(Map, ServiceConfigurationManager> serviceConfigurationManagersByServiceClass, AuthorizationService authorizationService, - PermissionFactory permissionFactory, AccountService accountService) { + AccountService accountService) { this.serviceConfigurationManagersByServiceClass = serviceConfigurationManagersByServiceClass; this.serviceConfigurationManagersByServiceClassName = serviceConfigurationManagersByServiceClass.entrySet().stream().collect(Collectors.toMap(kv -> kv.getKey().getName(), kv -> kv.getValue())); this.authorizationService = authorizationService; - this.permissionFactory = permissionFactory; this.accountService = accountService; } @@ -53,7 +51,7 @@ public ServiceConfiguration fetchAllConfigurations(KapuaId scopeId) throws Kapua final ServiceConfiguration res = new ServiceConfiguration(); for (ServiceConfigurationManager configurableService : serviceConfigurationManagersByServiceClass.values()) { - if (!authorizationService.isPermitted(permissionFactory.newPermission(configurableService.getDomain(), Actions.read, scopeId))) { + if (!authorizationService.isPermitted(new Permission(configurableService.getDomain(), Actions.read, scopeId))) { continue; } configurableService.extractServiceComponentConfiguration(scopeId).ifPresent(res.getComponentConfigurations()::add); @@ -67,7 +65,7 @@ public ServiceComponentConfiguration fetchConfiguration(KapuaId scopeId, String if (serviceConfigurationManager == null) { throw new KapuaIllegalArgumentException("service.pid", serviceId); } - authorizationService.checkPermission(permissionFactory.newPermission(serviceConfigurationManager.getDomain(), Actions.read, scopeId)); + authorizationService.checkPermission(new Permission(serviceConfigurationManager.getDomain(), Actions.read, scopeId)); return serviceConfigurationManager.extractServiceComponentConfiguration(scopeId).orElse(null); } @@ -91,7 +89,7 @@ private void doUpdateServiceComponentConfiguration(Account account, KapuaId scop if (serviceConfigurationManager == null) { throw new KapuaIllegalArgumentException("serviceConfiguration.componentConfiguration.id", newServiceComponentConfiguration.getId()); } - if (!authorizationService.isPermitted(permissionFactory.newPermission(serviceConfigurationManager.getDomain(), Actions.write, scopeId))) { + if (!authorizationService.isPermitted(new Permission(serviceConfigurationManager.getDomain(), Actions.write, scopeId))) { //TODO: Or maybe throw? return; } diff --git a/commons/src/main/java/org/eclipse/kapua/commons/configuration/UsedEntitiesCounterImpl.java b/commons/src/main/java/org/eclipse/kapua/commons/configuration/UsedEntitiesCounterImpl.java index 227dccac161..601e4a6ddc0 100644 --- a/commons/src/main/java/org/eclipse/kapua/commons/configuration/UsedEntitiesCounterImpl.java +++ b/commons/src/main/java/org/eclipse/kapua/commons/configuration/UsedEntitiesCounterImpl.java @@ -15,8 +15,6 @@ import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.model.KapuaEntity; -import org.eclipse.kapua.model.KapuaEntityCreator; -import org.eclipse.kapua.model.KapuaEntityFactory; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.model.query.KapuaListResult; import org.eclipse.kapua.model.query.KapuaQuery; @@ -25,24 +23,18 @@ public class UsedEntitiesCounterImpl< E extends KapuaEntity, - C extends KapuaEntityCreator, - L extends KapuaListResult, - Q extends KapuaQuery, - F extends KapuaEntityFactory - > implements UsedEntitiesCounter { + L extends KapuaListResult> implements UsedEntitiesCounter { - private final F factory; private final KapuaEntityRepository entityRepository; - public UsedEntitiesCounterImpl(F factory, - KapuaEntityRepository entityRepository) { - this.factory = factory; + public UsedEntitiesCounterImpl( + KapuaEntityRepository entityRepository) { this.entityRepository = entityRepository; } @Override public long countEntitiesInScope(TxContext tx, KapuaId scopeId) throws KapuaException { - final Q query = factory.newQuery(scopeId); + final KapuaQuery query = new KapuaQuery(scopeId); // Do count return entityRepository.count(tx, query); } diff --git a/commons/src/main/java/org/eclipse/kapua/commons/event/ServiceEventHousekeeper.java b/commons/src/main/java/org/eclipse/kapua/commons/event/ServiceEventHousekeeper.java index b6b6363879e..4ad90d127fc 100644 --- a/commons/src/main/java/org/eclipse/kapua/commons/event/ServiceEventHousekeeper.java +++ b/commons/src/main/java/org/eclipse/kapua/commons/event/ServiceEventHousekeeper.java @@ -12,6 +12,11 @@ *******************************************************************************/ package org.eclipse.kapua.commons.event; +import java.time.Duration; +import java.time.temporal.ChronoUnit; +import java.util.Date; +import java.util.List; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.commons.jpa.EntityManager; import org.eclipse.kapua.commons.jpa.EntityManagerFactory; @@ -22,7 +27,6 @@ import org.eclipse.kapua.commons.service.event.store.api.EventStoreRecordQuery; import org.eclipse.kapua.commons.service.event.store.api.EventStoreService; import org.eclipse.kapua.commons.service.event.store.api.ServiceEventUtil; -import org.eclipse.kapua.commons.service.event.store.internal.EventStoreFactoryImpl; import org.eclipse.kapua.commons.setting.system.SystemSetting; import org.eclipse.kapua.commons.setting.system.SystemSettingKey; import org.eclipse.kapua.commons.util.KapuaDateUtils; @@ -35,11 +39,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.time.Duration; -import java.time.temporal.ChronoUnit; -import java.util.Date; -import java.util.List; - /** * Event bus housekeeper. It is responsible to send unsent messages or send again messages gone in error. * @@ -78,7 +77,8 @@ private enum EventsProcessType { * @param servicesEntryList * @throws KapuaException */ - public ServiceEventHousekeeper(EventStoreService eventStoreService, EntityManagerFactory entityManagerFactory, ServiceEventBus eventbus, List servicesEntryList) throws KapuaException { + public ServiceEventHousekeeper(EventStoreService eventStoreService, EntityManagerFactory entityManagerFactory, ServiceEventBus eventbus, List servicesEntryList) + throws KapuaException { this.eventbus = eventbus; this.servicesEntryList = servicesEntryList; manager = entityManagerFactory.createEntityManager(); @@ -161,7 +161,7 @@ private void findAndSendUnsentEvents(String serviceName, EventsProcessType event } private EventStoreRecordListResult getUnsentEvents(String serviceName, EventsProcessType eventsProcessType) throws KapuaException { - EventStoreRecordQuery query = new EventStoreFactoryImpl().newQuery(null); + EventStoreRecordQuery query = new EventStoreRecordQuery(null); AndPredicate andPredicate = query.andPredicate(); andPredicate.and(query.attributePredicate(EventStoreRecordAttributes.SERVICE_NAME, serviceName)); diff --git a/commons/src/main/java/org/eclipse/kapua/commons/event/ServiceEventModule.java b/commons/src/main/java/org/eclipse/kapua/commons/event/ServiceEventModule.java index d043594a9bf..20e92ae1355 100644 --- a/commons/src/main/java/org/eclipse/kapua/commons/event/ServiceEventModule.java +++ b/commons/src/main/java/org/eclipse/kapua/commons/event/ServiceEventModule.java @@ -12,30 +12,28 @@ *******************************************************************************/ package org.eclipse.kapua.commons.event; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; + import org.apache.commons.lang3.StringUtils; import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.commons.core.ServiceModule; import org.eclipse.kapua.commons.jpa.JpaTxContext; -import org.eclipse.kapua.commons.service.event.store.internal.EventStoreFactoryImpl; import org.eclipse.kapua.commons.service.event.store.internal.EventStoreRecordImplJpaRepository; import org.eclipse.kapua.commons.service.event.store.internal.EventStoreServiceImpl; import org.eclipse.kapua.event.ServiceEventBus; import org.eclipse.kapua.locator.KapuaLocator; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; import org.eclipse.kapua.storage.TxManagerImpl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.TimeUnit; - /** * Base {@link ServiceModule} implementation to be used by the modules that listen for events. * @@ -101,9 +99,8 @@ public void start() throws KapuaException { final KapuaLocator locator = KapuaLocator.getInstance(); houseKeeperJob = new ServiceEventHousekeeper( new EventStoreServiceImpl(locator.getService(AuthorizationService.class), - locator.getFactory(PermissionFactory.class), - new TxManagerImpl(() -> new JpaTxContext(serviceEventModuleConfiguration.getEntityManagerFactory().getJpaEntityManagerFactory()), serviceEventModuleConfiguration.maxInsertAttempts), - new EventStoreFactoryImpl(), + new TxManagerImpl(() -> new JpaTxContext(serviceEventModuleConfiguration.getEntityManagerFactory().getJpaEntityManagerFactory()), + serviceEventModuleConfiguration.maxInsertAttempts), new EventStoreRecordImplJpaRepository(serviceEventModuleConfiguration.getKapuaJpaRepositoryConfiguration()) ), serviceEventModuleConfiguration.getEntityManagerFactory(), diff --git a/commons/src/main/java/org/eclipse/kapua/commons/event/ServiceEventTransactionalHousekeeper.java b/commons/src/main/java/org/eclipse/kapua/commons/event/ServiceEventTransactionalHousekeeper.java index 3895e025656..048b37ea1d4 100644 --- a/commons/src/main/java/org/eclipse/kapua/commons/event/ServiceEventTransactionalHousekeeper.java +++ b/commons/src/main/java/org/eclipse/kapua/commons/event/ServiceEventTransactionalHousekeeper.java @@ -12,6 +12,14 @@ *******************************************************************************/ package org.eclipse.kapua.commons.event; +import java.time.Duration; +import java.time.temporal.ChronoUnit; +import java.util.Date; +import java.util.List; + +import javax.persistence.EntityManager; +import javax.persistence.LockModeType; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.commons.jpa.JpaAwareTxContext; import org.eclipse.kapua.commons.security.KapuaSecurityUtils; @@ -21,7 +29,6 @@ import org.eclipse.kapua.commons.service.event.store.api.EventStoreRecordQuery; import org.eclipse.kapua.commons.service.event.store.api.EventStoreService; import org.eclipse.kapua.commons.service.event.store.api.ServiceEventUtil; -import org.eclipse.kapua.commons.service.event.store.internal.EventStoreFactoryImpl; import org.eclipse.kapua.commons.setting.system.SystemSetting; import org.eclipse.kapua.commons.setting.system.SystemSettingKey; import org.eclipse.kapua.commons.util.KapuaDateUtils; @@ -36,13 +43,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.persistence.EntityManager; -import javax.persistence.LockModeType; -import java.time.Duration; -import java.time.temporal.ChronoUnit; -import java.util.Date; -import java.util.List; - /** * Event bus housekeeper. It is responsible to send unsent messages or send again messages gone in error. * @@ -156,7 +156,7 @@ private void findAndSendUnsentEvents(String serviceName, EventsProcessType event } private EventStoreRecordListResult getUnsentEvents(String serviceName, EventsProcessType eventsProcessType) throws KapuaException { - EventStoreRecordQuery query = new EventStoreFactoryImpl().newQuery(null); + EventStoreRecordQuery query = new EventStoreRecordQuery(null); AndPredicate andPredicate = query.andPredicate(); andPredicate.and(query.attributePredicate(EventStoreRecordAttributes.SERVICE_NAME, serviceName)); diff --git a/commons/src/main/java/org/eclipse/kapua/commons/jpa/JpaTxContext.java b/commons/src/main/java/org/eclipse/kapua/commons/jpa/JpaTxContext.java index 13c5e14b0cc..480f30fb912 100644 --- a/commons/src/main/java/org/eclipse/kapua/commons/jpa/JpaTxContext.java +++ b/commons/src/main/java/org/eclipse/kapua/commons/jpa/JpaTxContext.java @@ -12,13 +12,9 @@ *******************************************************************************/ package org.eclipse.kapua.commons.jpa; -import org.eclipse.kapua.KapuaEntityExistsException; -import org.eclipse.kapua.KapuaException; -import org.eclipse.kapua.commons.util.KapuaExceptionUtils; -import org.eclipse.kapua.storage.TxContext; -import org.eclipse.persistence.exceptions.DatabaseException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import java.io.IOException; +import java.util.Optional; +import java.util.function.Predicate; import javax.persistence.EntityExistsException; import javax.persistence.EntityManager; @@ -27,11 +23,17 @@ import javax.persistence.OptimisticLockException; import javax.persistence.PessimisticLockException; import javax.persistence.RollbackException; -import java.io.IOException; -import java.util.Optional; -import java.util.function.Predicate; + +import org.eclipse.kapua.KapuaEntityExistsException; +import org.eclipse.kapua.KapuaException; +import org.eclipse.kapua.commons.util.KapuaExceptionUtils; +import org.eclipse.kapua.storage.TxContext; +import org.eclipse.persistence.exceptions.DatabaseException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class JpaTxContext implements JpaAwareTxContext, TxContext { + private final Logger logger = LoggerFactory.getLogger(this.getClass()); public final EntityManagerFactory entityManagerFactory; Optional entityManager = Optional.empty(); @@ -97,7 +99,7 @@ public KapuaException convertPersistenceException(Exception ex) { public boolean isRecoverableException(Exception ex) { if (ex instanceof KapuaEntityExistsException || ex instanceof EntityExistsException) { /* - * Most KapuaEntities inherit from AbstractKapuaEntity, which auto-generates ids via a method marked with @PrePersist and the use of + * Most KapuaEntities inherit from KapuaEntityBase, which auto-generates ids via a method marked with @PrePersist and the use of * a org.eclipse.kapua.commons.model.id.IdGenerator. Ids are pseudo-randomic. To deal with potential conflicts, a number of retries * is allowed. The entity needs to be detached in order for the @PrePersist method to be invoked once more, generating a new id * */ diff --git a/commons/src/main/java/org/eclipse/kapua/commons/jpa/KapuaEntityJpaRepository.java b/commons/src/main/java/org/eclipse/kapua/commons/jpa/KapuaEntityJpaRepository.java index 429bef059b9..65fa4a44808 100644 --- a/commons/src/main/java/org/eclipse/kapua/commons/jpa/KapuaEntityJpaRepository.java +++ b/commons/src/main/java/org/eclipse/kapua/commons/jpa/KapuaEntityJpaRepository.java @@ -48,8 +48,6 @@ import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.commons.model.AbstractKapuaEntity_; import org.eclipse.kapua.commons.model.id.KapuaEid; -import org.eclipse.kapua.commons.model.query.predicate.AttributePredicateImpl; -import org.eclipse.kapua.commons.model.query.predicate.OrPredicateImpl; import org.eclipse.kapua.model.KapuaEntity; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.model.query.FieldSortCriteria; @@ -373,9 +371,9 @@ private Predicate handleKapuaQueryPredicates(@NonNull QueryPredicate queryPr predicate = handleOrPredicate(orPredicate, binds, cb, userPermissionRoot, entityType); } else if (queryPredicate instanceof MatchPredicate) { MatchPredicate matchPredicate = (MatchPredicate) queryPredicate; - OrPredicate orPredicate = new OrPredicateImpl(); + OrPredicate orPredicate = new OrPredicate(); for (String attributeName : matchPredicate.getAttributeNames()) { - orPredicate.getPredicates().add(new AttributePredicateImpl<>(attributeName, matchPredicate.getMatchTerm(), AttributePredicate.Operator.STARTS_WITH_IGNORE_CASE)); + orPredicate.getPredicates().add(new AttributePredicate<>(attributeName, matchPredicate.getMatchTerm(), AttributePredicate.Operator.STARTS_WITH_IGNORE_CASE)); } predicate = handleOrPredicate(orPredicate, binds, cb, userPermissionRoot, entityType); } diff --git a/commons/src/main/java/org/eclipse/kapua/commons/model/AbstractKapuaEntityCreator.java b/commons/src/main/java/org/eclipse/kapua/commons/model/AbstractKapuaEntityCreator.java deleted file mode 100644 index 9ce733b593c..00000000000 --- a/commons/src/main/java/org/eclipse/kapua/commons/model/AbstractKapuaEntityCreator.java +++ /dev/null @@ -1,59 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.commons.model; - -import java.io.Serializable; - -import org.eclipse.kapua.model.KapuaEntity; -import org.eclipse.kapua.model.KapuaEntityCreator; -import org.eclipse.kapua.model.id.KapuaId; - -/** - * Kapua entity base creator service (reference abstract implementation). - * - * @param - * entity type - * - * @since 1.0 - * - */ -@SuppressWarnings("serial") -public abstract class AbstractKapuaEntityCreator implements KapuaEntityCreator, Serializable { - - protected KapuaId scopeId; - - /** - * Constructor - * - * @param scopeId - */ - protected AbstractKapuaEntityCreator(KapuaId scopeId) { - super(); - setScopeId(scopeId); - } - - protected AbstractKapuaEntityCreator(AbstractKapuaEntityCreator abstractEntityCreator) { - this(abstractEntityCreator.getScopeId()); - } - - @Override - public KapuaId getScopeId() { - return scopeId; - } - - @Override - public void setScopeId(KapuaId scopeId) { - - this.scopeId = scopeId; - } -} diff --git a/commons/src/main/java/org/eclipse/kapua/commons/model/AbstractKapuaNamedEntityCreator.java b/commons/src/main/java/org/eclipse/kapua/commons/model/AbstractKapuaNamedEntityCreator.java deleted file mode 100644 index 3fe4a69e00c..00000000000 --- a/commons/src/main/java/org/eclipse/kapua/commons/model/AbstractKapuaNamedEntityCreator.java +++ /dev/null @@ -1,66 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.commons.model; - -import org.eclipse.kapua.model.KapuaEntity; -import org.eclipse.kapua.model.KapuaNamedEntityCreator; -import org.eclipse.kapua.model.id.KapuaId; - -/** - * {@link KapuaNamedEntityCreator} {@code abstract} implementation. - * - * @param {@link KapuaEntity} which this {@link AbstractKapuaUpdatableEntityCreator} is for - * @since 1.0.0 - */ -public abstract class AbstractKapuaNamedEntityCreator extends AbstractKapuaUpdatableEntityCreator implements KapuaNamedEntityCreator { - - protected String name; - protected String description; - - /** - * Constructor - * - * @param scopeId the scope {@link KapuaId} - * @param name the name - * @since 1.0.0 - */ - protected AbstractKapuaNamedEntityCreator(KapuaId scopeId, String name) { - super(scopeId); - - setName(name); - } - - public AbstractKapuaNamedEntityCreator(KapuaId scopeId) { - super(scopeId); - } - - @Override - public String getName() { - return name; - } - - @Override - public void setName(String name) { - this.name = name; - } - - @Override - public String getDescription() { - return description; - } - - @Override - public void setDescription(String description) { - this.description = description; - } -} diff --git a/commons/src/main/java/org/eclipse/kapua/commons/model/AbstractKapuaUpdatableEntity.java b/commons/src/main/java/org/eclipse/kapua/commons/model/AbstractKapuaUpdatableEntity.java index fd0febcdf9f..82c8301753a 100644 --- a/commons/src/main/java/org/eclipse/kapua/commons/model/AbstractKapuaUpdatableEntity.java +++ b/commons/src/main/java/org/eclipse/kapua/commons/model/AbstractKapuaUpdatableEntity.java @@ -12,14 +12,9 @@ *******************************************************************************/ package org.eclipse.kapua.commons.model; -import org.eclipse.kapua.commons.model.id.KapuaEid; -import org.eclipse.kapua.commons.security.KapuaSecurityUtils; -import org.eclipse.kapua.commons.util.PropertiesUtils; -import org.eclipse.kapua.entity.EntityPropertiesReadException; -import org.eclipse.kapua.entity.EntityPropertiesWriteException; -import org.eclipse.kapua.model.KapuaEntity; -import org.eclipse.kapua.model.KapuaUpdatableEntity; -import org.eclipse.kapua.model.id.KapuaId; +import java.io.IOException; +import java.util.Date; +import java.util.Properties; import javax.persistence.Access; import javax.persistence.AccessType; @@ -33,9 +28,15 @@ import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Version; -import java.io.IOException; -import java.util.Date; -import java.util.Properties; + +import org.eclipse.kapua.PropertiesUtils; +import org.eclipse.kapua.commons.model.id.KapuaEid; +import org.eclipse.kapua.commons.security.KapuaSecurityUtils; +import org.eclipse.kapua.entity.EntityPropertiesReadException; +import org.eclipse.kapua.entity.EntityPropertiesWriteException; +import org.eclipse.kapua.model.KapuaEntity; +import org.eclipse.kapua.model.KapuaUpdatableEntity; +import org.eclipse.kapua.model.id.KapuaId; /** * {@link KapuaUpdatableEntity} {@code abstract} implementation. @@ -69,8 +70,7 @@ public abstract class AbstractKapuaUpdatableEntity extends AbstractKapuaEntity i protected String properties; /** - * Protected default constructor.
    - * Required by JPA. + * Protected default constructor.
    Required by JPA. * * @since 1.0.0 */ @@ -81,7 +81,8 @@ protected AbstractKapuaUpdatableEntity() { /** * Constructor. * - * @param scopeId The scope {@link KapuaId} to set for this {@link KapuaUpdatableEntity} + * @param scopeId + * The scope {@link KapuaId} to set for this {@link KapuaUpdatableEntity} * @since 1.0.0 */ public AbstractKapuaUpdatableEntity(KapuaId scopeId) { @@ -93,8 +94,10 @@ public AbstractKapuaUpdatableEntity(KapuaId scopeId) { *

    * It can be used to clone the {@link KapuaUpdatableEntity} * - * @throws EntityPropertiesReadException see {@link #getEntityProperties()} and {@link #getEntityAttributes()} - * @throws EntityPropertiesWriteException see {@link #setEntityProperties(Properties)} and {@link #setEntityAttributes(Properties)} + * @throws EntityPropertiesReadException + * see {@link #getEntityProperties()} and {@link #getEntityAttributes()} + * @throws EntityPropertiesWriteException + * see {@link #setEntityProperties(Properties)} and {@link #setEntityAttributes(Properties)} * @since 1.0.0 */ protected AbstractKapuaUpdatableEntity(KapuaUpdatableEntity entity) { @@ -103,8 +106,8 @@ protected AbstractKapuaUpdatableEntity(KapuaUpdatableEntity entity) { setModifiedOn(entity.getModifiedOn()); setModifiedBy(entity.getModifiedBy()); setOptlock(entity.getOptlock()); - setEntityAttributes(entity.getEntityAttributes()); - setEntityProperties(entity.getEntityProperties()); + // setEntityAttributes(entity.getEntityAttributes()); + // setEntityProperties(entity.getEntityProperties()); } @Override @@ -115,7 +118,8 @@ public Date getModifiedOn() { /** * Sets the date of the last update * - * @param modifiedOn The date of the last update + * @param modifiedOn + * The date of the last update * @since 1.0.0 */ public void setModifiedOn(Date modifiedOn) { @@ -130,7 +134,8 @@ public KapuaId getModifiedBy() { /** * Sets the identity {@link KapuaId} who has updated this {@link KapuaEntity} * - * @param modifiedBy The identity {@link KapuaId} who has updated this {@link KapuaEntity} + * @param modifiedBy + * The identity {@link KapuaId} who has updated this {@link KapuaEntity} * @since 1.0.0 */ public void setModifiedBy(KapuaId modifiedBy) { @@ -151,7 +156,7 @@ public void setOptlock(int optlock) { // Attributes APIs // ------------------------------------------------- - @Override + // @Override public Properties getEntityAttributes() { try { return PropertiesUtils.readPropertiesFromString(attributes); @@ -160,7 +165,7 @@ public Properties getEntityAttributes() { } } - @Override + // @Override public void setEntityAttributes(Properties entityAttributes) { try { this.attributes = PropertiesUtils.writePropertiesToString(entityAttributes); @@ -173,7 +178,7 @@ public void setEntityAttributes(Properties entityAttributes) { // Properties APIs // ------------------------------------------------- - @Override + // @Override public Properties getEntityProperties() { try { return PropertiesUtils.readPropertiesFromString(properties); @@ -182,7 +187,7 @@ public Properties getEntityProperties() { } } - @Override + // @Override public void setEntityProperties(Properties properties) { try { this.properties = PropertiesUtils.writePropertiesToString(properties); @@ -192,8 +197,7 @@ public void setEntityProperties(Properties properties) { } /** - * Before create action invokes {@link AbstractKapuaEntity#prePersistsAction()} and - * sets {@link KapuaUpdatableEntity} {@link #modifiedBy} and {@link #modifiedOn}. + * Before create action invokes {@link AbstractKapuaEntity#prePersistsAction()} and sets {@link KapuaUpdatableEntity} {@link #modifiedBy} and {@link #modifiedOn}. * * @since 1.0.0 */ diff --git a/commons/src/main/java/org/eclipse/kapua/commons/model/AbstractKapuaUpdatableEntityCreator.java b/commons/src/main/java/org/eclipse/kapua/commons/model/AbstractKapuaUpdatableEntityCreator.java deleted file mode 100644 index a0f596d3032..00000000000 --- a/commons/src/main/java/org/eclipse/kapua/commons/model/AbstractKapuaUpdatableEntityCreator.java +++ /dev/null @@ -1,62 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2017, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.commons.model; - -import org.eclipse.kapua.commons.util.PropertiesUtils; -import org.eclipse.kapua.entity.EntityPropertiesReadException; -import org.eclipse.kapua.entity.EntityPropertiesWriteException; -import org.eclipse.kapua.model.KapuaEntity; -import org.eclipse.kapua.model.KapuaUpdatableEntityCreator; -import org.eclipse.kapua.model.id.KapuaId; - -import java.io.IOException; -import java.util.Properties; - -/** - * {@link KapuaUpdatableEntityCreator} {@code abstract} implementation. - * - * @param the {@link KapuaEntity} for which this {@link AbstractKapuaEntityCreator} is for. - * @since 1.0.0 - */ -public abstract class AbstractKapuaUpdatableEntityCreator extends AbstractKapuaEntityCreator implements KapuaUpdatableEntityCreator { - - protected String attributes; - - /** - * Constructor. - * - * @param scopeId The scope {@link KapuaId} to set to in the {@link KapuaUpdatableEntityCreator} - * @since 1.0.0 - */ - public AbstractKapuaUpdatableEntityCreator(KapuaId scopeId) { - super(scopeId); - } - - @Override - public Properties getEntityAttributes() { - try { - return PropertiesUtils.readPropertiesFromString(attributes); - } catch (IOException e) { - throw new EntityPropertiesReadException(e, "attributes", attributes); - } - } - - @Override - public void setEntityAttributes(Properties attributes) { - try { - this.attributes = PropertiesUtils.writePropertiesToString(attributes); - } catch (IOException e) { - throw new EntityPropertiesWriteException(e, "attributes", attributes); - } - } -} diff --git a/commons/src/main/java/org/eclipse/kapua/commons/model/mappers/KapuaBaseMapper.java b/commons/src/main/java/org/eclipse/kapua/commons/model/mappers/KapuaBaseMapper.java index f66f1103711..9bfbdb6c6c5 100644 --- a/commons/src/main/java/org/eclipse/kapua/commons/model/mappers/KapuaBaseMapper.java +++ b/commons/src/main/java/org/eclipse/kapua/commons/model/mappers/KapuaBaseMapper.java @@ -41,6 +41,8 @@ public interface KapuaBaseMapper { @Mapping(target = "modifiedOn", ignore = true) @Mapping(target = "modifiedBy", ignore = true) @Mapping(target = "optlock", ignore = true) + @Mapping(target = "entityProperties", ignore = true) + @Mapping(target = "entityAttributes", ignore = true) @IgnoreKapuaEntityReadonlyFields public @interface IgnoreKapuaUpdatableEntityReadonlyFields { diff --git a/commons/src/main/java/org/eclipse/kapua/commons/model/query/AbstractKapuaForwardableEntityQuery.java b/commons/src/main/java/org/eclipse/kapua/commons/model/query/AbstractKapuaForwardableEntityQuery.java deleted file mode 100644 index 40b0954c96c..00000000000 --- a/commons/src/main/java/org/eclipse/kapua/commons/model/query/AbstractKapuaForwardableEntityQuery.java +++ /dev/null @@ -1,61 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2024, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.commons.model.query; - -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.model.query.KapuaForwardableEntityQuery; -import org.eclipse.kapua.model.query.KapuaQuery; - -public class AbstractKapuaForwardableEntityQuery extends AbstractKapuaNamedQuery implements KapuaForwardableEntityQuery { - - protected Boolean includeInherited = Boolean.FALSE; - - /** - * Constructor. - * - */ - public AbstractKapuaForwardableEntityQuery() { - super(); - } - - /** - * Constructor. - * - * @param scopeId The {@link #getScopeId()}. - */ - public AbstractKapuaForwardableEntityQuery(KapuaId scopeId) { - super(scopeId); - } - - /** - * Clone constructor. - * - * @param query The {@link AbstractKapuaForwardableEntityQuery} to clone. - */ - public AbstractKapuaForwardableEntityQuery(KapuaQuery query) { - super(query); - if(query instanceof KapuaForwardableEntityQuery) { - this.includeInherited = ((KapuaForwardableEntityQuery) query).getIncludeInherited(); - } - } - - @Override - public Boolean getIncludeInherited() { - return includeInherited; - } - - @Override - public void setIncludeInherited(Boolean includeInherited) { - this.includeInherited = includeInherited; - } -} diff --git a/commons/src/main/java/org/eclipse/kapua/commons/model/query/AbstractKapuaQuery.java b/commons/src/main/java/org/eclipse/kapua/commons/model/query/AbstractKapuaQuery.java deleted file mode 100644 index bcbb7588a10..00000000000 --- a/commons/src/main/java/org/eclipse/kapua/commons/model/query/AbstractKapuaQuery.java +++ /dev/null @@ -1,206 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.commons.model.query; - -import org.eclipse.kapua.commons.model.id.KapuaEid; -import org.eclipse.kapua.commons.model.query.predicate.AndPredicateImpl; -import org.eclipse.kapua.commons.model.query.predicate.AttributePredicateImpl; -import org.eclipse.kapua.commons.model.query.predicate.OrPredicateImpl; -import org.eclipse.kapua.model.KapuaEntityAttributes; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.model.query.FieldSortCriteria; -import org.eclipse.kapua.model.query.KapuaQuery; -import org.eclipse.kapua.model.query.KapuaSortCriteria; -import org.eclipse.kapua.model.query.SortOrder; -import org.eclipse.kapua.model.query.predicate.AndPredicate; -import org.eclipse.kapua.model.query.predicate.AttributePredicate; -import org.eclipse.kapua.model.query.predicate.OrPredicate; -import org.eclipse.kapua.model.query.predicate.QueryPredicate; - -import javax.validation.constraints.NotNull; -import java.util.ArrayList; -import java.util.List; - -/** - * {@link KapuaQuery} {@code abstract} implementation. - * - * @since 1.0.0 - */ -public abstract class AbstractKapuaQuery implements KapuaQuery { - - private KapuaId scopeId; - - private QueryPredicate predicate; - private KapuaSortCriteria sortCriteria; - private List fetchAttributes; - - private Integer offset; - private Integer limit; - private Boolean askTotalCount; - - /** - * Constructor. - * - * @since 1.0.0 - */ - public AbstractKapuaQuery() { - } - - /** - * Constructor. - * - * @param scopeId The scope {@link KapuaId} of the {@link KapuaQuery} - * @since 1.0.0 - */ - public AbstractKapuaQuery(KapuaId scopeId) { - this(); - - setScopeId(scopeId); - } - - /** - * Constructor. - *

    - * It deeply clones the given {@link KapuaQuery} - * - * @param query the query to clone. - */ - public AbstractKapuaQuery(@NotNull KapuaQuery query) { - setFetchAttributes(query.getFetchAttributes()); - setPredicate(query.getPredicate()); - setLimit(query.getLimit()); - setOffset(query.getOffset()); - setSortCriteria(query.getSortCriteria()); - setAskTotalCount(query.getAskTotalCount()); - } - - @Override - public KapuaId getScopeId() { - return scopeId; - } - - @Override - public void setScopeId(KapuaId scopeId) { - this.scopeId = KapuaEid.parseKapuaId(scopeId); - } - - @Override - public void addFetchAttributes(String fetchAttribute) { - getFetchAttributes().add(fetchAttribute); - } - - @Override - public List getFetchAttributes() { - if (fetchAttributes == null) { - fetchAttributes = new ArrayList<>(); - } - - return fetchAttributes; - } - - @Override - public void setFetchAttributes(List fetchAttributes) { - this.fetchAttributes = fetchAttributes; - } - - @Override - public QueryPredicate getPredicate() { - return this.predicate; - } - - @Override - public void setPredicate(QueryPredicate queryPredicate) { - this.predicate = queryPredicate; - } - - @Override - public KapuaSortCriteria getSortCriteria() { - return sortCriteria; - } - - @Override - public void setSortCriteria(KapuaSortCriteria sortCriteria) { - this.sortCriteria = sortCriteria; - } - - @Override - public KapuaSortCriteria getDefaultSortCriteria() { - return fieldSortCriteria(KapuaEntityAttributes.ENTITY_ID, SortOrder.ASCENDING); - } - - @Override - public Integer getOffset() { - return offset; - } - - @Override - public void setOffset(Integer offset) { - this.offset = offset; - } - - @Override - public Integer getLimit() { - return limit; - } - - @Override - public void setLimit(Integer limit) { - this.limit = limit; - } - - @Override - public Boolean getAskTotalCount() { - return askTotalCount; - } - - @Override - public void setAskTotalCount(Boolean askTotalCount) { - this.askTotalCount = askTotalCount; - } - - // Predicate factory - @Override - public AttributePredicate attributePredicate(String attributeName, T attributeValue) { - return new AttributePredicateImpl<>(attributeName, attributeValue); - } - - @Override - public AttributePredicate attributePredicate(String attributeName, T attributeValue, AttributePredicate.Operator operator) { - return new AttributePredicateImpl<>(attributeName, attributeValue, operator); - } - - @Override - public AndPredicate andPredicate() { - return new AndPredicateImpl(); - } - - @Override - public AndPredicate andPredicate(QueryPredicate... queryPredicates) { - return new AndPredicateImpl(queryPredicates); - } - - @Override - public OrPredicate orPredicate() { - return new OrPredicateImpl(); - } - - @Override - public OrPredicate orPredicate(QueryPredicate... queryPredicates) { - return new OrPredicateImpl(queryPredicates); - } - - @Override - public FieldSortCriteria fieldSortCriteria(String attributeName, SortOrder sortOrder) { - return new FieldSortCriteriaImpl(attributeName, sortOrder); - } -} diff --git a/commons/src/main/java/org/eclipse/kapua/commons/model/query/FieldSortCriteriaImpl.java b/commons/src/main/java/org/eclipse/kapua/commons/model/query/FieldSortCriteriaImpl.java deleted file mode 100644 index b5f08a94f84..00000000000 --- a/commons/src/main/java/org/eclipse/kapua/commons/model/query/FieldSortCriteriaImpl.java +++ /dev/null @@ -1,66 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.commons.model.query; - -import org.eclipse.kapua.model.query.FieldSortCriteria; -import org.eclipse.kapua.model.query.SortOrder; - -/** - * Field sort criteria. - * - * @since 1.0 - * - */ -public class FieldSortCriteriaImpl implements FieldSortCriteria { - - /** - * Field attribute name - */ - private String attributeName; - - /** - * Field sort order - */ - private SortOrder sortOrder; - - /** - * Constructor - * - * @param attributeName - * @param sortOrder - */ - public FieldSortCriteriaImpl(String attributeName, SortOrder sortOrder) { - this.attributeName = attributeName; - this.sortOrder = sortOrder; - } - - /** - * Get the sort attribute name - * - * @return - */ - @Override - public String getAttributeName() { - return attributeName; - } - - /** - * Get the sort attribute order - * - * @return - */ - @Override - public SortOrder getSortOrder() { - return sortOrder; - } -} diff --git a/commons/src/main/java/org/eclipse/kapua/commons/model/query/KapuaListResultImpl.java b/commons/src/main/java/org/eclipse/kapua/commons/model/query/KapuaListResultImpl.java deleted file mode 100644 index 3ff330435d3..00000000000 --- a/commons/src/main/java/org/eclipse/kapua/commons/model/query/KapuaListResultImpl.java +++ /dev/null @@ -1,134 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.commons.model.query; - -import org.eclipse.kapua.model.KapuaEntity; -import org.eclipse.kapua.model.query.KapuaListResult; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Comparator; -import java.util.List; -import java.util.Map; -import java.util.function.Function; -import java.util.function.Predicate; -import java.util.stream.Collectors; - -/** - * {@link KapuaListResult} implementation. - * - * @param {@link KapuaEntity} type. - * @since 1.0.0 - */ -public class KapuaListResultImpl implements KapuaListResult { - - private static final long serialVersionUID = 8939666089540269261L; - - private ArrayList items; - private boolean limitExceeded; - private Long totalCount; - - /** - * Constructor. - * - * @since 1.0.0 - */ - public KapuaListResultImpl() { - limitExceeded = false; - } - - @Override - public boolean isLimitExceeded() { - return limitExceeded; - } - - @Override - public void setLimitExceeded(boolean limitExceeded) { - this.limitExceeded = limitExceeded; - } - - @Override - public List getItems() { - if (items == null) { - items = new ArrayList<>(); - } - - return items; - } - - @Override - public List getItems(Predicate filter) { - return getItems().stream().filter(filter).collect(Collectors.toList()); - } - - @Override - public Map getItemsAsMap(Function keyMapper) { - return getItems().stream().collect(Collectors.toMap(keyMapper, e -> e)); - } - - @Override - public Map getItemsAsMap(Function keyMapper, Function valueMapper) { - return getItems().stream().collect(Collectors.toMap(keyMapper, valueMapper)); - } - - @Override - public E getItem(int index) { - return getItems().get(index); - } - - @Override - public E getFirstItem() { - return this.isEmpty() ? null : getItem(0); - } - - @Override - public int getSize() { - return getItems().size(); - } - - @Override - public boolean isEmpty() { - return getItems().isEmpty(); - } - - @Override - public void addItems(Collection items) { - getItems().addAll(items); - } - - @Override - public void addItem(E item) { - getItems().add(item); - } - - @Override - public void clearItems() { - getItems().clear(); - } - - @Override - public void sort(Comparator comparator) { - getItems().sort(comparator); - } - - @Override - public Long getTotalCount() { - return totalCount; - } - - @Override - public void setTotalCount(Long totalCount) { - this.totalCount = totalCount; - } - -} diff --git a/commons/src/main/java/org/eclipse/kapua/commons/model/query/QueryFactoryImpl.java b/commons/src/main/java/org/eclipse/kapua/commons/model/query/QueryFactoryImpl.java deleted file mode 100644 index ee03bb26e2b..00000000000 --- a/commons/src/main/java/org/eclipse/kapua/commons/model/query/QueryFactoryImpl.java +++ /dev/null @@ -1,33 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.commons.model.query; - -import org.eclipse.kapua.model.query.KapuaQuery; -import org.eclipse.kapua.model.query.QueryFactory; - -import javax.inject.Singleton; - -/** - * {@link QueryFactory} implementation. - * - * @since 2.0.0 - */ -@Singleton -public class QueryFactoryImpl implements QueryFactory { - - @Override - public KapuaQuery newQuery() { - return new AbstractKapuaQuery() { - }; - } -} diff --git a/commons/src/main/java/org/eclipse/kapua/commons/model/query/predicate/AndPredicateImpl.java b/commons/src/main/java/org/eclipse/kapua/commons/model/query/predicate/AndPredicateImpl.java deleted file mode 100644 index a07c30cc5a2..00000000000 --- a/commons/src/main/java/org/eclipse/kapua/commons/model/query/predicate/AndPredicateImpl.java +++ /dev/null @@ -1,73 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.commons.model.query.predicate; - -import com.google.common.collect.Lists; -import org.eclipse.kapua.model.query.predicate.AndPredicate; -import org.eclipse.kapua.model.query.predicate.QueryPredicate; - -import javax.validation.constraints.NotNull; -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; - -/** - * {@link AndPredicate} implementation. - * - * @since 1.0.0 - */ -public class AndPredicateImpl implements AndPredicate { - - private List predicates; - - /** - * Constructor. - * - * @since 1.0.0 - */ - public AndPredicateImpl() { - setPredicates(new ArrayList<>()); - } - - /** - * Constructor which accepts a not null array of {@link QueryPredicate}s. - * - * @param predicates the {@link QueryPredicate}s to add. - * @throws NullPointerException if the given parameter is {@code null}. - * @since 1.0.0 - */ - public AndPredicateImpl(@NotNull QueryPredicate... predicates) { - Objects.requireNonNull(predicates); - - setPredicates(Lists.newArrayList(predicates)); - } - - @Override - public AndPredicateImpl and(@NotNull QueryPredicate predicate) { - Objects.requireNonNull(predicates); - - getPredicates().add(predicate); - - return this; - } - - @Override - public List getPredicates() { - return this.predicates; - } - - @Override - public void setPredicates(List predicates) { - this.predicates = predicates; - } -} diff --git a/commons/src/main/java/org/eclipse/kapua/commons/model/query/predicate/AttributePredicateImpl.java b/commons/src/main/java/org/eclipse/kapua/commons/model/query/predicate/AttributePredicateImpl.java deleted file mode 100644 index bca11012e26..00000000000 --- a/commons/src/main/java/org/eclipse/kapua/commons/model/query/predicate/AttributePredicateImpl.java +++ /dev/null @@ -1,70 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.commons.model.query.predicate; - -import org.eclipse.kapua.model.query.predicate.AttributePredicate; - -/** - * {@link AttributePredicate} implementation. - * - * @since 1.0.0 - */ -public class AttributePredicateImpl implements AttributePredicate { - - private String attributeName; - private T attributeValue; - private Operator operator; - - /** - * Constructor. - *

    - * Defaults ot {@link org.eclipse.kapua.model.query.predicate.AttributePredicate.Operator#EQUAL} - * - * @param attributeName The name of {@link org.eclipse.kapua.model.KapuaEntityAttributes} to set into the {@link AttributePredicate}. - * @param attributeValue The value of {@link org.eclipse.kapua.model.KapuaEntityAttributes} to set into the {@link AttributePredicate}. - * @since 1.0.0 - */ - public AttributePredicateImpl(String attributeName, T attributeValue) { - this(attributeName, attributeValue, Operator.EQUAL); - } - - /** - * Constructor. - * - * @param attributeName The name of {@link org.eclipse.kapua.model.KapuaEntityAttributes} to set into the {@link AttributePredicate}. - * @param attributeValue The value of {@link org.eclipse.kapua.model.KapuaEntityAttributes} to set into the {@link AttributePredicate}. - * @param operator The {@link org.eclipse.kapua.model.query.predicate.AttributePredicate.Operator} to set into the {@link AttributePredicate}. - * @since 1.0.0 - */ - public AttributePredicateImpl(String attributeName, T attributeValue, Operator operator) { - this.attributeName = attributeName; - this.attributeValue = attributeValue; - this.operator = operator; - } - - @Override - public String getAttributeName() { - return attributeName; - } - - @Override - public T getAttributeValue() { - return attributeValue; - } - - @Override - public Operator getOperator() { - return operator; - } - -} diff --git a/commons/src/main/java/org/eclipse/kapua/commons/model/query/predicate/OrPredicateImpl.java b/commons/src/main/java/org/eclipse/kapua/commons/model/query/predicate/OrPredicateImpl.java deleted file mode 100644 index 579e51c40de..00000000000 --- a/commons/src/main/java/org/eclipse/kapua/commons/model/query/predicate/OrPredicateImpl.java +++ /dev/null @@ -1,73 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2018, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.commons.model.query.predicate; - -import com.google.common.collect.Lists; -import org.eclipse.kapua.model.query.predicate.OrPredicate; -import org.eclipse.kapua.model.query.predicate.QueryPredicate; - -import javax.validation.constraints.NotNull; -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; - -/** - * {@link OrPredicate} implementation. - * - * @since 1.0.0 - */ -public class OrPredicateImpl implements OrPredicate { - - private List predicates; - - /** - * Constructor. - * - * @since 1.0.0 - */ - public OrPredicateImpl() { - setPredicates(new ArrayList<>()); - } - - /** - * Constructor which accepts a not {@code null} array of {@link QueryPredicate}s. - * - * @param predicates the {@link QueryPredicate}s to add. - * @throws NullPointerException if the given parameter is {@code null}. - * @since 1.0.0 - */ - public OrPredicateImpl(@NotNull QueryPredicate... predicates) { - Objects.requireNonNull(predicates); - - setPredicates(Lists.newArrayList(predicates)); - } - - @Override - public OrPredicateImpl or(@NotNull QueryPredicate predicate) { - Objects.requireNonNull(predicates); - - getPredicates().add(predicate); - - return this; - } - - @Override - public List getPredicates() { - return this.predicates; - } - - @Override - public void setPredicates(List predicates) { - this.predicates = predicates; - } -} diff --git a/commons/src/main/java/org/eclipse/kapua/commons/service/event/store/api/EventStoreFactory.java b/commons/src/main/java/org/eclipse/kapua/commons/service/event/store/api/EventStoreFactory.java index d26edcfbaca..80843bbbd1b 100644 --- a/commons/src/main/java/org/eclipse/kapua/commons/service/event/store/api/EventStoreFactory.java +++ b/commons/src/main/java/org/eclipse/kapua/commons/service/event/store/api/EventStoreFactory.java @@ -20,6 +20,6 @@ * @see org.eclipse.kapua.model.KapuaEntityFactory * @since 1.0.0 */ -public interface EventStoreFactory extends KapuaEntityFactory { +public interface EventStoreFactory extends KapuaEntityFactory { } diff --git a/commons/src/main/java/org/eclipse/kapua/commons/service/event/store/api/EventStoreRecordCreator.java b/commons/src/main/java/org/eclipse/kapua/commons/service/event/store/api/EventStoreRecordCreator.java index 196599158c4..b78b5766229 100644 --- a/commons/src/main/java/org/eclipse/kapua/commons/service/event/store/api/EventStoreRecordCreator.java +++ b/commons/src/main/java/org/eclipse/kapua/commons/service/event/store/api/EventStoreRecordCreator.java @@ -13,7 +13,20 @@ package org.eclipse.kapua.commons.service.event.store.api; import org.eclipse.kapua.model.KapuaEntityCreator; +import org.eclipse.kapua.model.id.KapuaId; -public interface EventStoreRecordCreator extends KapuaEntityCreator { +public class EventStoreRecordCreator extends KapuaEntityCreator { + private static final long serialVersionUID = 1048699703033893534L; + + public EventStoreRecordCreator() { + } + + public EventStoreRecordCreator(KapuaId scopeId) { + super(scopeId); + } + + public EventStoreRecordCreator(KapuaEntityCreator entityCreator) { + super(entityCreator); + } } diff --git a/commons/src/main/java/org/eclipse/kapua/commons/service/event/store/api/EventStoreRecordListResult.java b/commons/src/main/java/org/eclipse/kapua/commons/service/event/store/api/EventStoreRecordListResult.java index 1ca0de04f84..604c3b771ea 100644 --- a/commons/src/main/java/org/eclipse/kapua/commons/service/event/store/api/EventStoreRecordListResult.java +++ b/commons/src/main/java/org/eclipse/kapua/commons/service/event/store/api/EventStoreRecordListResult.java @@ -23,11 +23,12 @@ * KapuaEvent result list definition. * * @since 1.0 - * */ @XmlRootElement(name = "eventStoreRecords") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = EventStoreXmlRegistry.class,factoryMethod = "newEventStoreRecordListResult") -public interface EventStoreRecordListResult extends KapuaListResult { +@XmlType +public class EventStoreRecordListResult extends KapuaListResult { + + private static final long serialVersionUID = -5118004898345748297L; } diff --git a/commons/src/main/java/org/eclipse/kapua/commons/service/event/store/api/EventStoreRecordQuery.java b/commons/src/main/java/org/eclipse/kapua/commons/service/event/store/api/EventStoreRecordQuery.java index 9f359cf8d18..6f05c3403c3 100644 --- a/commons/src/main/java/org/eclipse/kapua/commons/service/event/store/api/EventStoreRecordQuery.java +++ b/commons/src/main/java/org/eclipse/kapua/commons/service/event/store/api/EventStoreRecordQuery.java @@ -12,13 +12,14 @@ *******************************************************************************/ package org.eclipse.kapua.commons.service.event.store.api; -import org.eclipse.kapua.model.query.KapuaQuery; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; +import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.query.KapuaQuery; + /** * {@link EventStoreRecord} {@link KapuaQuery} definition. * @@ -27,6 +28,27 @@ */ @XmlRootElement(name = "query") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = EventStoreXmlRegistry.class, factoryMethod = "newQuery") -public interface EventStoreRecordQuery extends KapuaQuery { +@XmlType +public class EventStoreRecordQuery extends KapuaQuery { + + /** + * Constructor. + * + * @since 1.0.0 + */ + public EventStoreRecordQuery() { + super(); + } + + /** + * Constructor. + * + * @param scopeId + * The {@link #getScopeId()}. + * @since 1.0.0 + */ + public EventStoreRecordQuery(KapuaId scopeId) { + this(); + setScopeId(scopeId); + } } diff --git a/commons/src/main/java/org/eclipse/kapua/commons/service/event/store/api/EventStoreXmlRegistry.java b/commons/src/main/java/org/eclipse/kapua/commons/service/event/store/api/EventStoreXmlRegistry.java index 39fd356fa6b..4a53749ef2a 100644 --- a/commons/src/main/java/org/eclipse/kapua/commons/service/event/store/api/EventStoreXmlRegistry.java +++ b/commons/src/main/java/org/eclipse/kapua/commons/service/event/store/api/EventStoreXmlRegistry.java @@ -12,10 +12,10 @@ *******************************************************************************/ package org.eclipse.kapua.commons.service.event.store.api; -import org.eclipse.kapua.commons.service.event.store.internal.EventStoreFactoryImpl; - import javax.xml.bind.annotation.XmlRegistry; +import org.eclipse.kapua.commons.service.event.store.internal.EventStoreFactoryImpl; + @XmlRegistry public class EventStoreXmlRegistry { @@ -29,27 +29,4 @@ public class EventStoreXmlRegistry { public EventStoreRecord newEventStoreRecord() { return kapuaEventFactory.newEntity(null); } - - /** - * Creates a new kapuaEvent creator instance - * - * @return - */ - public EventStoreRecordCreator newEventStoreRecordCreator() { - return kapuaEventFactory.newCreator(null); - } - - /** - * Creates a new kapuaEvent list result instance - * - * @return - */ - public EventStoreRecordListResult newEventStoreRecordListResult() { - return kapuaEventFactory.newListResult(); - } - - public EventStoreRecordQuery newQuery() { - return kapuaEventFactory.newQuery(null); - } - } diff --git a/commons/src/main/java/org/eclipse/kapua/commons/service/event/store/internal/EventStoreFactoryImpl.java b/commons/src/main/java/org/eclipse/kapua/commons/service/event/store/internal/EventStoreFactoryImpl.java index e5622dfc59c..53543b4f33d 100644 --- a/commons/src/main/java/org/eclipse/kapua/commons/service/event/store/internal/EventStoreFactoryImpl.java +++ b/commons/src/main/java/org/eclipse/kapua/commons/service/event/store/internal/EventStoreFactoryImpl.java @@ -12,16 +12,13 @@ *******************************************************************************/ package org.eclipse.kapua.commons.service.event.store.internal; +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaEntityCloneException; import org.eclipse.kapua.commons.service.event.store.api.EventStoreFactory; import org.eclipse.kapua.commons.service.event.store.api.EventStoreRecord; -import org.eclipse.kapua.commons.service.event.store.api.EventStoreRecordCreator; -import org.eclipse.kapua.commons.service.event.store.api.EventStoreRecordListResult; -import org.eclipse.kapua.commons.service.event.store.api.EventStoreRecordQuery; import org.eclipse.kapua.model.id.KapuaId; -import javax.inject.Singleton; - /** * {@link EventStoreFactory} implementation * @@ -35,21 +32,6 @@ public EventStoreRecord newEntity(KapuaId scopeId) { return new EventStoreRecordImpl(scopeId); } - @Override - public EventStoreRecordCreator newCreator(KapuaId scopeId) { - return new EventStoreRecordCreatorImpl(scopeId); - } - - @Override - public EventStoreRecordQuery newQuery(KapuaId scopeId) { - return new EventStoreQueryImpl(scopeId); - } - - @Override - public EventStoreRecordListResult newListResult() { - return new EventStoreRecordListResultImpl(); - } - @Override public EventStoreRecord clone(EventStoreRecord eventStoreRecord) { try { diff --git a/commons/src/main/java/org/eclipse/kapua/commons/service/event/store/internal/EventStoreQueryImpl.java b/commons/src/main/java/org/eclipse/kapua/commons/service/event/store/internal/EventStoreQueryImpl.java deleted file mode 100644 index b50c177ccc4..00000000000 --- a/commons/src/main/java/org/eclipse/kapua/commons/service/event/store/internal/EventStoreQueryImpl.java +++ /dev/null @@ -1,45 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2017, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.commons.service.event.store.internal; - -import org.eclipse.kapua.commons.model.query.AbstractKapuaQuery; -import org.eclipse.kapua.commons.service.event.store.api.EventStoreRecordQuery; -import org.eclipse.kapua.model.id.KapuaId; - -/** - * {@link EventStoreRecordQuery} implementation. - * - * @since 1.0.0 - */ -public class EventStoreQueryImpl extends AbstractKapuaQuery implements EventStoreRecordQuery { - - /** - * Constructor. - * - * @since 1.0.0 - */ - public EventStoreQueryImpl() { - super(); - } - - /** - * Constructor. - * - * @param scopeId The {@link #getScopeId()}. - * @since 1.0.0 - */ - public EventStoreQueryImpl(KapuaId scopeId) { - this(); - setScopeId(scopeId); - } -} diff --git a/commons/src/main/java/org/eclipse/kapua/commons/service/event/store/internal/EventStoreRecordCreatorImpl.java b/commons/src/main/java/org/eclipse/kapua/commons/service/event/store/internal/EventStoreRecordCreatorImpl.java deleted file mode 100644 index 63057c711d6..00000000000 --- a/commons/src/main/java/org/eclipse/kapua/commons/service/event/store/internal/EventStoreRecordCreatorImpl.java +++ /dev/null @@ -1,39 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.commons.service.event.store.internal; - -import org.eclipse.kapua.commons.model.AbstractKapuaEntityCreator; -import org.eclipse.kapua.commons.service.event.store.api.EventStoreRecord; -import org.eclipse.kapua.commons.service.event.store.api.EventStoreRecordCreator; -import org.eclipse.kapua.model.id.KapuaId; - -/** - * KapuaEvent creator service implementation. - * - * @since 1.0 - * - */ -public class EventStoreRecordCreatorImpl extends AbstractKapuaEntityCreator implements EventStoreRecordCreator { - - private static final long serialVersionUID = 1048699703033893534L; - - /** - * Constructor - * - * @param scopeId - */ - public EventStoreRecordCreatorImpl(KapuaId scopeId) { - super(scopeId); - } - -} diff --git a/commons/src/main/java/org/eclipse/kapua/commons/service/event/store/internal/EventStoreRecordImplJpaRepository.java b/commons/src/main/java/org/eclipse/kapua/commons/service/event/store/internal/EventStoreRecordImplJpaRepository.java index 10363ed304a..67b965941f6 100644 --- a/commons/src/main/java/org/eclipse/kapua/commons/service/event/store/internal/EventStoreRecordImplJpaRepository.java +++ b/commons/src/main/java/org/eclipse/kapua/commons/service/event/store/internal/EventStoreRecordImplJpaRepository.java @@ -21,9 +21,9 @@ public class EventStoreRecordImplJpaRepository extends KapuaUpdatableEntityJpaRepository implements EventStoreRecordRepository { + public EventStoreRecordImplJpaRepository(KapuaJpaRepositoryConfiguration jpaRepoConfig) { - super(EventStoreRecordImpl.class, EventStoreRecord.TYPE, () -> new EventStoreRecordListResultImpl(), jpaRepoConfig); + super(EventStoreRecordImpl.class, EventStoreRecord.TYPE, () -> new EventStoreRecordListResult(), jpaRepoConfig); } - } diff --git a/commons/src/main/java/org/eclipse/kapua/commons/service/event/store/internal/EventStoreRecordListResultImpl.java b/commons/src/main/java/org/eclipse/kapua/commons/service/event/store/internal/EventStoreRecordListResultImpl.java deleted file mode 100644 index 38ed77fbcc8..00000000000 --- a/commons/src/main/java/org/eclipse/kapua/commons/service/event/store/internal/EventStoreRecordListResultImpl.java +++ /dev/null @@ -1,27 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.commons.service.event.store.internal; - -import org.eclipse.kapua.commons.model.query.KapuaListResultImpl; -import org.eclipse.kapua.commons.service.event.store.api.EventStoreRecord; -import org.eclipse.kapua.commons.service.event.store.api.EventStoreRecordListResult; - -/** - * KapuaEvent list result implementation. - * - * @since 1.0 - */ -public class EventStoreRecordListResultImpl extends KapuaListResultImpl implements EventStoreRecordListResult { - - private static final long serialVersionUID = -5118004898345748297L; -} diff --git a/commons/src/main/java/org/eclipse/kapua/commons/service/event/store/internal/EventStoreServiceImpl.java b/commons/src/main/java/org/eclipse/kapua/commons/service/event/store/internal/EventStoreServiceImpl.java index f4a1fa61807..fe6865cbb1c 100644 --- a/commons/src/main/java/org/eclipse/kapua/commons/service/event/store/internal/EventStoreServiceImpl.java +++ b/commons/src/main/java/org/eclipse/kapua/commons/service/event/store/internal/EventStoreServiceImpl.java @@ -12,9 +12,10 @@ *******************************************************************************/ package org.eclipse.kapua.commons.service.event.store.internal; +import javax.inject.Inject; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.commons.model.domains.Domains; -import org.eclipse.kapua.commons.service.event.store.api.EventStoreFactory; import org.eclipse.kapua.commons.service.event.store.api.EventStoreRecord; import org.eclipse.kapua.commons.service.event.store.api.EventStoreRecordCreator; import org.eclipse.kapua.commons.service.event.store.api.EventStoreRecordListResult; @@ -27,11 +28,9 @@ import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; +import org.eclipse.kapua.service.authorization.permission.Permission; import org.eclipse.kapua.storage.TxManager; -import javax.inject.Inject; - /** * {@link EventStoreService} implementation. * @@ -41,22 +40,16 @@ public class EventStoreServiceImpl implements EventStoreService { private final AuthorizationService authorizationService; - private final PermissionFactory permissionFactory; private final TxManager txManager; - private final EventStoreFactory entityFactory; private final EventStoreRecordRepository repository; @Inject public EventStoreServiceImpl( AuthorizationService authorizationService, - PermissionFactory permissionFactory, TxManager txManager, - EventStoreFactory entityFactory, EventStoreRecordRepository repository) { this.authorizationService = authorizationService; - this.permissionFactory = permissionFactory; this.txManager = txManager; - this.entityFactory = entityFactory; this.repository = repository; } @@ -75,7 +68,7 @@ public EventStoreRecord update(EventStoreRecord kapuaEvent) // Validation of the fields ArgumentValidator.notNull(kapuaEvent.getId(), "kapuaEvent.id"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.EVENT_STORE, Actions.write, kapuaEvent.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.EVENT_STORE, Actions.write, kapuaEvent.getScopeId())); // Do update return txManager.execute(tx -> repository.update(tx, kapuaEvent)); } @@ -89,7 +82,7 @@ public void delete(KapuaId scopeId, KapuaId kapuaEventId) ArgumentValidator.notNull(kapuaEventId, KapuaEntityAttributes.ENTITY_ID); // Check Access Actions action = Actions.write; - authorizationService.checkPermission(permissionFactory.newPermission(Domains.EVENT_STORE, action, scopeId)); + authorizationService.checkPermission(new Permission(Domains.EVENT_STORE, action, scopeId)); // Do delete txManager.execute(tx -> repository.delete(tx, scopeId, kapuaEventId)); } @@ -101,7 +94,7 @@ public EventStoreRecord find(KapuaId scopeId, KapuaId kapuaEventId) ArgumentValidator.notNull(scopeId, KapuaEntityAttributes.SCOPE_ID); ArgumentValidator.notNull(kapuaEventId, KapuaEntityAttributes.ENTITY_ID); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.EVENT_STORE, Actions.read, scopeId)); + authorizationService.checkPermission(new Permission(Domains.EVENT_STORE, Actions.read, scopeId)); // Make sure kapuaEvent exists return txManager.execute(tx -> repository.find(tx, scopeId, kapuaEventId)) .orElse(null); @@ -113,7 +106,7 @@ public EventStoreRecord find(KapuaId kapuaEventId) // Validation of the fields ArgumentValidator.notNull(kapuaEventId, KapuaEntityAttributes.ENTITY_ID); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.EVENT_STORE, Actions.read, kapuaEventId)); + authorizationService.checkPermission(new Permission(Domains.EVENT_STORE, Actions.read, kapuaEventId)); return txManager.execute(tx -> repository.find(tx, KapuaId.ANY, kapuaEventId)) .orElse(null); @@ -124,7 +117,7 @@ public EventStoreRecordListResult query(KapuaQuery query) throws KapuaException { ArgumentValidator.notNull(query, "query"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.EVENT_STORE, Actions.read, query.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.EVENT_STORE, Actions.read, query.getScopeId())); return txManager.execute(tx -> repository.query(tx, query)); } @@ -133,7 +126,7 @@ public long count(KapuaQuery query) throws KapuaException { ArgumentValidator.notNull(query, "query"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.EVENT_STORE, Actions.read, query.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.EVENT_STORE, Actions.read, query.getScopeId())); return txManager.execute(tx -> repository.count(tx, query)); } } diff --git a/commons/src/main/java/org/eclipse/kapua/commons/service/internal/KapuaNamedEntityServiceUtils.java b/commons/src/main/java/org/eclipse/kapua/commons/service/internal/KapuaNamedEntityServiceUtils.java index 47ab5ce0c2a..c0816fad61a 100644 --- a/commons/src/main/java/org/eclipse/kapua/commons/service/internal/KapuaNamedEntityServiceUtils.java +++ b/commons/src/main/java/org/eclipse/kapua/commons/service/internal/KapuaNamedEntityServiceUtils.java @@ -12,6 +12,11 @@ *******************************************************************************/ package org.eclipse.kapua.commons.service.internal; +import java.util.Collections; +import java.util.List; + +import javax.validation.constraints.NotNull; + import org.eclipse.kapua.KapuaDuplicateNameException; import org.eclipse.kapua.KapuaDuplicateNameInAnotherAccountError; import org.eclipse.kapua.KapuaException; @@ -21,16 +26,11 @@ import org.eclipse.kapua.model.KapuaNamedEntityAttributes; import org.eclipse.kapua.model.KapuaNamedEntityCreator; import org.eclipse.kapua.model.query.KapuaQuery; -import org.eclipse.kapua.model.query.QueryFactory; import org.eclipse.kapua.model.query.predicate.AndPredicate; import org.eclipse.kapua.model.query.predicate.AttributePredicate; import org.eclipse.kapua.model.query.predicate.QueryPredicate; import org.eclipse.kapua.service.KapuaEntityService; -import javax.validation.constraints.NotNull; -import java.util.Collections; -import java.util.List; - /** * Util class that offers checks on the {@link KapuaNamedEntity#getName()} uniqueness in different flavors. * @@ -41,7 +41,6 @@ public class KapuaNamedEntityServiceUtils { private static final KapuaLocator LOCATOR = KapuaLocator.getInstance(); - private static final QueryFactory QUERY_FACTORY = LOCATOR.getFactory(QueryFactory.class); /** * Constructor. @@ -56,36 +55,52 @@ private KapuaNamedEntityServiceUtils() { /** * Checks that the given {@link KapuaNamedEntityCreator#getName()} is unique within the {@link KapuaNamedEntityCreator#getScopeId()}. * - * @param kapuaNamedEntityService The {@link KapuaEntityService} to use. Usually it is the same service that is using this utility. - * @param creator The {@link KapuaNamedEntityCreator} to check. - * @param The {@link KapuaNamedEntity} type. - * @param The {@link KapuaNamedEntityCreator} type. - * @throws KapuaDuplicateNameException if the {@link KapuaNamedEntityCreator#getName()} is duplicated within the {@link KapuaNamedEntityCreator#getScopeId()}. - * @throws KapuaException if any other error occurs. + * @param kapuaNamedEntityService + * The {@link KapuaEntityService} to use. Usually it is the same service that is using this utility. + * @param creator + * The {@link KapuaNamedEntityCreator} to check. + * @param + * The {@link KapuaNamedEntity} type. + * @param + * The {@link KapuaNamedEntityCreator} type. + * @throws KapuaDuplicateNameException + * if the {@link KapuaNamedEntityCreator#getName()} is duplicated within the {@link KapuaNamedEntityCreator#getScopeId()}. + * @throws KapuaException + * if any other error occurs. * @since 2.0.0 * @deprecated since 2.0.0 - use {@link org.eclipse.kapua.storage.KapuaNamedEntityRepository} instead */ @Deprecated - public static > void checkEntityNameUniqueness(@NotNull KapuaEntityService kapuaNamedEntityService, @NotNull C creator) throws KapuaException { + public static void checkEntityNameUniqueness(@NotNull KapuaEntityService kapuaNamedEntityService, @NotNull C creator) + throws KapuaException { checkEntityNameUniqueness(kapuaNamedEntityService, creator, Collections.emptyList()); } /** - * Checks that the given {@link KapuaNamedEntityCreator#getName()} is unique within the {@link KapuaNamedEntityCreator#getScopeId()} with additional {@link QueryPredicate}s to customize the check. + * Checks that the given {@link KapuaNamedEntityCreator#getName()} is unique within the {@link KapuaNamedEntityCreator#getScopeId()} with additional {@link QueryPredicate}s to customize the + * check. * - * @param kapuaNamedEntityService The {@link KapuaEntityService} to use. Usually it is the same service that is using this utility. - * @param creator The {@link KapuaNamedEntityCreator} to check. - * @param additionalPredicates The additional {@link QueryPredicate}s to customize the check - * @param The {@link KapuaNamedEntity} type. - * @param The {@link KapuaNamedEntityCreator} type. - * @throws KapuaDuplicateNameException if the {@link KapuaNamedEntityCreator#getName()} is duplicated within the {@link KapuaNamedEntityCreator#getScopeId()}. - * @throws KapuaException if any other error occurs. + * @param kapuaNamedEntityService + * The {@link KapuaEntityService} to use. Usually it is the same service that is using this utility. + * @param creator + * The {@link KapuaNamedEntityCreator} to check. + * @param additionalPredicates + * The additional {@link QueryPredicate}s to customize the check + * @param + * The {@link KapuaNamedEntity} type. + * @param + * The {@link KapuaNamedEntityCreator} type. + * @throws KapuaDuplicateNameException + * if the {@link KapuaNamedEntityCreator#getName()} is duplicated within the {@link KapuaNamedEntityCreator#getScopeId()}. + * @throws KapuaException + * if any other error occurs. * @since 2.0.0 * @deprecated since 2.0.0 - use {@link org.eclipse.kapua.storage.KapuaNamedEntityRepository} instead */ @Deprecated - public static > void checkEntityNameUniqueness(@NotNull KapuaEntityService kapuaNamedEntityService, @NotNull C creator, @NotNull List additionalPredicates) throws KapuaException { - KapuaQuery query = QUERY_FACTORY.newQuery(); + public static void checkEntityNameUniqueness(@NotNull KapuaEntityService kapuaNamedEntityService, @NotNull C creator, + @NotNull List additionalPredicates) throws KapuaException { + KapuaQuery query = new KapuaQuery(); query.setScopeId(creator.getScopeId()); AndPredicate andPredicate = query.andPredicate(); @@ -105,11 +120,16 @@ public static > /** * Checks that the given {@link KapuaNamedEntity#getName()} is unique within the {@link KapuaNamedEntity#getScopeId()}. * - * @param kapuaNamedEntityService The {@link KapuaEntityService} to use. Usually it is the same service that is using this utility. - * @param entity The {@link KapuaNamedEntity} to check. - * @param The {@link KapuaNamedEntity} type. - * @throws KapuaDuplicateNameException if the {@link KapuaNamedEntity#getName()} is duplicated within the {@link KapuaNamedEntity#getScopeId()}. - * @throws KapuaException if any other error occurs. + * @param kapuaNamedEntityService + * The {@link KapuaEntityService} to use. Usually it is the same service that is using this utility. + * @param entity + * The {@link KapuaNamedEntity} to check. + * @param + * The {@link KapuaNamedEntity} type. + * @throws KapuaDuplicateNameException + * if the {@link KapuaNamedEntity#getName()} is duplicated within the {@link KapuaNamedEntity#getScopeId()}. + * @throws KapuaException + * if any other error occurs. * @since 2.0.0 * @deprecated since 2.0.0 - use {@link org.eclipse.kapua.storage.KapuaNamedEntityRepository} instead */ @@ -121,18 +141,25 @@ public static void checkEntityNameUniqueness(@NotNu /** * Checks that the given {@link KapuaNamedEntity#getName()} is unique within the {@link KapuaNamedEntity#getScopeId()} with additional {@link QueryPredicate}s to customize the check. * - * @param kapuaNamedEntityService The {@link KapuaEntityService} to use. Usually it is the same service that is using this utility. - * @param entity The {@link KapuaNamedEntity} to check. - * @param additionalPredicates The additional {@link QueryPredicate}s to customize the check - * @param The {@link KapuaNamedEntity} type. - * @throws KapuaDuplicateNameException if the {@link KapuaNamedEntity#getName()} is duplicated within the {@link KapuaNamedEntity#getScopeId()}. - * @throws KapuaException if any other error occurs. + * @param kapuaNamedEntityService + * The {@link KapuaEntityService} to use. Usually it is the same service that is using this utility. + * @param entity + * The {@link KapuaNamedEntity} to check. + * @param additionalPredicates + * The additional {@link QueryPredicate}s to customize the check + * @param + * The {@link KapuaNamedEntity} type. + * @throws KapuaDuplicateNameException + * if the {@link KapuaNamedEntity#getName()} is duplicated within the {@link KapuaNamedEntity#getScopeId()}. + * @throws KapuaException + * if any other error occurs. * @since 2.0.0 * @deprecated since 2.0.0 - use {@link org.eclipse.kapua.storage.KapuaNamedEntityRepository} instead */ @Deprecated - public static void checkEntityNameUniqueness(@NotNull KapuaEntityService kapuaNamedEntityService, @NotNull E entity, @NotNull List additionalPredicates) throws KapuaException { - KapuaQuery query = QUERY_FACTORY.newQuery(); + public static void checkEntityNameUniqueness(@NotNull KapuaEntityService kapuaNamedEntityService, @NotNull E entity, + @NotNull List additionalPredicates) throws KapuaException { + KapuaQuery query = new KapuaQuery(); query.setScopeId(entity.getScopeId()); AndPredicate andPredicate = query.andPredicate(); @@ -153,18 +180,25 @@ public static void checkEntityNameUniqueness(@NotNu /** * Checks that the given {@link KapuaNamedEntityCreator#getName()} is unique within all the scopes. * - * @param kapuaNamedEntityService The {@link KapuaEntityService} to use. Usually it is the same service that is using this utility. - * @param creator The {@link KapuaNamedEntityCreator} to check. - * @param The {@link KapuaNamedEntity} type. - * @param The {@link KapuaNamedEntityCreator} type. - * @throws KapuaDuplicateNameException if the {@link KapuaNamedEntityCreator#getName()} is duplicated within all the scopes - * @throws KapuaException if any other error occurs. + * @param kapuaNamedEntityService + * The {@link KapuaEntityService} to use. Usually it is the same service that is using this utility. + * @param creator + * The {@link KapuaNamedEntityCreator} to check. + * @param + * The {@link KapuaNamedEntity} type. + * @param + * The {@link KapuaNamedEntityCreator} type. + * @throws KapuaDuplicateNameException + * if the {@link KapuaNamedEntityCreator#getName()} is duplicated within all the scopes + * @throws KapuaException + * if any other error occurs. * @since 2.0.0 * @deprecated since 2.0.0 - use {@link org.eclipse.kapua.storage.KapuaNamedEntityRepository} instead */ @Deprecated - public static > void checkEntityNameUniquenessInAllScopes(@NotNull KapuaEntityService kapuaNamedEntityService, @NotNull C creator) throws KapuaException { - KapuaQuery query = QUERY_FACTORY.newQuery(); + public static void checkEntityNameUniquenessInAllScopes(@NotNull KapuaEntityService kapuaNamedEntityService, + @NotNull C creator) throws KapuaException { + KapuaQuery query = new KapuaQuery(); query.setPredicate(query.attributePredicate(KapuaNamedEntityAttributes.NAME, creator.getName())); if (KapuaSecurityUtils.doPrivileged(() -> kapuaNamedEntityService.count(query) > 0)) { @@ -175,17 +209,22 @@ public static > /** * Checks that the given {@link KapuaNamedEntity#getName()} is unique within all the scopes. * - * @param kapuaNamedEntityService The {@link KapuaEntityService} to use. Usually it is the same service that is using this utility. - * @param entity The {@link KapuaNamedEntity} to check. - * @param The {@link KapuaNamedEntity} type. - * @throws KapuaDuplicateNameException if the {@link KapuaNamedEntity#getName()} is duplicated within all the scopes - * @throws KapuaException if any other error occurs. + * @param kapuaNamedEntityService + * The {@link KapuaEntityService} to use. Usually it is the same service that is using this utility. + * @param entity + * The {@link KapuaNamedEntity} to check. + * @param + * The {@link KapuaNamedEntity} type. + * @throws KapuaDuplicateNameException + * if the {@link KapuaNamedEntity#getName()} is duplicated within all the scopes + * @throws KapuaException + * if any other error occurs. * @since 2.0.0 * @deprecated since 2.0.0 - use {@link org.eclipse.kapua.storage.KapuaNamedEntityRepository} instead */ @Deprecated public static void checkEntityNameUniquenessInAllScopes(@NotNull KapuaEntityService kapuaNamedEntityService, @NotNull E entity) throws KapuaException { - KapuaQuery query = QUERY_FACTORY.newQuery(); + KapuaQuery query = new KapuaQuery(); query.setPredicate( query.andPredicate( query.attributePredicate(KapuaNamedEntityAttributes.NAME, entity.getName()), diff --git a/commons/src/main/java/org/eclipse/kapua/commons/service/internal/ServiceDAO.java b/commons/src/main/java/org/eclipse/kapua/commons/service/internal/ServiceDAO.java index e3febf8c3da..ee179add2f1 100644 --- a/commons/src/main/java/org/eclipse/kapua/commons/service/internal/ServiceDAO.java +++ b/commons/src/main/java/org/eclipse/kapua/commons/service/internal/ServiceDAO.java @@ -12,7 +12,32 @@ *******************************************************************************/ package org.eclipse.kapua.commons.service.internal; -import com.google.common.base.MoreObjects; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.persistence.Embedded; +import javax.persistence.EntityExistsException; +import javax.persistence.NonUniqueResultException; +import javax.persistence.PersistenceException; +import javax.persistence.TypedQuery; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Expression; +import javax.persistence.criteria.JoinType; +import javax.persistence.criteria.Order; +import javax.persistence.criteria.ParameterExpression; +import javax.persistence.criteria.Path; +import javax.persistence.criteria.Predicate; +import javax.persistence.criteria.Root; +import javax.persistence.metamodel.Attribute; +import javax.persistence.metamodel.EntityType; +import javax.validation.constraints.Null; + import org.apache.commons.lang.ArrayUtils; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; @@ -23,8 +48,6 @@ import org.eclipse.kapua.commons.jpa.EntityManager; import org.eclipse.kapua.commons.model.AbstractKapuaUpdatableEntity; import org.eclipse.kapua.commons.model.id.KapuaEid; -import org.eclipse.kapua.commons.model.query.predicate.AttributePredicateImpl; -import org.eclipse.kapua.commons.model.query.predicate.OrPredicateImpl; import org.eclipse.kapua.commons.security.KapuaSecurityUtils; import org.eclipse.kapua.commons.security.KapuaSession; import org.eclipse.kapua.commons.setting.system.SystemSetting; @@ -69,30 +92,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.persistence.Embedded; -import javax.persistence.EntityExistsException; -import javax.persistence.NonUniqueResultException; -import javax.persistence.PersistenceException; -import javax.persistence.TypedQuery; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Expression; -import javax.persistence.criteria.JoinType; -import javax.persistence.criteria.Order; -import javax.persistence.criteria.ParameterExpression; -import javax.persistence.criteria.Path; -import javax.persistence.criteria.Predicate; -import javax.persistence.criteria.Root; -import javax.persistence.metamodel.Attribute; -import javax.persistence.metamodel.EntityType; -import javax.validation.constraints.Null; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import com.google.common.base.MoreObjects; /** * {@link ServiceDAO} utility methods. @@ -169,8 +169,10 @@ protected ServiceDAO() { *

    * This method checks for the constraint violation and, in this case, it throws a specific exception ({@link KapuaEntityExistsException}). * - * @param em The {@link EntityManager} that holds the transaction. - * @param entity The {@link KapuaEntity} to be persisted. + * @param em + * The {@link EntityManager} that holds the transaction. + * @param entity + * The {@link KapuaEntity} to be persisted. * @return The persisted {@link KapuaEntity}. * @since 1.0.0 */ @@ -199,11 +201,15 @@ public static E create(@NonNull EntityManager em, @NonNu /** * Updates the {@link KapuaUpdatableEntity}. * - * @param em The {@link EntityManager} that holds the transaction. - * @param clazz The {@link KapuaUpdatableEntity} class. This must be the implementing {@code class}. - * @param entity The {@link KapuaUpdatableEntity} to be updated. + * @param em + * The {@link EntityManager} that holds the transaction. + * @param clazz + * The {@link KapuaUpdatableEntity} class. This must be the implementing {@code class}. + * @param entity + * The {@link KapuaUpdatableEntity} to be updated. * @return The updated {@link KapuaUpdatableEntity}. - * @throws KapuaEntityNotFoundException If the {@link KapuaEntity} does not exist. + * @throws KapuaEntityNotFoundException + * If the {@link KapuaEntity} does not exist. * @since 1.0.0 */ public static E update(@NonNull EntityManager em, @NonNull Class clazz, @NonNull E entity) throws KapuaEntityNotFoundException { @@ -231,10 +237,14 @@ public static E update(@NonNull EntityManager e /** * Finds a {@link KapuaEntity}. * - * @param em The {@link EntityManager} that holds the transaction. - * @param clazz The {@link KapuaEntity} class. This must be the implementing {@code class}. - * @param scopeId The {@link KapuaEntity#getScopeId()} the entity to be found. - * @param entityId The {@link KapuaEntity#getId()} of the entity to be found. + * @param em + * The {@link EntityManager} that holds the transaction. + * @param clazz + * The {@link KapuaEntity} class. This must be the implementing {@code class}. + * @param scopeId + * The {@link KapuaEntity#getScopeId()} the entity to be found. + * @param entityId + * The {@link KapuaEntity#getId()} of the entity to be found. * @since 1.0.0 */ public static E find(@NonNull EntityManager em, @NonNull Class clazz, @Null KapuaId scopeId, @NonNull KapuaId entityId) { @@ -263,76 +273,96 @@ public static E find(@NonNull EntityManager em, @NonNull /** * Finds a {@link KapuaNamedEntity} by {@link KapuaNamedEntity#getName()}. * - * @param em The {@link EntityManager} that holds the transaction. - * @param clazz The {@link KapuaNamedEntity} class. This must be the implementing {@code class}. - * @param value The value of the {@link KapuaNamedEntity#getName()} to search. + * @param em + * The {@link EntityManager} that holds the transaction. + * @param clazz + * The {@link KapuaNamedEntity} class. This must be the implementing {@code class}. + * @param value + * The value of the {@link KapuaNamedEntity#getName()} to search. * @return The {@link KapuaNamedEntity} found, or {@code null} if not found. - * @throws NonUniqueResultException When more than one result is returned + * @throws NonUniqueResultException + * When more than one result is returned * @since 2.0.0 */ @Nullable public static E findByName(@NonNull EntityManager em, - @NonNull Class clazz, - @NonNull Object value) { + @NonNull Class clazz, + @NonNull Object value) { return findByName(em, clazz, KapuaId.ANY, value); } /** * Finds a {@link KapuaNamedEntity} by {@link KapuaNamedEntity#getName()}. * - * @param em The {@link EntityManager} that holds the transaction. - * @param clazz The {@link KapuaNamedEntity} class. This must be the implementing {@code class}. - * @param scopeId The {@link KapuaNamedEntity#getScopeId()} in which to look for results. - * @param value The value of the field from which to search. + * @param em + * The {@link EntityManager} that holds the transaction. + * @param clazz + * The {@link KapuaNamedEntity} class. This must be the implementing {@code class}. + * @param scopeId + * The {@link KapuaNamedEntity#getScopeId()} in which to look for results. + * @param value + * The value of the field from which to search. * @return The {@link KapuaNamedEntity} found, or {@code null} if not found. - * @throws NonUniqueResultException When more than one result is returned. + * @throws NonUniqueResultException + * When more than one result is returned. * @since 1.0.0 */ @Nullable public static E findByName(@NonNull EntityManager em, - @NonNull Class clazz, - @NonNull KapuaId scopeId, - @NonNull Object value) { + @NonNull Class clazz, + @NonNull KapuaId scopeId, + @NonNull Object value) { return findByField(em, clazz, scopeId, KapuaNamedEntityAttributes.NAME, value); } /** * Find a {@link KapuaEntity} by one of its fields. * - * @param em The {@link EntityManager} that holds the transaction. - * @param clazz The {@link KapuaEntity} class. This must be the implementing {@code class}. - * @param name The {@link KapuaEntity} name of the field from which to search. - * @param value The value of the field from which to search. + * @param em + * The {@link EntityManager} that holds the transaction. + * @param clazz + * The {@link KapuaEntity} class. This must be the implementing {@code class}. + * @param name + * The {@link KapuaEntity} name of the field from which to search. + * @param value + * The value of the field from which to search. * @return The {@link KapuaEntity} found, or {@code null} if not found. - * @throws NonUniqueResultException When more than one result is returned. + * @throws NonUniqueResultException + * When more than one result is returned. * @since 1.0.0 */ @Nullable public static E findByField(@NonNull EntityManager em, - @NonNull Class clazz, - @NonNull String name, - @NonNull Object value) { + @NonNull Class clazz, + @NonNull String name, + @NonNull Object value) { return findByField(em, clazz, KapuaId.ANY, name, value); } /** * Find a {@link KapuaEntity} by one of its fields. * - * @param em The {@link EntityManager} that holds the transaction. - * @param clazz The {@link KapuaEntity} class. This must be the implementing {@code class}. - * @param scopeId The {@link KapuaEntity#getScopeId()} in which to look for results. - * @param name The {@link KapuaEntity} name of the field from which to search. - * @param value The value of the field from which to search. + * @param em + * The {@link EntityManager} that holds the transaction. + * @param clazz + * The {@link KapuaEntity} class. This must be the implementing {@code class}. + * @param scopeId + * The {@link KapuaEntity#getScopeId()} in which to look for results. + * @param name + * The {@link KapuaEntity} name of the field from which to search. + * @param value + * The value of the field from which to search. * @return The {@link KapuaEntity} found, or {@code null} if not found. - * @throws NonUniqueResultException When more than one result is returned. + * @throws NonUniqueResultException + * When more than one result is returned. * @since 1.0.0 */ @Nullable public static E findByField(@NonNull EntityManager em, - @NonNull Class clazz, - @NonNull KapuaId scopeId, - @NonNull String name, - @NonNull Object value) { + @NonNull Class clazz, + @NonNull KapuaId scopeId, + @NonNull String name, + @NonNull Object value) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery criteriaSelectQuery = cb.createQuery(clazz); @@ -371,32 +401,38 @@ public static E findByField(@NonNull EntityManager em, // QUERY! List result = query.getResultList(); switch (result.size()) { - case 0: - return null; - case 1: - return result.get(0); - default: - throw new NonUniqueResultException(String.format("Multiple %s results found for field %s with value %s", clazz.getName(), pName, value.toString())); + case 0: + return null; + case 1: + return result.get(0); + default: + throw new NonUniqueResultException(String.format("Multiple %s results found for field %s with value %s", clazz.getName(), pName, value.toString())); } } /** * Queries the {@link KapuaEntity}es. * - * @param em The {@link EntityManager} that holds the transaction. - * @param interfaceClass {@link KapuaQuery} result entity interface class - * @param implementingClass {@link KapuaQuery} result entity implementation class - * @param resultContainer The {@link KapuaListResult} in which load the result. It must be empty. - * @param kapuaQuery The {@link KapuaQuery} to perform. + * @param em + * The {@link EntityManager} that holds the transaction. + * @param interfaceClass + * {@link KapuaQuery} result entity interface class + * @param implementingClass + * {@link KapuaQuery} result entity implementation class + * @param resultContainer + * The {@link KapuaListResult} in which load the result. It must be empty. + * @param kapuaQuery + * The {@link KapuaQuery} to perform. * @return The reference of the {@code resultContainer} parameter. Results are added to the given {@code resultContainer} parameter. - * @throws KapuaException If filter predicates in the {@link KapuaQuery} are incorrect. See {@link #handleKapuaQueryPredicates(QueryPredicate, Map, CriteriaBuilder, Root, EntityType)}. + * @throws KapuaException + * If filter predicates in the {@link KapuaQuery} are incorrect. See {@link #handleKapuaQueryPredicates(QueryPredicate, Map, CriteriaBuilder, Root, EntityType)}. * @since 1.0.0 */ public static > L query(@NonNull EntityManager em, - @NonNull Class interfaceClass, - @NonNull Class implementingClass, - @NonNull L resultContainer, - @NonNull KapuaQuery kapuaQuery) + @NonNull Class interfaceClass, + @NonNull Class implementingClass, + @NonNull L resultContainer, + @NonNull KapuaQuery kapuaQuery) throws KapuaException { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery criteriaSelectQuery = cb.createQuery(implementingClass); @@ -506,18 +542,23 @@ public static > /** * Counts the {@link KapuaEntity}es. * - * @param em The {@link EntityManager} that holds the transaction. - * @param interfaceClass {@link KapuaQuery} result entity interface class - * @param implementingClass {@link KapuaQuery} result entity implementation class - * @param kapuaQuery The {@link KapuaQuery} to perform. + * @param em + * The {@link EntityManager} that holds the transaction. + * @param interfaceClass + * {@link KapuaQuery} result entity interface class + * @param implementingClass + * {@link KapuaQuery} result entity implementation class + * @param kapuaQuery + * The {@link KapuaQuery} to perform. * @return The number of {@link KapuaEntity}es that matched the filter predicates. - * @throws KapuaException If filter predicates in the {@link KapuaQuery} are incorrect. See {@link #handleKapuaQueryPredicates(QueryPredicate, Map, CriteriaBuilder, Root, EntityType)}. + * @throws KapuaException + * If filter predicates in the {@link KapuaQuery} are incorrect. See {@link #handleKapuaQueryPredicates(QueryPredicate, Map, CriteriaBuilder, Root, EntityType)}. * @since 1.0.0 */ public static long count(@NonNull EntityManager em, - @NonNull Class interfaceClass, - @NonNull Class implementingClass, - @NonNull KapuaQuery kapuaQuery) + @NonNull Class interfaceClass, + @NonNull Class implementingClass, + @NonNull KapuaQuery kapuaQuery) throws KapuaException { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery criteriaSelectQuery = cb.createQuery(Long.class); @@ -573,12 +614,17 @@ public static long count(@NonNull EntityMan /** * Deletes a {@link KapuaEntity}. * - * @param em The {@link EntityManager} that holds the transaction. - * @param clazz The {@link KapuaEntity} class. This must be the implementing {@code class}. - * @param scopeId The {@link KapuaEntity#getScopeId()} of the entity to be deleted. - * @param entityId The {@link KapuaEntity#getId()} of the entity to be deleted. + * @param em + * The {@link EntityManager} that holds the transaction. + * @param clazz + * The {@link KapuaEntity} class. This must be the implementing {@code class}. + * @param scopeId + * The {@link KapuaEntity#getScopeId()} of the entity to be deleted. + * @param entityId + * The {@link KapuaEntity#getId()} of the entity to be deleted. * @return The deleted {@link KapuaEntity}. - * @throws KapuaEntityNotFoundException If the {@link KapuaEntity} does not exists. + * @throws KapuaEntityNotFoundException + * If the {@link KapuaEntity} does not exists. * @since 1.0.0 */ public static E delete(@NonNull EntityManager em, @NonNull Class clazz, @NonNull KapuaId scopeId, @NonNull KapuaId entityId) @@ -617,19 +663,25 @@ public static E delete(@NonNull EntityManager em, @NonNu *

    * It can be invoked recursively (i.e. to handle {@link AttributePredicate}s of the {@link AndPredicate}. * - * @param queryPredicate The {@link QueryPredicate} to handle. - * @param binds The {@link Map}≶{@link String}, {@link Object}> of the query values. - * @param cb The JPA {@link CriteriaBuilder} of the {@link javax.persistence.Query}. - * @param userPermissionRoot The JPA {@link Root} of the {@link javax.persistence.Query}. - * @param entityType The JPA {@link EntityType} of the {@link javax.persistence.Query}. + * @param queryPredicate + * The {@link QueryPredicate} to handle. + * @param binds + * The {@link Map}≶{@link String}, {@link Object}> of the query values. + * @param cb + * The JPA {@link CriteriaBuilder} of the {@link javax.persistence.Query}. + * @param userPermissionRoot + * The JPA {@link Root} of the {@link javax.persistence.Query}. + * @param entityType + * The JPA {@link EntityType} of the {@link javax.persistence.Query}. * @return The handled {@link Predicate} - * @throws KapuaException If any problem occurs. + * @throws KapuaException + * If any problem occurs. */ private static Predicate handleKapuaQueryPredicates(@NonNull QueryPredicate queryPredicate, - @NonNull Map binds, - @NonNull CriteriaBuilder cb, - @NonNull Root userPermissionRoot, - @NonNull EntityType entityType) + @NonNull Map binds, + @NonNull CriteriaBuilder cb, + @NonNull Root userPermissionRoot, + @NonNull EntityType entityType) throws KapuaException { Predicate predicate = null; if (queryPredicate instanceof AttributePredicate) { @@ -643,9 +695,9 @@ private static Predicate handleKapuaQueryPredicates(@NonNull QueryPredicate predicate = handleOrPredicate(orPredicate, binds, cb, userPermissionRoot, entityType); } else if (queryPredicate instanceof MatchPredicate) { MatchPredicate matchPredicate = (MatchPredicate) queryPredicate; - OrPredicate orPredicate = new OrPredicateImpl(); + OrPredicate orPredicate = new OrPredicate(); for (String attributeName : matchPredicate.getAttributeNames()) { - orPredicate.getPredicates().add(new AttributePredicateImpl<>(attributeName, matchPredicate.getMatchTerm(), Operator.STARTS_WITH_IGNORE_CASE)); + orPredicate.getPredicates().add(new AttributePredicate<>(attributeName, matchPredicate.getMatchTerm(), Operator.STARTS_WITH_IGNORE_CASE)); } predicate = handleOrPredicate(orPredicate, binds, cb, userPermissionRoot, entityType); } @@ -653,10 +705,10 @@ private static Predicate handleKapuaQueryPredicates(@NonNull QueryPredicate } private static Predicate handleAndPredicate(@NonNull AndPredicate andPredicate, - @NonNull Map binds, - @NonNull CriteriaBuilder cb, - @NonNull Root entityRoot, - @NonNull EntityType entityType) + @NonNull Map binds, + @NonNull CriteriaBuilder cb, + @NonNull Root entityRoot, + @NonNull EntityType entityType) throws KapuaException { Predicate[] jpaAndPredicates = @@ -672,10 +724,10 @@ private static Predicate handleAndPredicate(@NonNull AndPredicate andPredica } private static Predicate handleOrPredicate(@NonNull OrPredicate orPredicate, - @NonNull Map binds, - @NonNull CriteriaBuilder cb, - @NonNull Root entityRoot, - @NonNull EntityType entityType) + @NonNull Map binds, + @NonNull CriteriaBuilder cb, + @NonNull Root entityRoot, + @NonNull EntityType entityType) throws KapuaException { Predicate[] jpaOrPredicates = @@ -690,10 +742,10 @@ private static Predicate handleOrPredicate(@NonNull OrPredicate orPredicate, } private static Predicate[] handlePredicate(@NonNull List orPredicates, - @NonNull Map binds, - @NonNull CriteriaBuilder cb, - @NonNull Root entityRoot, - @NonNull EntityType entityType) throws KapuaException { + @NonNull Map binds, + @NonNull CriteriaBuilder cb, + @NonNull Root entityRoot, + @NonNull EntityType entityType) throws KapuaException { Predicate[] jpaOrPredicates = new Predicate[orPredicates.size()]; for (int i = 0; i < orPredicates.size(); i++) { @@ -704,10 +756,10 @@ private static Predicate[] handlePredicate(@NonNull List orP } private static Predicate handleAttributePredicate(@NonNull AttributePredicate attrPred, - @NonNull Map binds, - @NonNull CriteriaBuilder cb, - @NonNull Root entityRoot, - @NonNull EntityType entityType) + @NonNull Map binds, + @NonNull CriteriaBuilder cb, + @NonNull Root entityRoot, + @NonNull EntityType entityType) throws KapuaException { Predicate expr; String attrName = attrPred.getAttributeName(); @@ -753,88 +805,88 @@ private static Predicate handleAttributePredicate(@NonNull AttributePredicat } else { String strAttrValue; switch (attrPred.getOperator()) { - case LIKE: - strAttrValue = attributeValue.toString().replace(LIKE, ESCAPE + LIKE).replace(ANY, ESCAPE + ANY); - ParameterExpression pl = cb.parameter(String.class); - binds.put(pl, LIKE + strAttrValue + LIKE); - expr = cb.like(extractAttribute(entityRoot, attrName), pl); - break; - - case LIKE_IGNORE_CASE: - strAttrValue = attributeValue.toString().replace(LIKE, ESCAPE + LIKE).replace(ANY, ESCAPE + ANY).toLowerCase(); - ParameterExpression plci = cb.parameter(String.class); - binds.put(plci, LIKE + strAttrValue + LIKE); - expr = cb.like(cb.lower(extractAttribute(entityRoot, attrName)), plci); - break; - - case STARTS_WITH: - strAttrValue = attributeValue.toString().replace(LIKE, ESCAPE + LIKE).replace(ANY, ESCAPE + ANY); - ParameterExpression psw = cb.parameter(String.class); - binds.put(psw, strAttrValue + LIKE); - expr = cb.like(extractAttribute(entityRoot, attrName), psw); - break; - - case STARTS_WITH_IGNORE_CASE: - strAttrValue = attributeValue.toString().replace(LIKE, ESCAPE + LIKE).replace(ANY, ESCAPE + ANY).toLowerCase(); - ParameterExpression pswci = cb.parameter(String.class); - binds.put(pswci, strAttrValue + LIKE); - expr = cb.like(cb.lower(extractAttribute(entityRoot, attrName)), pswci); - break; - - case IS_NULL: - expr = cb.isNull(extractAttribute(entityRoot, attrName)); - break; - - case NOT_NULL: - expr = cb.isNotNull(extractAttribute(entityRoot, attrName)); - break; - - case NOT_EQUAL: - expr = cb.notEqual(extractAttribute(entityRoot, attrName), attributeValue); - break; - - case GREATER_THAN: - if (attributeValue instanceof Comparable && ArrayUtils.contains(attribute.getJavaType().getInterfaces(), Comparable.class)) { - Comparable comparableAttrValue = (Comparable) attributeValue; - Expression comparableExpression = extractAttribute(entityRoot, attrName); - expr = cb.greaterThan(comparableExpression, comparableAttrValue); - } else { - throw new KapuaException(KapuaErrorCodes.ILLEGAL_ARGUMENT, COMPARE_ERROR_MESSAGE); - } - break; - - case GREATER_THAN_OR_EQUAL: - if (attributeValue instanceof Comparable && ArrayUtils.contains(attribute.getJavaType().getInterfaces(), Comparable.class)) { - Expression comparableExpression = extractAttribute(entityRoot, attrName); - Comparable comparableAttrValue = (Comparable) attributeValue; - expr = cb.greaterThanOrEqualTo(comparableExpression, comparableAttrValue); - } else { - throw new KapuaException(KapuaErrorCodes.ILLEGAL_ARGUMENT, COMPARE_ERROR_MESSAGE); - } - break; - - case LESS_THAN: - if (attributeValue instanceof Comparable && ArrayUtils.contains(attribute.getJavaType().getInterfaces(), Comparable.class)) { - Expression comparableExpression = extractAttribute(entityRoot, attrName); - Comparable comparableAttrValue = (Comparable) attributeValue; - expr = cb.lessThan(comparableExpression, comparableAttrValue); - } else { - throw new KapuaException(KapuaErrorCodes.ILLEGAL_ARGUMENT, COMPARE_ERROR_MESSAGE); - } - break; - case LESS_THAN_OR_EQUAL: - if (attributeValue instanceof Comparable && ArrayUtils.contains(attribute.getJavaType().getInterfaces(), Comparable.class)) { - Expression comparableExpression = extractAttribute(entityRoot, attrName); - Comparable comparableAttrValue = (Comparable) attributeValue; - expr = cb.lessThanOrEqualTo(comparableExpression, comparableAttrValue); - } else { - throw new KapuaException(KapuaErrorCodes.ILLEGAL_ARGUMENT, COMPARE_ERROR_MESSAGE); - } - break; + case LIKE: + strAttrValue = attributeValue.toString().replace(LIKE, ESCAPE + LIKE).replace(ANY, ESCAPE + ANY); + ParameterExpression pl = cb.parameter(String.class); + binds.put(pl, LIKE + strAttrValue + LIKE); + expr = cb.like(extractAttribute(entityRoot, attrName), pl); + break; + + case LIKE_IGNORE_CASE: + strAttrValue = attributeValue.toString().replace(LIKE, ESCAPE + LIKE).replace(ANY, ESCAPE + ANY).toLowerCase(); + ParameterExpression plci = cb.parameter(String.class); + binds.put(plci, LIKE + strAttrValue + LIKE); + expr = cb.like(cb.lower(extractAttribute(entityRoot, attrName)), plci); + break; + + case STARTS_WITH: + strAttrValue = attributeValue.toString().replace(LIKE, ESCAPE + LIKE).replace(ANY, ESCAPE + ANY); + ParameterExpression psw = cb.parameter(String.class); + binds.put(psw, strAttrValue + LIKE); + expr = cb.like(extractAttribute(entityRoot, attrName), psw); + break; + + case STARTS_WITH_IGNORE_CASE: + strAttrValue = attributeValue.toString().replace(LIKE, ESCAPE + LIKE).replace(ANY, ESCAPE + ANY).toLowerCase(); + ParameterExpression pswci = cb.parameter(String.class); + binds.put(pswci, strAttrValue + LIKE); + expr = cb.like(cb.lower(extractAttribute(entityRoot, attrName)), pswci); + break; + + case IS_NULL: + expr = cb.isNull(extractAttribute(entityRoot, attrName)); + break; + + case NOT_NULL: + expr = cb.isNotNull(extractAttribute(entityRoot, attrName)); + break; + + case NOT_EQUAL: + expr = cb.notEqual(extractAttribute(entityRoot, attrName), attributeValue); + break; + + case GREATER_THAN: + if (attributeValue instanceof Comparable && ArrayUtils.contains(attribute.getJavaType().getInterfaces(), Comparable.class)) { + Comparable comparableAttrValue = (Comparable) attributeValue; + Expression comparableExpression = extractAttribute(entityRoot, attrName); + expr = cb.greaterThan(comparableExpression, comparableAttrValue); + } else { + throw new KapuaException(KapuaErrorCodes.ILLEGAL_ARGUMENT, COMPARE_ERROR_MESSAGE); + } + break; + + case GREATER_THAN_OR_EQUAL: + if (attributeValue instanceof Comparable && ArrayUtils.contains(attribute.getJavaType().getInterfaces(), Comparable.class)) { + Expression comparableExpression = extractAttribute(entityRoot, attrName); + Comparable comparableAttrValue = (Comparable) attributeValue; + expr = cb.greaterThanOrEqualTo(comparableExpression, comparableAttrValue); + } else { + throw new KapuaException(KapuaErrorCodes.ILLEGAL_ARGUMENT, COMPARE_ERROR_MESSAGE); + } + break; + + case LESS_THAN: + if (attributeValue instanceof Comparable && ArrayUtils.contains(attribute.getJavaType().getInterfaces(), Comparable.class)) { + Expression comparableExpression = extractAttribute(entityRoot, attrName); + Comparable comparableAttrValue = (Comparable) attributeValue; + expr = cb.lessThan(comparableExpression, comparableAttrValue); + } else { + throw new KapuaException(KapuaErrorCodes.ILLEGAL_ARGUMENT, COMPARE_ERROR_MESSAGE); + } + break; + case LESS_THAN_OR_EQUAL: + if (attributeValue instanceof Comparable && ArrayUtils.contains(attribute.getJavaType().getInterfaces(), Comparable.class)) { + Expression comparableExpression = extractAttribute(entityRoot, attrName); + Comparable comparableAttrValue = (Comparable) attributeValue; + expr = cb.lessThanOrEqualTo(comparableExpression, comparableAttrValue); + } else { + throw new KapuaException(KapuaErrorCodes.ILLEGAL_ARGUMENT, COMPARE_ERROR_MESSAGE); + } + break; - case EQUAL: - default: - expr = cb.equal(extractAttribute(entityRoot, attrName), attributeValue); + case EQUAL: + default: + expr = cb.equal(extractAttribute(entityRoot, attrName), attributeValue); } } return expr; @@ -847,8 +899,10 @@ private static Predicate handleAttributePredicate(@NonNull AttributePredicat *

    * Filter predicates takes advantage of the dot notation to access {@link Embedded} attributes and nested {@link KapuaEntity}es. * - * @param entityRoot The {@link Root} entity from which extract the attribute. - * @param attributeName The full attribute name. + * @param entityRoot + * The {@link Root} entity from which extract the attribute. + * @param attributeName + * The full attribute name. * @return The {@link Path} expression that matches the given {@code attributeName} parameter. * @since 1.0.0 */ @@ -870,9 +924,12 @@ private static Path

    extractAttribute(@NonNull Root entityRoot, @Non /** * Handles the {@link Groupable} property of the {@link KapuaEntity}. * - * @param query The {@link KapuaQuery} to manage. - * @param domain The {@link Domain} inside which the {@link KapuaQuery} param targets. - * @param groupPredicateName The name of the {@link Group} id field. + * @param query + * The {@link KapuaQuery} to manage. + * @param domain + * The {@link Domain} inside which the {@link KapuaQuery} param targets. + * @param groupPredicateName + * The name of the {@link Group} id field. * @since 1.0.0 */ protected static void handleKapuaQueryGroupPredicate(@NonNull KapuaQuery query, @NonNull Domain domain, @NonNull String groupPredicateName) throws KapuaException { @@ -971,7 +1028,8 @@ private static boolean checkGroupPermission(@NonNull Domain domain, @NonNull Lis /** * Check if the given {@link PersistenceException} is a SQL constraint violation error. * - * @param persistenceException {@link PersistenceException} to check. + * @param persistenceException + * {@link PersistenceException} to check. * @return {@code true} if it is a constraint validation error, {@code false} otherwise. * @since 1.0.0 */ diff --git a/commons/src/main/java/org/eclipse/kapua/commons/service/internal/cache/EntityCache.java b/commons/src/main/java/org/eclipse/kapua/commons/service/internal/cache/EntityCache.java index f17db8d4930..481a90e69d7 100644 --- a/commons/src/main/java/org/eclipse/kapua/commons/service/internal/cache/EntityCache.java +++ b/commons/src/main/java/org/eclipse/kapua/commons/service/internal/cache/EntityCache.java @@ -12,6 +12,10 @@ *******************************************************************************/ package org.eclipse.kapua.commons.service.internal.cache; +import java.io.Serializable; + +import javax.cache.Cache; + import org.eclipse.kapua.commons.metric.CommonsMetric; import org.eclipse.kapua.model.KapuaEntity; import org.eclipse.kapua.model.id.KapuaId; @@ -19,12 +23,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.cache.Cache; -import java.io.Serializable; - /** - * The basic cache class, it contains two {@link Cache} objects. - * The {@code idCache} cache contains {@link KapuaEntity} objects, while the {@code listsCache} contains {@link KapuaListResult} objects. + * The basic cache class, it contains two {@link Cache} objects. The {@code idCache} cache contains {@link KapuaEntity} objects, while the {@code listsCache} contains {@link KapuaListResult} objects. */ public class EntityCache { @@ -134,11 +134,13 @@ public KapuaListResult removeList(KapuaId scopeId, Serializable id) { } /** - * Checks that the scopeId of the entity matches the provided one. - * This mimics the checks that are performed in the 'find' method of the {@link org.eclipse.kapua.commons.jpa.KapuaEntityJpaRepository} class. + * Checks that the scopeId of the entity matches the provided one. This mimics the checks that are performed in the 'find' method of the + * {@link org.eclipse.kapua.commons.jpa.KapuaEntityJpaRepository} class. * - * @param scopeId a {@link KapuaId} representing the scopeId - * @param entity the {@link KapuaEntity} to be checked + * @param scopeId + * a {@link KapuaId} representing the scopeId + * @param entity + * the {@link KapuaEntity} to be checked * @return the provided entity if it has the required scopeId, null otherwise */ protected KapuaEntity checkResult(KapuaId scopeId, KapuaEntity entity) { @@ -158,14 +160,16 @@ protected KapuaEntity checkResult(KapuaId scopeId, KapuaEntity entity) { } /** - * Checks that the scopeId of the entity matches the provided one. - * This mimics the checks that are performed in the 'find' method of the {@link org.eclipse.kapua.commons.jpa.KapuaEntityJpaRepository} class. + * Checks that the scopeId of the entity matches the provided one. This mimics the checks that are performed in the 'find' method of the + * {@link org.eclipse.kapua.commons.jpa.KapuaEntityJpaRepository} class. * - * @param scopeId a {@link KapuaId} representing the scopeId - * @param entity the {@link KapuaListResult} entity to be checked + * @param scopeId + * a {@link KapuaId} representing the scopeId + * @param entity + * the {@link KapuaListResult} entity to be checked * @return the provided entity if it has the required scopeId, null otherwise */ - protected KapuaListResult checkResult(KapuaId scopeId, KapuaListResult entity) { + protected KapuaListResult checkResult(KapuaId scopeId, KapuaListResult entity) { if (entity != null) { if (entity.getSize() == 0) { return entity; // If the list is empty, I want to return the empty list @@ -186,10 +190,14 @@ protected KapuaListResult checkResult(KapuaId scopeId, KapuaListResult entity) { /** * Handles logging for cache exceptions. * - * @param operation the name of the method/operation - * @param cacheName the name of the cache in which the operation is performed - * @param keyId the Id of the entry's key in the cache - * @param t the exception + * @param operation + * the name of the method/operation + * @param cacheName + * the name of the cache in which the operation is performed + * @param keyId + * the Id of the entry's key in the cache + * @param t + * the exception */ protected void cacheErrorLogger(String operation, String cacheName, Serializable keyId, Throwable t) { commonsMetric.getCacheError().inc(); diff --git a/commons/src/test/java/org/eclipse/kapua/commons/configuration/ServiceConfigurationCreatorImplTest.java b/commons/src/test/java/org/eclipse/kapua/commons/configuration/ServiceConfigCreatorTest.java similarity index 92% rename from commons/src/test/java/org/eclipse/kapua/commons/configuration/ServiceConfigurationCreatorImplTest.java rename to commons/src/test/java/org/eclipse/kapua/commons/configuration/ServiceConfigCreatorTest.java index 1ccb058a742..1a5b911beae 100644 --- a/commons/src/test/java/org/eclipse/kapua/commons/configuration/ServiceConfigurationCreatorImplTest.java +++ b/commons/src/test/java/org/eclipse/kapua/commons/configuration/ServiceConfigCreatorTest.java @@ -12,6 +12,8 @@ *******************************************************************************/ package org.eclipse.kapua.commons.configuration; +import java.util.Properties; + import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.qa.markers.junit.JUnitTests; import org.junit.Assert; @@ -19,17 +21,15 @@ import org.junit.Test; import org.junit.experimental.categories.Category; -import java.util.Properties; - - @Category(JUnitTests.class) -public class ServiceConfigurationCreatorImplTest { - ServiceConfigCreatorImpl configCreator; +public class ServiceConfigCreatorTest { + + ServiceConfigCreator configCreator; @Before public void createInstanceOfClass() { KapuaId id = KapuaId.ONE; - configCreator = new ServiceConfigCreatorImpl(id); + configCreator = new ServiceConfigCreator(id); } @Test diff --git a/commons/src/test/java/org/eclipse/kapua/commons/configuration/ServiceConfigImplTest.java b/commons/src/test/java/org/eclipse/kapua/commons/configuration/ServiceConfigImplTest.java deleted file mode 100644 index dc430321e74..00000000000 --- a/commons/src/test/java/org/eclipse/kapua/commons/configuration/ServiceConfigImplTest.java +++ /dev/null @@ -1,72 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2020, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.commons.configuration; - -import org.eclipse.kapua.KapuaException; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.qa.markers.junit.JUnitTests; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.experimental.categories.Category; - -import java.util.Properties; - - -@Category(JUnitTests.class) -public class ServiceConfigImplTest { - ServiceConfigImpl serviceConfigImpl; - - @Before - public void createInstenceOfClass() { - KapuaId id = KapuaId.ONE; - serviceConfigImpl = new ServiceConfigImpl(id); - } - - @Test - public void constructorWithNoValuesTest() { - ServiceConfigImpl config = new ServiceConfigImpl(); - Assert.assertNull(config.getPid()); - } - - @Test - public void setPidRegularTest() { - serviceConfigImpl.setPid("123"); - Assert.assertEquals(serviceConfigImpl.getPid(), "123"); - } - - @Test - public void setPidNullValueTest() { - serviceConfigImpl.setPid(null); - Assert.assertNull(serviceConfigImpl.getPid()); - } - - @Test - public void setConfigurationsNullValueTest() throws KapuaException { - serviceConfigImpl.setConfigurations(null); - Assert.assertEquals(serviceConfigImpl.getConfigurations(), new Properties()); - } - - @Test - public void setConfigurationsRegularTest() throws KapuaException { - Properties properties = new Properties(); - properties.setProperty("prop1", "value1"); - serviceConfigImpl.setConfigurations(properties); - Assert.assertEquals(serviceConfigImpl.getConfigurations(), properties); - } - - @Test - public void getTypeTest() { - Assert.assertEquals(serviceConfigImpl.getType(), ServiceConfig.TYPE); - } -} diff --git a/commons/src/test/java/org/eclipse/kapua/commons/configuration/ServiceConfigQueryImplTest.java b/commons/src/test/java/org/eclipse/kapua/commons/configuration/ServiceConfigQueryImplTest.java deleted file mode 100644 index 43e8195d15c..00000000000 --- a/commons/src/test/java/org/eclipse/kapua/commons/configuration/ServiceConfigQueryImplTest.java +++ /dev/null @@ -1,32 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2020, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.commons.configuration; - -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.qa.markers.junit.JUnitTests; -import org.junit.Assert; -import org.junit.Test; -import org.junit.experimental.categories.Category; - - - -@Category(JUnitTests.class) -public class ServiceConfigQueryImplTest { - - @Test - public void createInstanceTest() { - ServiceConfigQueryImpl query = new ServiceConfigQueryImpl(KapuaId.ONE); - Assert.assertEquals(query.getScopeId(), KapuaId.ONE); - } - -} diff --git a/commons/src/test/java/org/eclipse/kapua/commons/model/AbstractKapuaUpdatableEntityTest.java b/commons/src/test/java/org/eclipse/kapua/commons/model/AbstractKapuaUpdatableEntityTest.java index f46aca5c8cc..c093343e97d 100644 --- a/commons/src/test/java/org/eclipse/kapua/commons/model/AbstractKapuaUpdatableEntityTest.java +++ b/commons/src/test/java/org/eclipse/kapua/commons/model/AbstractKapuaUpdatableEntityTest.java @@ -12,6 +12,10 @@ *******************************************************************************/ package org.eclipse.kapua.commons.model; +import java.math.BigInteger; +import java.util.Date; +import java.util.Random; + import org.eclipse.kapua.commons.model.id.KapuaEid; import org.eclipse.kapua.commons.security.KapuaSecurityUtils; import org.eclipse.kapua.commons.security.KapuaSession; @@ -24,12 +28,6 @@ import org.junit.experimental.categories.Category; import org.mockito.Mockito; -import java.math.BigInteger; -import java.util.Date; -import java.util.Properties; -import java.util.Random; - - @Category(JUnitTests.class) public class AbstractKapuaUpdatableEntityTest { @@ -65,8 +63,8 @@ public void abstractKapuaUpdatableEntityScopeIdTest() { @Test public void abstractKapuaUpdatableEntityEntityIdTest() { KapuaUpdatableEntity entity = new ActualKapuaUpdatableEntity(); - entity.setEntityAttributes(new Properties()); - entity.setEntityProperties(new Properties()); + // entity.setEntityAttributes(new Properties()); + // entity.setEntityProperties(new Properties()); entity.setOptlock(10); AbstractKapuaUpdatableEntity updatableEntity = new ActualKapuaUpdatableEntity(entity); updatableEntity.setModifiedOn(new Date()); diff --git a/commons/src/test/java/org/eclipse/kapua/commons/model/AbstractKapuaEntityCreatorTest.java b/commons/src/test/java/org/eclipse/kapua/commons/model/KapuaEntityBaseCreatorTest.java similarity index 77% rename from commons/src/test/java/org/eclipse/kapua/commons/model/AbstractKapuaEntityCreatorTest.java rename to commons/src/test/java/org/eclipse/kapua/commons/model/KapuaEntityBaseCreatorTest.java index d224355c2fb..03fcbf01f22 100644 --- a/commons/src/test/java/org/eclipse/kapua/commons/model/AbstractKapuaEntityCreatorTest.java +++ b/commons/src/test/java/org/eclipse/kapua/commons/model/KapuaEntityBaseCreatorTest.java @@ -12,9 +12,14 @@ *******************************************************************************/ package org.eclipse.kapua.commons.model; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.Random; + import org.eclipse.kapua.commons.model.id.KapuaEid; import org.eclipse.kapua.commons.util.RandomUtils; import org.eclipse.kapua.model.KapuaEntity; +import org.eclipse.kapua.model.KapuaEntityCreator; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.qa.markers.junit.JUnitTests; import org.junit.Assert; @@ -24,14 +29,9 @@ import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; -import java.math.BigInteger; -import java.util.Arrays; -import java.util.Random; - - @Category(JUnitTests.class) @RunWith(value = Parameterized.class) -public class AbstractKapuaEntityCreatorTest { +public class KapuaEntityBaseCreatorTest { private final static Random RANDOM = RandomUtils.getInstance(); @@ -39,20 +39,20 @@ public class AbstractKapuaEntityCreatorTest { @Parameters public static Iterable eids() { - return Arrays.asList(new Object[]{new BigInteger(64, RANDOM)}, new Object[]{null}); + return Arrays.asList(new Object[] { new BigInteger(64, RANDOM) }, new Object[] { null }); } - public AbstractKapuaEntityCreatorTest(BigInteger eid) { + public KapuaEntityBaseCreatorTest(BigInteger eid) { this.eid = eid; } - private class ActualKapuaEntityCreator extends AbstractKapuaEntityCreator { + private class ActualKapuaEntityCreator extends KapuaEntityCreator { public ActualKapuaEntityCreator(KapuaId scopeId) { super(scopeId); } - public ActualKapuaEntityCreator(AbstractKapuaEntityCreator abstractEntityCreator) { + public ActualKapuaEntityCreator(KapuaEntityCreator abstractEntityCreator) { super(abstractEntityCreator); } } @@ -60,8 +60,8 @@ public ActualKapuaEntityCreator(AbstractKapuaEntityCreator abstractEntityCrea @Test public void constructorScopeIdTest() { KapuaId scopeId = new KapuaEid(eid); - AbstractKapuaEntityCreator kapuaEntityCreator = new ActualKapuaEntityCreator(scopeId); - AbstractKapuaEntityCreator kapuaCopyEntityCreator = new ActualKapuaEntityCreator(kapuaEntityCreator); + KapuaEntityCreator kapuaEntityCreator = new ActualKapuaEntityCreator(scopeId); + KapuaEntityCreator kapuaCopyEntityCreator = new ActualKapuaEntityCreator(kapuaEntityCreator); Assert.assertEquals("Those entities should have the same scopeId.", kapuaEntityCreator.getScopeId(), kapuaCopyEntityCreator.getScopeId()); } } diff --git a/commons/src/test/java/org/eclipse/kapua/commons/model/AbstractKapuaEntityTest.java b/commons/src/test/java/org/eclipse/kapua/commons/model/KapuaEntityBaseTest.java similarity index 98% rename from commons/src/test/java/org/eclipse/kapua/commons/model/AbstractKapuaEntityTest.java rename to commons/src/test/java/org/eclipse/kapua/commons/model/KapuaEntityBaseTest.java index 31f15068122..5a5e6d263bb 100644 --- a/commons/src/test/java/org/eclipse/kapua/commons/model/AbstractKapuaEntityTest.java +++ b/commons/src/test/java/org/eclipse/kapua/commons/model/KapuaEntityBaseTest.java @@ -12,6 +12,10 @@ *******************************************************************************/ package org.eclipse.kapua.commons.model; +import java.math.BigInteger; +import java.util.Date; +import java.util.Random; + import org.eclipse.kapua.commons.model.id.KapuaEid; import org.eclipse.kapua.commons.security.KapuaSecurityUtils; import org.eclipse.kapua.commons.security.KapuaSession; @@ -24,13 +28,8 @@ import org.junit.experimental.categories.Category; import org.mockito.Mockito; -import java.math.BigInteger; -import java.util.Date; -import java.util.Random; - - @Category(JUnitTests.class) -public class AbstractKapuaEntityTest { +public class KapuaEntityBaseTest { private final static Random RANDOM = RandomUtils.getInstance(); diff --git a/commons/src/test/java/org/eclipse/kapua/commons/model/AbstractKapuaNamedEntityCreatorTest.java b/commons/src/test/java/org/eclipse/kapua/commons/model/KapuaNamedEntityCreatorTest.java similarity index 72% rename from commons/src/test/java/org/eclipse/kapua/commons/model/AbstractKapuaNamedEntityCreatorTest.java rename to commons/src/test/java/org/eclipse/kapua/commons/model/KapuaNamedEntityCreatorTest.java index e287297625d..da40a00fa88 100644 --- a/commons/src/test/java/org/eclipse/kapua/commons/model/AbstractKapuaNamedEntityCreatorTest.java +++ b/commons/src/test/java/org/eclipse/kapua/commons/model/KapuaNamedEntityCreatorTest.java @@ -12,8 +12,12 @@ *******************************************************************************/ package org.eclipse.kapua.commons.model; +import java.util.Arrays; +import java.util.Collection; + import org.eclipse.kapua.commons.model.id.KapuaEid; import org.eclipse.kapua.model.KapuaEntity; +import org.eclipse.kapua.model.KapuaNamedEntityCreator; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.qa.markers.junit.JUnitTests; import org.junit.Assert; @@ -23,13 +27,9 @@ import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; -import java.util.Arrays; -import java.util.Collection; - - @Category(JUnitTests.class) @RunWith(value = Parameterized.class) -public class AbstractKapuaNamedEntityCreatorTest { +public class KapuaNamedEntityCreatorTest { private final String name; @@ -37,30 +37,26 @@ public class AbstractKapuaNamedEntityCreatorTest { KapuaId scopeId = new KapuaEid(); - AbstractKapuaNamedEntityCreator namedEntityCreator = new ActualKapuaNamedEntityCreator(scopeId); + KapuaNamedEntityCreator namedEntityCreator = new ActualKapuaNamedEntityCreator(scopeId, null); - public AbstractKapuaNamedEntityCreatorTest(String name, String description) { + public KapuaNamedEntityCreatorTest(String name, String description) { this.name = name; this.description = description; } @Parameters public static Collection strings() { - return Arrays.asList(new Object[][]{ - {"", ""}, - {"name", "description"}, - {"NAME", "DESCRIPTION"}, - {"&name%", "#description!"}, - {"1234", "5678"}, - {"make space", "make space"}, + return Arrays.asList(new Object[][] { + { "", "" }, + { "name", "description" }, + { "NAME", "DESCRIPTION" }, + { "&name%", "#description!" }, + { "1234", "5678" }, + { "make space", "make space" }, }); } - private class ActualKapuaNamedEntityCreator extends AbstractKapuaNamedEntityCreator { - - protected ActualKapuaNamedEntityCreator(KapuaId scopeId) { - super(scopeId); - } + private class ActualKapuaNamedEntityCreator extends KapuaNamedEntityCreator { protected ActualKapuaNamedEntityCreator(KapuaId scopeId, String name) { super(scopeId, name); @@ -70,7 +66,7 @@ protected ActualKapuaNamedEntityCreator(KapuaId scopeId, String name) { @Test public void abstractKapuaNamedEntityCreatorNameTest() { namedEntityCreator.setName(name); - AbstractKapuaNamedEntityCreator namedCopyEntityCreator = new ActualKapuaNamedEntityCreator(scopeId, name); + KapuaNamedEntityCreator namedCopyEntityCreator = new ActualKapuaNamedEntityCreator(scopeId, name); Assert.assertEquals("Expected and actual values should be the same!", namedEntityCreator.getName(), namedCopyEntityCreator.getName()); } diff --git a/commons/src/test/java/org/eclipse/kapua/commons/model/AbstractKapuaUpdatableEntityCreatorTest.java b/commons/src/test/java/org/eclipse/kapua/commons/model/KapuaUpdatableEntityCreatorTest.java similarity index 75% rename from commons/src/test/java/org/eclipse/kapua/commons/model/AbstractKapuaUpdatableEntityCreatorTest.java rename to commons/src/test/java/org/eclipse/kapua/commons/model/KapuaUpdatableEntityCreatorTest.java index d4d4b67e0bb..787230be2ca 100644 --- a/commons/src/test/java/org/eclipse/kapua/commons/model/AbstractKapuaUpdatableEntityCreatorTest.java +++ b/commons/src/test/java/org/eclipse/kapua/commons/model/KapuaUpdatableEntityCreatorTest.java @@ -12,21 +12,20 @@ *******************************************************************************/ package org.eclipse.kapua.commons.model; +import java.util.Properties; + import org.eclipse.kapua.commons.model.id.KapuaEid; -import org.eclipse.kapua.model.KapuaEntity; +import org.eclipse.kapua.model.KapuaUpdatableEntityCreator; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.qa.markers.junit.JUnitTests; import org.junit.Assert; import org.junit.Test; import org.junit.experimental.categories.Category; -import java.util.Properties; - - @Category(JUnitTests.class) -public class AbstractKapuaUpdatableEntityCreatorTest { +public class KapuaUpdatableEntityCreatorTest { - private class ActualKapuaUpdatableEntityCreator extends AbstractKapuaUpdatableEntityCreator { + private class ActualKapuaUpdatableEntityCreator extends KapuaUpdatableEntityCreator { public ActualKapuaUpdatableEntityCreator(KapuaId scopeId) { super(scopeId); @@ -36,14 +35,14 @@ public ActualKapuaUpdatableEntityCreator(KapuaId scopeId) { @Test public void abstractKapuaUpdatableEntityCreatorScopeId() { KapuaId scopeId = new KapuaEid(); - AbstractKapuaUpdatableEntityCreator kapuaUpdatableEntityCreator = new ActualKapuaUpdatableEntityCreator<>(scopeId); + KapuaUpdatableEntityCreator kapuaUpdatableEntityCreator = new ActualKapuaUpdatableEntityCreator(scopeId); Assert.assertEquals("Actual and expected values are not the same!", scopeId, kapuaUpdatableEntityCreator.getScopeId()); } @Test public void getEntityAttributesTest() { KapuaId scopeId = new KapuaEid(); - AbstractKapuaUpdatableEntityCreator kapuaUpdatableEntityCreator = new ActualKapuaUpdatableEntityCreator<>(scopeId); + KapuaUpdatableEntityCreator kapuaUpdatableEntityCreator = new ActualKapuaUpdatableEntityCreator(scopeId); Properties properties = new Properties(); kapuaUpdatableEntityCreator.setEntityAttributes(properties); Assert.assertEquals("Actual and expected values are not the same!", properties, kapuaUpdatableEntityCreator.getEntityAttributes()); diff --git a/commons/src/test/java/org/eclipse/kapua/commons/model/misc/CollisionEntityJpaRepository.java b/commons/src/test/java/org/eclipse/kapua/commons/model/misc/CollisionEntityJpaRepository.java index dacf2bbb7e1..e8d5726b35d 100644 --- a/commons/src/test/java/org/eclipse/kapua/commons/model/misc/CollisionEntityJpaRepository.java +++ b/commons/src/test/java/org/eclipse/kapua/commons/model/misc/CollisionEntityJpaRepository.java @@ -14,14 +14,12 @@ import org.eclipse.kapua.commons.jpa.KapuaEntityJpaRepository; import org.eclipse.kapua.commons.jpa.KapuaJpaRepositoryConfiguration; -import org.eclipse.kapua.commons.model.query.KapuaListResultImpl; import org.eclipse.kapua.model.query.KapuaListResult; - public class CollisionEntityJpaRepository extends KapuaEntityJpaRepository> { public CollisionEntityJpaRepository(KapuaJpaRepositoryConfiguration configuration) { - super(CollisionEntity.class, CollisionEntity.TYPE, () -> new KapuaListResultImpl<>(), configuration); + super(CollisionEntity.class, CollisionEntity.TYPE, () -> new KapuaListResult<>(), configuration); } } diff --git a/commons/src/test/java/org/eclipse/kapua/commons/model/query/FieldSortCriteriaImplTest.java b/commons/src/test/java/org/eclipse/kapua/commons/model/query/FieldSortCriteriaTest.java similarity index 64% rename from commons/src/test/java/org/eclipse/kapua/commons/model/query/FieldSortCriteriaImplTest.java rename to commons/src/test/java/org/eclipse/kapua/commons/model/query/FieldSortCriteriaTest.java index 0e93245f75e..64125803b90 100644 --- a/commons/src/test/java/org/eclipse/kapua/commons/model/query/FieldSortCriteriaImplTest.java +++ b/commons/src/test/java/org/eclipse/kapua/commons/model/query/FieldSortCriteriaTest.java @@ -12,6 +12,9 @@ *******************************************************************************/ package org.eclipse.kapua.commons.model.query; +import java.util.Arrays; + +import org.eclipse.kapua.model.query.FieldSortCriteria; import org.eclipse.kapua.model.query.SortOrder; import org.eclipse.kapua.qa.markers.junit.JUnitTests; import org.junit.Assert; @@ -21,40 +24,38 @@ import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; -import java.util.Arrays; - - @Category(JUnitTests.class) @RunWith(value = Parameterized.class) -public class FieldSortCriteriaImplTest { +public class FieldSortCriteriaTest { private final String attributeName; private SortOrder sortOrder; - public FieldSortCriteriaImplTest(String attributeName) { + public FieldSortCriteriaTest(String attributeName) { this.attributeName = attributeName; } @Parameters public static Iterable attributeNames() { return Arrays.asList( - new Object[]{""}, - new Object[]{"NAME"}, - new Object[]{"attributeName"}, - new Object[]{"attribute name"}, - new Object[]{"0123456789"}, - new Object[]{"!#$%&'()=?⁄@‹›€°·‚,.-;:_Èˇ¿<>«‘”’ÉØ∏{}|ÆæÒuF8FFÔÓÌÏÎÅ«»Ç◊ш¯Èˇ"}, - new Object[]{"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefg"}); + new Object[] { "" }, + new Object[] { "NAME" }, + new Object[] { "attributeName" }, + new Object[] { "attribute name" }, + new Object[] { "0123456789" }, + new Object[] { "!#$%&'()=?⁄@‹›€°·‚,.-;:_Èˇ¿<>«‘”’ÉØ∏{}|ÆæÒuF8FFÔÓÌÏÎÅ«»Ç◊ш¯Èˇ" }, + new Object[] { + "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefg" }); } @Test public void fieldSortCriteriaImplTest() { SortOrder sortOrderAscending = SortOrder.ASCENDING; - FieldSortCriteriaImpl fieldSortCriteriaAscending = new FieldSortCriteriaImpl(attributeName, sortOrderAscending); + FieldSortCriteria fieldSortCriteriaAscending = new FieldSortCriteria(attributeName, sortOrderAscending); Assert.assertEquals("Actual and expected values are not the same!", attributeName, fieldSortCriteriaAscending.getAttributeName()); Assert.assertEquals("Actual and expected values are not the same!", sortOrderAscending, fieldSortCriteriaAscending.getSortOrder()); SortOrder sortOrderDescending = SortOrder.DESCENDING; - FieldSortCriteriaImpl fieldSortCriteriaDescending = new FieldSortCriteriaImpl(attributeName, sortOrderDescending); + FieldSortCriteria fieldSortCriteriaDescending = new FieldSortCriteria(attributeName, sortOrderDescending); Assert.assertEquals("Actual and expected values are not the same!", attributeName, fieldSortCriteriaDescending.getAttributeName()); Assert.assertEquals("Actual and expected values are not the same!", sortOrderDescending, fieldSortCriteriaDescending.getSortOrder()); } diff --git a/commons/src/test/java/org/eclipse/kapua/commons/model/query/KapuaListResultImplTest.java b/commons/src/test/java/org/eclipse/kapua/commons/model/query/KapuaListResultTest.java similarity index 84% rename from commons/src/test/java/org/eclipse/kapua/commons/model/query/KapuaListResultImplTest.java rename to commons/src/test/java/org/eclipse/kapua/commons/model/query/KapuaListResultTest.java index db57913c750..16ddd12dc2e 100644 --- a/commons/src/test/java/org/eclipse/kapua/commons/model/query/KapuaListResultImplTest.java +++ b/commons/src/test/java/org/eclipse/kapua/commons/model/query/KapuaListResultTest.java @@ -12,31 +12,32 @@ *******************************************************************************/ package org.eclipse.kapua.commons.model.query; +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.Random; + import org.eclipse.kapua.commons.model.AbstractKapuaEntity; import org.eclipse.kapua.commons.model.id.KapuaEid; import org.eclipse.kapua.commons.util.RandomUtils; import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.query.KapuaListResult; import org.eclipse.kapua.qa.markers.junit.JUnitTests; import org.junit.Assert; import org.junit.Test; import org.junit.experimental.categories.Category; import org.mockito.Mockito; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.List; -import java.util.Map; -import java.util.Random; - @Category(JUnitTests.class) -public class KapuaListResultImplTest { +public class KapuaListResultTest { private final static Random RANDOM = RandomUtils.getInstance(); @Test - public void kapuaListResultImplTest() { - KapuaListResultImpl kapuaListResult = new KapuaListResultImpl<>(); + public void kapuaListResultTest() { + KapuaListResult kapuaListResult = new KapuaListResult<>(); Assert.assertNotNull(kapuaListResult.getItems()); Assert.assertTrue(kapuaListResult.getItems().isEmpty()); @@ -53,7 +54,7 @@ public void addItemsTest() { items.add(kapuaEntity1); items.add(kapuaEntity2); - KapuaListResultImpl kapuaListResult = new KapuaListResultImpl<>(); + KapuaListResult kapuaListResult = new KapuaListResult<>(); kapuaListResult.addItems(items); Assert.assertEquals(2, kapuaListResult.getItems().size()); @@ -67,7 +68,7 @@ public void addItemTest() { AbstractKapuaEntity kapuaEntity1 = Mockito.mock(AbstractKapuaEntity.class); AbstractKapuaEntity kapuaEntity2 = Mockito.mock(AbstractKapuaEntity.class); - KapuaListResultImpl kapuaListResult = new KapuaListResultImpl<>(); + KapuaListResult kapuaListResult = new KapuaListResult<>(); kapuaListResult.addItem(kapuaEntity1); kapuaListResult.addItem(kapuaEntity2); @@ -79,7 +80,7 @@ public void addItemTest() { @Test public void clearItemsTest() { int testSize = 10; - KapuaListResultImpl kapuaListResult = new KapuaListResultImpl<>(); + KapuaListResult kapuaListResult = new KapuaListResult<>(); for (int i = 0; i < testSize; i++) { kapuaListResult.addItem(Mockito.mock(AbstractKapuaEntity.class)); @@ -94,7 +95,7 @@ public void clearItemsTest() { @Test public void getFirstItemTest() { - KapuaListResultImpl kapuaListResult = new KapuaListResultImpl<>(); + KapuaListResult kapuaListResult = new KapuaListResult<>(); AbstractKapuaEntity kapuaEntity1 = Mockito.mock(AbstractKapuaEntity.class); kapuaListResult.addItem(kapuaEntity1); @@ -108,7 +109,7 @@ public void getFirstItemTest() { @Test public void getItemsTest() { - KapuaListResultImpl kapuaListResult = new KapuaListResultImpl<>(); + KapuaListResult kapuaListResult = new KapuaListResult<>(); AbstractKapuaEntity kapuaEntity1 = Mockito.mock(AbstractKapuaEntity.class); kapuaListResult.addItem(kapuaEntity1); @@ -124,7 +125,7 @@ public void getItemsTest() { @Test public void getItemsPredicateTest() { int testSize = 10; - KapuaListResultImpl kapuaListResult = new KapuaListResultImpl<>(); + KapuaListResult kapuaListResult = new KapuaListResult<>(); for (int i = 0; i < testSize; i++) { AbstractKapuaEntity kapuaEntity = Mockito.mock(AbstractKapuaEntity.class); @@ -144,7 +145,7 @@ public void getItemsPredicateTest() { @Test public void getItemsAsMapKeyTest() { int testSize = 10; - KapuaListResultImpl kapuaListResult = new KapuaListResultImpl<>(); + KapuaListResult kapuaListResult = new KapuaListResult<>(); for (int i = 0; i < testSize; i++) { AbstractKapuaEntity kapuaEntity = Mockito.mock(AbstractKapuaEntity.class); @@ -164,7 +165,7 @@ public void getItemsAsMapKeyTest() { @Test public void getItemsAsMapKeyValueTest() { int testSize = 10; - KapuaListResultImpl kapuaListResult = new KapuaListResultImpl<>(); + KapuaListResult kapuaListResult = new KapuaListResult<>(); for (int i = 0; i < testSize; i++) { AbstractKapuaEntity kapuaEntity = Mockito.mock(AbstractKapuaEntity.class); @@ -181,10 +182,9 @@ public void getItemsAsMapKeyValueTest() { } } - @Test public void getItemTest() { - KapuaListResultImpl kapuaListResult = new KapuaListResultImpl<>(); + KapuaListResult kapuaListResult = new KapuaListResult<>(); AbstractKapuaEntity kapuaEntity1 = Mockito.mock(AbstractKapuaEntity.class); kapuaListResult.addItem(kapuaEntity1); @@ -199,7 +199,7 @@ public void getItemTest() { @Test public void getSizeTest() { int testSize = 10; - KapuaListResultImpl kapuaListResult = new KapuaListResultImpl<>(); + KapuaListResult kapuaListResult = new KapuaListResult<>(); for (int i = 0; i < testSize; i++) { kapuaListResult.addItem(Mockito.mock(AbstractKapuaEntity.class)); @@ -210,7 +210,7 @@ public void getSizeTest() { @Test public void isEmptyTest() { - KapuaListResultImpl kapuaListResult = new KapuaListResultImpl<>(); + KapuaListResult kapuaListResult = new KapuaListResult<>(); Assert.assertTrue(kapuaListResult.isEmpty()); kapuaListResult.addItem(Mockito.mock(AbstractKapuaEntity.class)); @@ -219,7 +219,7 @@ public void isEmptyTest() { @Test public void setGetLimitExceededTrueTest() { - KapuaListResultImpl kapuaListResult = new KapuaListResultImpl<>(); + KapuaListResult kapuaListResult = new KapuaListResult<>(); kapuaListResult.setLimitExceeded(true); Assert.assertTrue(kapuaListResult.isLimitExceeded()); @@ -227,7 +227,7 @@ public void setGetLimitExceededTrueTest() { @Test public void setGetLimitExceededFalseTest() { - KapuaListResultImpl kapuaListResult = new KapuaListResultImpl<>(); + KapuaListResult kapuaListResult = new KapuaListResult<>(); kapuaListResult.setLimitExceeded(false); Assert.assertFalse(kapuaListResult.isLimitExceeded()); @@ -235,14 +235,14 @@ public void setGetLimitExceededFalseTest() { @Test public void setGetTotalCountDefaultTest() { - KapuaListResultImpl kapuaListResult = new KapuaListResultImpl<>(); + KapuaListResult kapuaListResult = new KapuaListResult<>(); Assert.assertNull(kapuaListResult.getTotalCount()); } @Test public void setGetTotalCountValueTest() { - KapuaListResultImpl kapuaListResult = new KapuaListResultImpl<>(); + KapuaListResult kapuaListResult = new KapuaListResult<>(); kapuaListResult.setTotalCount(10L); Assert.assertEquals(new Long(10L), kapuaListResult.getTotalCount()); @@ -251,7 +251,7 @@ public void setGetTotalCountValueTest() { @Test public void sortComparatorTest() { int testSize = 10; - KapuaListResultImpl kapuaListResult = new KapuaListResultImpl<>(); + KapuaListResult kapuaListResult = new KapuaListResult<>(); // Add the max value AbstractKapuaEntity kapuaEntityMax = Mockito.mock(AbstractKapuaEntity.class); diff --git a/commons/src/test/java/org/eclipse/kapua/commons/model/query/AbstractKapuaQueryTest.java b/commons/src/test/java/org/eclipse/kapua/commons/model/query/KapuaQueryTest.java similarity index 70% rename from commons/src/test/java/org/eclipse/kapua/commons/model/query/AbstractKapuaQueryTest.java rename to commons/src/test/java/org/eclipse/kapua/commons/model/query/KapuaQueryTest.java index b04a8c0fb42..69c2958adef 100644 --- a/commons/src/test/java/org/eclipse/kapua/commons/model/query/AbstractKapuaQueryTest.java +++ b/commons/src/test/java/org/eclipse/kapua/commons/model/query/KapuaQueryTest.java @@ -12,10 +12,14 @@ *******************************************************************************/ package org.eclipse.kapua.commons.model.query; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; + import org.eclipse.kapua.commons.model.id.KapuaEid; -import org.eclipse.kapua.commons.model.query.predicate.AndPredicateImpl; -import org.eclipse.kapua.commons.model.query.predicate.OrPredicateImpl; import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.query.FieldSortCriteria; import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.model.query.KapuaSortCriteria; import org.eclipse.kapua.model.query.SortOrder; @@ -32,60 +36,40 @@ import org.junit.runners.Parameterized.Parameters; import org.mockito.Mockito; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; - - @Category(JUnitTests.class) @RunWith(value = Parameterized.class) -public class AbstractKapuaQueryTest { +public class KapuaQueryTest { private final String attributeName; private final AttributePredicate.Operator operator; - public AbstractKapuaQueryTest(String attributeName, AttributePredicate.Operator operator) { + public KapuaQueryTest(String attributeName, AttributePredicate.Operator operator) { this.attributeName = attributeName; this.operator = operator; } @Parameters public static Collection attributeNamesAndOperators() { - return Arrays.asList(new Object[][]{ - {"", AttributePredicate.Operator.EQUAL}, - {"NAME", AttributePredicate.Operator.NOT_EQUAL}, - {"attributeName", AttributePredicate.Operator.IS_NULL}, - {"attribute name", AttributePredicate.Operator.NOT_NULL}, - {"0123456789", AttributePredicate.Operator.GREATER_THAN}, - {"!#$%&'()=?⁄@‹›€°·‚,.-;:_Èˇ¿<>«‘”’ÉØ∏{}|ÆæÒuF8FFÔÓÌÏÎÅ«»Ç◊ш¯Èˇ", AttributePredicate.Operator.GREATER_THAN_OR_EQUAL}, - {"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefg", AttributePredicate.Operator.STARTS_WITH}, - {"ATTRIBUTE NAME", AttributePredicate.Operator.LIKE}, - {"name123", AttributePredicate.Operator.LESS_THAN}, - {"#$attribute", AttributePredicate.Operator.LESS_THAN_OR_EQUAL}, + return Arrays.asList(new Object[][] { + { "", AttributePredicate.Operator.EQUAL }, + { "NAME", AttributePredicate.Operator.NOT_EQUAL }, + { "attributeName", AttributePredicate.Operator.IS_NULL }, + { "attribute name", AttributePredicate.Operator.NOT_NULL }, + { "0123456789", AttributePredicate.Operator.GREATER_THAN }, + { "!#$%&'()=?⁄@‹›€°·‚,.-;:_Èˇ¿<>«‘”’ÉØ∏{}|ÆæÒuF8FFÔÓÌÏÎÅ«»Ç◊ш¯Èˇ", AttributePredicate.Operator.GREATER_THAN_OR_EQUAL }, + { "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefg", + AttributePredicate.Operator.STARTS_WITH }, + { "ATTRIBUTE NAME", AttributePredicate.Operator.LIKE }, + { "name123", AttributePredicate.Operator.LESS_THAN }, + { "#$attribute", AttributePredicate.Operator.LESS_THAN_OR_EQUAL }, }); } - private class ActualKapuaQuery extends AbstractKapuaQuery { - - public ActualKapuaQuery() { - super(); - } - - public ActualKapuaQuery(KapuaId scopeId) { - super(scopeId); - } - - public ActualKapuaQuery(KapuaQuery query) { - super(query); - } - } - @Test public void abstractKapuaQueryScopeIdTest() { KapuaId scopeId = new KapuaEid(); - AbstractKapuaQuery kapuaQuery = new ActualKapuaQuery(scopeId); + KapuaQuery kapuaQuery = new KapuaQuery(scopeId); Assert.assertEquals("Actual and expected values are not the same!", scopeId, kapuaQuery.getScopeId()); } @@ -93,18 +77,18 @@ public void abstractKapuaQueryScopeIdTest() { public void abstractKapuaQueryQueryIdTest() { KapuaId scopeId = new KapuaEid(); List fetchAttributes = new ArrayList<>(); - QueryPredicate predicate = Mockito.mock(AndPredicateImpl.class); + QueryPredicate predicate = Mockito.mock(AndPredicate.class); SortOrder sortOrder = SortOrder.ASCENDING; - KapuaSortCriteria sortCriteria = new FieldSortCriteriaImpl(attributeName, sortOrder); + KapuaSortCriteria sortCriteria = new FieldSortCriteria(attributeName, sortOrder); Integer limit = 48; Integer offset = 56; - AbstractKapuaQuery kapuaQuery = new ActualKapuaQuery(scopeId); + KapuaQuery kapuaQuery = new KapuaQuery(scopeId); kapuaQuery.setFetchAttributes(fetchAttributes); kapuaQuery.setPredicate(predicate); kapuaQuery.setLimit(limit); kapuaQuery.setOffset(offset); kapuaQuery.setSortCriteria(sortCriteria); - AbstractKapuaQuery kapuaCopyQuery = new ActualKapuaQuery(kapuaQuery); + KapuaQuery kapuaCopyQuery = new KapuaQuery(kapuaQuery); Assert.assertEquals("Actual and expected values are not the same!", kapuaQuery.getFetchAttributes(), kapuaCopyQuery.getFetchAttributes()); Assert.assertEquals("Actual and expected values are not the same!", kapuaQuery.getPredicate(), kapuaCopyQuery.getPredicate()); Assert.assertEquals("Actual and expected values are not the same!", kapuaQuery.getLimit(), kapuaCopyQuery.getLimit()); @@ -114,7 +98,7 @@ public void abstractKapuaQueryQueryIdTest() { @Test public void addFetchAttributesTest() { - AbstractKapuaQuery kapuaQuery = new ActualKapuaQuery(); + KapuaQuery kapuaQuery = new KapuaQuery(); String emptyFetchAttribute = ""; String fetchAttribute = "fetchAttribute"; kapuaQuery.addFetchAttributes(null); @@ -127,7 +111,7 @@ public void addFetchAttributesTest() { @Test public void attributePredicateTest() { - AbstractKapuaQuery kapuaQuery = new ActualKapuaQuery(); + KapuaQuery kapuaQuery = new KapuaQuery(); Object attributeValue = new Object(); AttributePredicate attributePredicate = kapuaQuery.attributePredicate(attributeName, attributeValue); Assert.assertEquals("Actual and expected values are not the same!", attributeName, attributePredicate.getAttributeName()); @@ -136,7 +120,7 @@ public void attributePredicateTest() { @Test public void attributePredicateWithOperatorTest() { - AbstractKapuaQuery kapuaQuery = new ActualKapuaQuery(); + KapuaQuery kapuaQuery = new KapuaQuery(); Object attributeValue = new Object(); AttributePredicate attributePredicate = kapuaQuery.attributePredicate(attributeName, attributeValue, operator); Assert.assertEquals("Actual and expected values are not the same!", attributeName, attributePredicate.getAttributeName()); @@ -146,7 +130,7 @@ public void attributePredicateWithOperatorTest() { @Test public void andPredicateTest() { - AbstractKapuaQuery kapuaQuery = new ActualKapuaQuery(); + KapuaQuery kapuaQuery = new KapuaQuery(); AndPredicate andPredicate = kapuaQuery.andPredicate(); ArrayList queryPredicateArray = new ArrayList<>(); Assert.assertEquals("Actual and expected values are not the same!", queryPredicateArray, andPredicate.getPredicates()); @@ -154,18 +138,18 @@ public void andPredicateTest() { @Test public void andPredicateWithQueryPredicatesTest() { - AbstractKapuaQuery kapuaQuery = new ActualKapuaQuery(); + KapuaQuery kapuaQuery = new KapuaQuery(); QueryPredicate[] queryPredicateArray = new QueryPredicate[10]; for (int i = 0; i < queryPredicateArray.length; i++) { - queryPredicateArray[i] = Mockito.mock(AndPredicateImpl.class); + queryPredicateArray[i] = Mockito.mock(AndPredicate.class); } - AndPredicate andPredicate = new AndPredicateImpl(queryPredicateArray); + AndPredicate andPredicate = new AndPredicate(queryPredicateArray); Assert.assertEquals("Actual and expected values are not the same!", andPredicate.getPredicates(), kapuaQuery.andPredicate(queryPredicateArray).getPredicates()); } @Test public void orPredicateTest() { - AbstractKapuaQuery kapuaQuery = new ActualKapuaQuery(); + KapuaQuery kapuaQuery = new KapuaQuery(); OrPredicate orPredicate = kapuaQuery.orPredicate(); ArrayList queryPredicateArray = new ArrayList<>(); Assert.assertEquals("Actual and expected values are not the same!", queryPredicateArray, orPredicate.getPredicates()); @@ -173,18 +157,18 @@ public void orPredicateTest() { @Test public void orPredicateWithQueryPredicatesTest() { - AbstractKapuaQuery kapuaQuery = new ActualKapuaQuery(); + KapuaQuery kapuaQuery = new KapuaQuery(); QueryPredicate[] queryPredicateArray = new QueryPredicate[5]; for (int i = 0; i < queryPredicateArray.length; i++) { - queryPredicateArray[i] = Mockito.mock(AndPredicateImpl.class); + queryPredicateArray[i] = Mockito.mock(AndPredicate.class); } - OrPredicate orPredicate = new OrPredicateImpl(queryPredicateArray); + OrPredicate orPredicate = new OrPredicate(queryPredicateArray); Assert.assertEquals("Actual and expected values are not the same!", orPredicate.getPredicates(), kapuaQuery.orPredicate(queryPredicateArray).getPredicates()); } @Test public void getAskTotalCountTest() { - AbstractKapuaQuery kapuaQuery = new ActualKapuaQuery(); + KapuaQuery kapuaQuery = new KapuaQuery(); kapuaQuery.setAskTotalCount(true); Assert.assertEquals("Actual and expected values are not the same!", true, kapuaQuery.getAskTotalCount()); kapuaQuery.setAskTotalCount(false); diff --git a/commons/src/test/java/org/eclipse/kapua/commons/model/query/predicate/AndPredicateImplTest.java b/commons/src/test/java/org/eclipse/kapua/commons/model/query/predicate/AndPredicateTest.java similarity index 68% rename from commons/src/test/java/org/eclipse/kapua/commons/model/query/predicate/AndPredicateImplTest.java rename to commons/src/test/java/org/eclipse/kapua/commons/model/query/predicate/AndPredicateTest.java index 8fa95c35c37..8adc5a119df 100644 --- a/commons/src/test/java/org/eclipse/kapua/commons/model/query/predicate/AndPredicateImplTest.java +++ b/commons/src/test/java/org/eclipse/kapua/commons/model/query/predicate/AndPredicateTest.java @@ -12,36 +12,36 @@ *******************************************************************************/ package org.eclipse.kapua.commons.model.query.predicate; +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.kapua.model.query.predicate.AndPredicate; import org.eclipse.kapua.model.query.predicate.QueryPredicate; import org.eclipse.kapua.qa.markers.junit.JUnitTests; import org.junit.Assert; import org.junit.Test; import org.junit.experimental.categories.Category; -import java.util.ArrayList; -import java.util.List; - - @Category(JUnitTests.class) -public class AndPredicateImplTest { +public class AndPredicateTest { @Test public void andPredicateImpl() { - AndPredicateImpl andPredicate = new AndPredicateImpl(); + AndPredicate andPredicate = new AndPredicate(); ArrayList array = new ArrayList<>(); Assert.assertEquals("Actual and expected values are not the same!", array, andPredicate.getPredicates()); } @Test public void andPredicateImplQueryPredicateId() { - QueryPredicate queryPredicate = new AndPredicateImpl(); - AndPredicateImpl andPredicate = new AndPredicateImpl(queryPredicate); + QueryPredicate queryPredicate = new AndPredicate(); + AndPredicate andPredicate = new AndPredicate(queryPredicate); Assert.assertEquals("Actual and expected values are not the same!", queryPredicate, andPredicate.getPredicates().get(0)); - QueryPredicate queryPredicate1 = new AndPredicateImpl(); - QueryPredicate queryPredicate2 = new AndPredicateImpl(); - QueryPredicate queryPredicate3 = new AndPredicateImpl(); - QueryPredicate[] queryPredicateArray = {queryPredicate1, queryPredicate2, queryPredicate3}; - AndPredicateImpl andPredicateWithMultiplePredicates = new AndPredicateImpl(queryPredicate1, queryPredicate2, queryPredicate3); + QueryPredicate queryPredicate1 = new AndPredicate(); + QueryPredicate queryPredicate2 = new AndPredicate(); + QueryPredicate queryPredicate3 = new AndPredicate(); + QueryPredicate[] queryPredicateArray = { queryPredicate1, queryPredicate2, queryPredicate3 }; + AndPredicate andPredicateWithMultiplePredicates = new AndPredicate(queryPredicate1, queryPredicate2, queryPredicate3); for (int i = 0; i < queryPredicateArray.length; i++) { Assert.assertEquals("Actual and expected values are not the same!", queryPredicateArray[i], andPredicateWithMultiplePredicates.getPredicates().get(i)); } @@ -49,26 +49,26 @@ public void andPredicateImplQueryPredicateId() { @Test public void andTest() { - AndPredicateImpl andPredicate = new AndPredicateImpl(); - QueryPredicate queryPredicate = new AndPredicateImpl(); + AndPredicate andPredicate = new AndPredicate(); + QueryPredicate queryPredicate = new AndPredicate(); andPredicate.and(queryPredicate); Assert.assertEquals("Actual and expected values are not the same!", queryPredicate, andPredicate.getPredicates().get(0)); } @Test public void andWithNullPredicateTest() { - AndPredicateImpl andPredicate = new AndPredicateImpl(); + AndPredicate andPredicate = new AndPredicate(); andPredicate.and(null); Assert.assertNull(andPredicate.getPredicates().get(0)); } @Test public void getPredicatesTest() { - AndPredicateImpl andPredicate = new AndPredicateImpl(); + AndPredicate andPredicate = new AndPredicate(); List predicates = new ArrayList<>(); - predicates.add(new AndPredicateImpl()); - predicates.add(new AndPredicateImpl()); - predicates.add(new AndPredicateImpl()); + predicates.add(new AndPredicate()); + predicates.add(new AndPredicate()); + predicates.add(new AndPredicate()); andPredicate.setPredicates(predicates); for (int i = 0; i < predicates.size(); i++) { Assert.assertEquals("Actual and expected values are not the same!", predicates.get(i), andPredicate.getPredicates().get(i)); diff --git a/commons/src/test/java/org/eclipse/kapua/commons/model/query/predicate/AttributePredicateImplTest.java b/commons/src/test/java/org/eclipse/kapua/commons/model/query/predicate/AttributePredicateTest.java similarity index 64% rename from commons/src/test/java/org/eclipse/kapua/commons/model/query/predicate/AttributePredicateImplTest.java rename to commons/src/test/java/org/eclipse/kapua/commons/model/query/predicate/AttributePredicateTest.java index 7a5f9e41180..9a5f9977ed2 100644 --- a/commons/src/test/java/org/eclipse/kapua/commons/model/query/predicate/AttributePredicateImplTest.java +++ b/commons/src/test/java/org/eclipse/kapua/commons/model/query/predicate/AttributePredicateTest.java @@ -12,6 +12,9 @@ *******************************************************************************/ package org.eclipse.kapua.commons.model.query.predicate; +import java.util.Arrays; +import java.util.Collection; + import org.eclipse.kapua.model.query.predicate.AttributePredicate; import org.eclipse.kapua.qa.markers.junit.JUnitTests; import org.junit.Assert; @@ -21,87 +24,84 @@ import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; -import java.util.Arrays; -import java.util.Collection; - - @Category(JUnitTests.class) @RunWith(value = Parameterized.class) -public class AttributePredicateImplTest { +public class AttributePredicateTest { private final String attributeName; private final AttributePredicate.Operator operator; - public AttributePredicateImplTest(String attributeName, AttributePredicate.Operator operator) { + public AttributePredicateTest(String attributeName, AttributePredicate.Operator operator) { this.attributeName = attributeName; this.operator = operator; } @Parameters public static Collection attributeNamesAndOperators() { - return Arrays.asList(new Object[][]{ - {"", AttributePredicate.Operator.EQUAL}, - {"NAME", AttributePredicate.Operator.NOT_EQUAL}, - {"attributeName", AttributePredicate.Operator.IS_NULL}, - {"attribute name", AttributePredicate.Operator.NOT_NULL}, - {"0123456789", AttributePredicate.Operator.GREATER_THAN}, - {"!#$%&'()=?⁄@‹›€°·‚,.-;:_Èˇ¿<>«‘”’ÉØ∏{}|ÆæÒuF8FFÔÓÌÏÎÅ«»Ç◊ш¯Èˇ", AttributePredicate.Operator.GREATER_THAN_OR_EQUAL}, - {"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefg", AttributePredicate.Operator.STARTS_WITH}, - {"ATTRIBUTE NAME", AttributePredicate.Operator.LIKE}, - {"name123", AttributePredicate.Operator.LESS_THAN}, - {"#$attribute", AttributePredicate.Operator.LESS_THAN_OR_EQUAL}, + return Arrays.asList(new Object[][] { + { "", AttributePredicate.Operator.EQUAL }, + { "NAME", AttributePredicate.Operator.NOT_EQUAL }, + { "attributeName", AttributePredicate.Operator.IS_NULL }, + { "attribute name", AttributePredicate.Operator.NOT_NULL }, + { "0123456789", AttributePredicate.Operator.GREATER_THAN }, + { "!#$%&'()=?⁄@‹›€°·‚,.-;:_Èˇ¿<>«‘”’ÉØ∏{}|ÆæÒuF8FFÔÓÌÏÎÅ«»Ç◊ш¯Èˇ", AttributePredicate.Operator.GREATER_THAN_OR_EQUAL }, + { "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefg", + AttributePredicate.Operator.STARTS_WITH }, + { "ATTRIBUTE NAME", AttributePredicate.Operator.LIKE }, + { "name123", AttributePredicate.Operator.LESS_THAN }, + { "#$attribute", AttributePredicate.Operator.LESS_THAN_OR_EQUAL }, }); } @Test public void attributePredicateImplTest() { String attributeValueStr = ""; - AttributePredicateImpl attributePredicateStr = new AttributePredicateImpl<>(attributeName, attributeValueStr); + AttributePredicate attributePredicateStr = new AttributePredicate<>(attributeName, attributeValueStr); Assert.assertEquals("Actual and expected values are not the same!", attributeName, attributePredicateStr.getAttributeName()); Assert.assertEquals("Actual and expected values are not the same!", attributeValueStr, attributePredicateStr.getAttributeValue()); Integer attributeValueInt = 1234567890; - AttributePredicateImpl attributePredicateInt = new AttributePredicateImpl<>(attributeName, attributeValueInt); + AttributePredicate attributePredicateInt = new AttributePredicate<>(attributeName, attributeValueInt); Assert.assertEquals("Actual and expected values are not the same!", attributeName, attributePredicateInt.getAttributeName()); Assert.assertEquals("Actual and expected values are not the same!", attributeValueInt, attributePredicateInt.getAttributeValue()); Double attributeValueDouble = 123.23d; - AttributePredicateImpl attributePredicateDouble = new AttributePredicateImpl<>(attributeName, attributeValueDouble); + AttributePredicate attributePredicateDouble = new AttributePredicate<>(attributeName, attributeValueDouble); Assert.assertEquals("Actual and expected values are not the same!", attributeName, attributePredicateDouble.getAttributeName()); Assert.assertEquals("Actual and expected values are not the same!", attributeValueDouble, attributePredicateDouble.getAttributeValue()); Character attributeValueChar = 'a'; - AttributePredicateImpl attributePredicateChar = new AttributePredicateImpl<>(attributeName, attributeValueChar); + AttributePredicate attributePredicateChar = new AttributePredicate<>(attributeName, attributeValueChar); Assert.assertEquals("Actual and expected values are not the same!", attributeName, attributePredicateChar.getAttributeName()); Assert.assertEquals("Actual and expected values are not the same!", attributeValueChar, attributePredicateChar.getAttributeValue()); Long attributeValueLong = 12345678910L; - AttributePredicateImpl attributePredicateLong = new AttributePredicateImpl<>(attributeName, attributeValueLong); + AttributePredicate attributePredicateLong = new AttributePredicate<>(attributeName, attributeValueLong); Assert.assertEquals("Actual and expected values are not the same!", attributeName, attributePredicateLong.getAttributeName()); Assert.assertEquals("Actual and expected values are not the same!", attributeValueLong, attributePredicateLong.getAttributeValue()); - AttributePredicateImpl attributePredicateBooleanTrue = new AttributePredicateImpl<>(attributeName, true); + AttributePredicate attributePredicateBooleanTrue = new AttributePredicate<>(attributeName, true); Assert.assertEquals("Actual and expected values are not the same!", attributeName, attributePredicateBooleanTrue.getAttributeName()); Assert.assertEquals("Actual and expected values are not the same!", true, attributePredicateBooleanTrue.getAttributeValue()); - AttributePredicateImpl attributePredicateBooleanFalse = new AttributePredicateImpl<>(attributeName, false); + AttributePredicate attributePredicateBooleanFalse = new AttributePredicate<>(attributeName, false); Assert.assertEquals("Actual and expected values are not the same!", attributeName, attributePredicateBooleanFalse.getAttributeName()); Assert.assertEquals("Actual and expected values are not the same!", false, attributePredicateBooleanFalse.getAttributeValue()); Short attributeValueShort = Short.MAX_VALUE; - AttributePredicateImpl attributePredicateShort = new AttributePredicateImpl<>(attributeName, attributeValueShort); + AttributePredicate attributePredicateShort = new AttributePredicate<>(attributeName, attributeValueShort); Assert.assertEquals("Actual and expected values are not the same!", attributeName, attributePredicateShort.getAttributeName()); Assert.assertEquals("Actual and expected values are not the same!", attributeValueShort, attributePredicateShort.getAttributeValue()); Float attributeValueFloat = 123.23f; - AttributePredicateImpl attributePredicateFloat = new AttributePredicateImpl<>(attributeName, attributeValueFloat); + AttributePredicate attributePredicateFloat = new AttributePredicate<>(attributeName, attributeValueFloat); Assert.assertEquals("Actual and expected values are not the same!", attributeName, attributePredicateFloat.getAttributeName()); Assert.assertEquals("Actual and expected values are not the same!", attributeValueFloat, attributePredicateFloat.getAttributeValue()); } @Test public void getOperatorTest() { - AttributePredicate attributePredicate = new AttributePredicateImpl<>(attributeName, 1234567890, operator); + AttributePredicate attributePredicate = new AttributePredicate<>(attributeName, 1234567890, operator); Assert.assertEquals("Actual and expected values are not the same!", operator, attributePredicate.getOperator()); } } diff --git a/commons/src/test/java/org/eclipse/kapua/commons/model/query/predicate/OrPredicateImplTest.java b/commons/src/test/java/org/eclipse/kapua/commons/model/query/predicate/OrPredicateTest.java similarity index 68% rename from commons/src/test/java/org/eclipse/kapua/commons/model/query/predicate/OrPredicateImplTest.java rename to commons/src/test/java/org/eclipse/kapua/commons/model/query/predicate/OrPredicateTest.java index 87bc1c4aa5d..61d5d7920d8 100644 --- a/commons/src/test/java/org/eclipse/kapua/commons/model/query/predicate/OrPredicateImplTest.java +++ b/commons/src/test/java/org/eclipse/kapua/commons/model/query/predicate/OrPredicateTest.java @@ -12,37 +12,37 @@ *******************************************************************************/ package org.eclipse.kapua.commons.model.query.predicate; +import java.util.ArrayList; + +import org.eclipse.kapua.model.query.predicate.OrPredicate; import org.eclipse.kapua.model.query.predicate.QueryPredicate; import org.eclipse.kapua.qa.markers.junit.JUnitTests; import org.junit.Assert; import org.junit.Test; import org.junit.experimental.categories.Category; -import java.util.ArrayList; - - @Category(JUnitTests.class) -public class OrPredicateImplTest { +public class OrPredicateTest { @Test public void orPredicateImplGetPredicateTest() { - OrPredicateImpl orPredicate = new OrPredicateImpl(); + OrPredicate orPredicate = new OrPredicate(); ArrayList array = new ArrayList<>(); Assert.assertEquals("Actual and expected values are not the same!", array, orPredicate.getPredicates()); } @Test(expected = NullPointerException.class) public void orPredicateImplQueryPredicateId() { - OrPredicateImpl orPredicateNull = new OrPredicateImpl(null); + OrPredicate orPredicateNull = new OrPredicate(null); Assert.assertNull(orPredicateNull.getPredicates().get(0)); - QueryPredicate queryPredicate = new OrPredicateImpl(); - OrPredicateImpl orPredicate = new OrPredicateImpl(queryPredicate); + QueryPredicate queryPredicate = new OrPredicate(); + OrPredicate orPredicate = new OrPredicate(queryPredicate); Assert.assertEquals("Actual and expected values are not the same!", queryPredicate, orPredicate.getPredicates().get(0)); - QueryPredicate queryPredicate1 = new OrPredicateImpl(); - QueryPredicate queryPredicate2 = new OrPredicateImpl(); - QueryPredicate queryPredicate3 = new OrPredicateImpl(); - QueryPredicate[] array = {queryPredicate1, queryPredicate2, queryPredicate3}; - OrPredicateImpl orPredicateWithMultiplePredicates = new OrPredicateImpl(queryPredicate1, queryPredicate2, queryPredicate3); + QueryPredicate queryPredicate1 = new OrPredicate(); + QueryPredicate queryPredicate2 = new OrPredicate(); + QueryPredicate queryPredicate3 = new OrPredicate(); + QueryPredicate[] array = { queryPredicate1, queryPredicate2, queryPredicate3 }; + OrPredicate orPredicateWithMultiplePredicates = new OrPredicate(queryPredicate1, queryPredicate2, queryPredicate3); for (int i = 0; i < array.length; i++) { Assert.assertEquals("Actual and expected values are not the same!", array[i], orPredicateWithMultiplePredicates.getPredicates().get(i)); } @@ -50,15 +50,15 @@ public void orPredicateImplQueryPredicateId() { @Test public void orTest() { - OrPredicateImpl orPredicate = new OrPredicateImpl(); - QueryPredicate queryPredicate = new OrPredicateImpl(); + OrPredicate orPredicate = new OrPredicate(); + QueryPredicate queryPredicate = new OrPredicate(); orPredicate.or(queryPredicate); Assert.assertEquals("Actual and expected values are not the same!", queryPredicate, orPredicate.getPredicates().get(0)); } @Test public void orWithNullPredicateTest() { - OrPredicateImpl orPredicate = new OrPredicateImpl(); + OrPredicate orPredicate = new OrPredicate(); orPredicate.or(null); Assert.assertNull(orPredicate.getPredicates().get(0)); } diff --git a/commons/src/test/java/org/eclipse/kapua/commons/service/event/store/internal/EventStoreFactoryImplTest.java b/commons/src/test/java/org/eclipse/kapua/commons/service/event/store/internal/EventStoreFactoryImplTest.java index 23379802a93..1faf50064fd 100644 --- a/commons/src/test/java/org/eclipse/kapua/commons/service/event/store/internal/EventStoreFactoryImplTest.java +++ b/commons/src/test/java/org/eclipse/kapua/commons/service/event/store/internal/EventStoreFactoryImplTest.java @@ -12,11 +12,12 @@ *******************************************************************************/ package org.eclipse.kapua.commons.service.event.store.internal; +import java.math.BigInteger; + import org.eclipse.kapua.KapuaEntityCloneException; import org.eclipse.kapua.commons.model.id.KapuaEid; import org.eclipse.kapua.commons.service.event.store.api.EventStoreRecord; import org.eclipse.kapua.model.id.KapuaId; - import org.eclipse.kapua.qa.markers.junit.JUnitTests; import org.hamcrest.core.IsInstanceOf; import org.junit.Assert; @@ -24,53 +25,20 @@ import org.junit.experimental.categories.Category; import org.mockito.Mockito; -import java.math.BigInteger; - - @Category(JUnitTests.class) public class EventStoreFactoryImplTest { @Test public void newEntityTest() { EventStoreFactoryImpl eventStoreFactoryImpl = new EventStoreFactoryImpl(); - KapuaId[] scopeIdList = {null, new KapuaEid(BigInteger.ONE)}; + KapuaId[] scopeIdList = { null, new KapuaEid(BigInteger.ONE) }; for (KapuaId scopeId : scopeIdList) { Assert.assertNotNull("Null not expected.", eventStoreFactoryImpl.newEntity(scopeId)); - Assert.assertThat("EventStoreRecordImpl object expected.", eventStoreFactoryImpl.newEntity(scopeId), IsInstanceOf.instanceOf(EventStoreRecordImpl.class)); - } - } - - @Test - public void newCreatorTest() { - EventStoreFactoryImpl eventStoreFactoryImpl = new EventStoreFactoryImpl(); - KapuaId[] scopeIdList = {null, new KapuaEid(BigInteger.ONE)}; - - for (KapuaId scopeId : scopeIdList) { - Assert.assertNotNull("Null not expected.", eventStoreFactoryImpl.newCreator(scopeId)); - Assert.assertThat("EventStoreRecordImpl object expected.", eventStoreFactoryImpl.newCreator(scopeId), IsInstanceOf.instanceOf(EventStoreRecordCreatorImpl.class)); + Assert.assertThat("EventStoreRecordImpl object expected.", eventStoreFactoryImpl.newEntity(scopeId), IsInstanceOf.instanceOf(EventStoreRecordImpl.class)); } } - @Test - public void newQueryTest() { - EventStoreFactoryImpl eventStoreFactoryImpl = new EventStoreFactoryImpl(); - KapuaId[] scopeIdList = {null, new KapuaEid(BigInteger.ONE)}; - - for (KapuaId scopeId : scopeIdList) { - Assert.assertNotNull("Null not expected.", eventStoreFactoryImpl.newQuery(scopeId)); - Assert.assertThat("EventStoreQueryImpl object expected.", eventStoreFactoryImpl.newQuery(scopeId), IsInstanceOf.instanceOf(EventStoreQueryImpl.class)); - } - } - - @Test - public void newListResultTest() { - EventStoreFactoryImpl eventStoreFactoryImpl = new EventStoreFactoryImpl(); - - Assert.assertNotNull("Null not expected.", eventStoreFactoryImpl.newListResult()); - Assert.assertThat("EventStoreRecordListResultImpl object expected.", eventStoreFactoryImpl.newListResult(), IsInstanceOf.instanceOf(EventStoreRecordListResultImpl.class)); - } - @Test public void cloneTest() { EventStoreFactoryImpl eventStoreFactoryImpl = new EventStoreFactoryImpl(); diff --git a/commons/src/test/java/org/eclipse/kapua/commons/service/event/store/internal/EventStoreQueryImplTest.java b/commons/src/test/java/org/eclipse/kapua/commons/service/event/store/internal/EventStoreQueryImplTest.java deleted file mode 100644 index 4f5eaefa8bc..00000000000 --- a/commons/src/test/java/org/eclipse/kapua/commons/service/event/store/internal/EventStoreQueryImplTest.java +++ /dev/null @@ -1,49 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2020, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.commons.service.event.store.internal; - -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.model.id.KapuaIdImpl; -import org.eclipse.kapua.qa.markers.junit.JUnitTests; -import org.junit.Assert; -import org.junit.Test; -import org.junit.experimental.categories.Category; - -import java.math.BigInteger; - - -@Category(JUnitTests.class) -public class EventStoreQueryImplTest { - - @Test - public void eventStoreQueryImplTest1() { - EventStoreQueryImpl eventStoreQueryImpl = new EventStoreQueryImpl(); - Assert.assertNull("query.sortCriteria", eventStoreQueryImpl.getSortCriteria()); - Assert.assertNotNull("query.defaultSortCriteria", eventStoreQueryImpl.getDefaultSortCriteria()); - } - - @Test - public void eventStoreQueryImplTest2() { - KapuaId scopeId = new KapuaIdImpl(BigInteger.ONE); - - EventStoreQueryImpl eventStoreQueryImpl1 = new EventStoreQueryImpl(null); - Assert.assertNull("query.sortCriteria", eventStoreQueryImpl1.getSortCriteria()); - Assert.assertNotNull("query.defaultSortCriteria", eventStoreQueryImpl1.getDefaultSortCriteria()); - Assert.assertNull("Null expected.", eventStoreQueryImpl1.getScopeId()); - - EventStoreQueryImpl eventStoreQueryImpl2 = new EventStoreQueryImpl(scopeId); - Assert.assertNull("query.sortCriteria", eventStoreQueryImpl2.getSortCriteria()); - Assert.assertNotNull("query.defaultSortCriteria", eventStoreQueryImpl2.getDefaultSortCriteria()); - Assert.assertEquals("Expected and actual values should be the same.", scopeId, eventStoreQueryImpl2.getScopeId()); - } -} diff --git a/commons/src/test/java/org/eclipse/kapua/commons/service/event/store/internal/EventStoreRecordCreatorImplTest.java b/commons/src/test/java/org/eclipse/kapua/commons/service/event/store/internal/EventStoreRecordCreatorTest.java similarity index 79% rename from commons/src/test/java/org/eclipse/kapua/commons/service/event/store/internal/EventStoreRecordCreatorImplTest.java rename to commons/src/test/java/org/eclipse/kapua/commons/service/event/store/internal/EventStoreRecordCreatorTest.java index a4cfc72bcfc..be05ad60276 100644 --- a/commons/src/test/java/org/eclipse/kapua/commons/service/event/store/internal/EventStoreRecordCreatorImplTest.java +++ b/commons/src/test/java/org/eclipse/kapua/commons/service/event/store/internal/EventStoreRecordCreatorTest.java @@ -12,6 +12,9 @@ *******************************************************************************/ package org.eclipse.kapua.commons.service.event.store.internal; +import java.math.BigInteger; + +import org.eclipse.kapua.commons.service.event.store.api.EventStoreRecordCreator; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.model.id.KapuaIdImpl; import org.eclipse.kapua.qa.markers.junit.JUnitTests; @@ -19,17 +22,15 @@ import org.junit.Test; import org.junit.experimental.categories.Category; -import java.math.BigInteger; - - @Category(JUnitTests.class) -public class EventStoreRecordCreatorImplTest { +public class EventStoreRecordCreatorTest { + @Test public void eventStoreRecordCreatorImplTest() { - KapuaId[] scopeIdList = {null, new KapuaIdImpl(BigInteger.ONE)}; + KapuaId[] scopeIdList = { null, new KapuaIdImpl(BigInteger.ONE) }; for (KapuaId scopeId : scopeIdList) { - EventStoreRecordCreatorImpl eventStoreRecordCreatorImpl = new EventStoreRecordCreatorImpl(scopeId); + EventStoreRecordCreator eventStoreRecordCreatorImpl = new EventStoreRecordCreator(scopeId); Assert.assertEquals("Expected and actual values should be the same.", scopeId, eventStoreRecordCreatorImpl.getScopeId()); } } diff --git a/commons/src/test/java/org/eclipse/kapua/commons/service/internal/cache/EntityCacheTest.java b/commons/src/test/java/org/eclipse/kapua/commons/service/internal/cache/EntityCacheTest.java index 98a1e6ecd29..45cd082a67a 100644 --- a/commons/src/test/java/org/eclipse/kapua/commons/service/internal/cache/EntityCacheTest.java +++ b/commons/src/test/java/org/eclipse/kapua/commons/service/internal/cache/EntityCacheTest.java @@ -15,265 +15,264 @@ import org.eclipse.kapua.qa.markers.junit.JUnitTests; import org.junit.experimental.categories.Category; - @Category(JUnitTests.class) public class EntityCacheTest { //TODO: FIXME: PRIORITY: rewrite -// @Before -// public void setFakeLocator() { -// System.setProperty(org.eclipse.kapua.locator.KapuaLocator.LOCATOR_CLASS_NAME_SYSTEM_PROPERTY, MockitoLocator.class.getName()); -// } -// -// @Test -// public void entityCacheTest() { -// String idCacheName = "idCacheName"; -// Cache expectedIdCache = StaticKapuaCacheManager.getCache(idCacheName); -// Cache expectedListsCache = StaticKapuaCacheManager.getCache(idCacheName + "_list"); -// //non sense! test to be removed or at least refactored! -//// Counter expectedCacheMiss = MetricServiceFactory.getInstance().getCounter("commons", "cache", "entity", "miss", "count"); -//// Counter expectedCacheHit = MetricServiceFactory.getInstance().getCounter("commons", "cache", "entity", "hit", "count"); -//// Counter expectedCacheRemoval = MetricServiceFactory.getInstance().getCounter("commons", "cache", "entity", "removal", "count"); -// NullPointerException nullPointerException = new NullPointerException(); -// -// EntityCache entityCache = new EntityCache(idCacheName); -// Assert.assertEquals(expectedIdCache, entityCache.idCache); -// Assert.assertEquals(expectedListsCache, entityCache.listsCache); -// //non sense! test to be removed or at least refactored! -//// Assert.assertEquals(expectedCacheMiss, entityCache.cacheMiss); -//// Assert.assertEquals(expectedCacheHit, entityCache.cacheHit); -//// Assert.assertEquals(expectedCacheRemoval, entityCache.cacheRemoval); -// -// try { -// EntityCache invalidEntityCache = new EntityCache(null); -// } catch (Exception e) { -// Assert.assertEquals("NullPointerException expected", nullPointerException.toString(), e.toString()); -// } -// } -// -// @Test -// public void getTest() { -// String idCacheName = "idCacheName"; -// EntityCache entityCache = new EntityCache(idCacheName); -// KapuaId scopeId = new KapuaIdImpl(BigInteger.ONE); -// KapuaId kapuaId = new KapuaIdImpl(BigInteger.TEN); -// -// //COMMENT: Entity is always null (see Cache.get() method) -// // Due to that reason the following part of code could not be tested in EntityCache.java: -// // else { -// // cacheHit.inc(); -// // } -// //and this method always returns null -// Assert.assertNull("Null expected", entityCache.get(scopeId, kapuaId)); -// Assert.assertNull("Null expected", entityCache.get(null, kapuaId)); -// Assert.assertNull("Null expected", entityCache.get(scopeId, null)); -// Assert.assertNull("Null expected", entityCache.get(null, null)); -// -// // COMMENT: Once the get() method will be changed, -// // we will be able to test other results also. -// } -// -// @Test -// public void getListTest() { -// String idCacheName = "idCacheName"; -// EntityCache entityCache = new EntityCache(idCacheName); -// KapuaId scopeId = new KapuaIdImpl(BigInteger.ONE); -// KapuaId scopeId1 = new KapuaIdImpl(BigInteger.TEN); -// Serializable key = new ComposedKey(scopeId1, null); -// Serializable id = new ComposedKey(scopeId1, key); -// -// //COMMENT: This method always returns null, because entity is always null (see Cache.get() method) -// Assert.assertNull("Null expected", entityCache.getList(scopeId, id)); -// Assert.assertNull("Null expected", entityCache.getList(null, id)); -// Assert.assertNull("Null expected", entityCache.getList(null, null)); -// Assert.assertNull("Null expected", entityCache.getList(scopeId, null)); -// -// // COMMENT: Once the get() method will be changed, -// // we will be able to test other results also. -// } -// -// @Test -// public void putTest() { -// EntityCache entityCache1 = new EntityCache("IdCacheName"); -// EntityCache entityCache2 = new EntityCache("Id Cache Name"); -// KapuaId scopeId = new KapuaIdImpl(BigInteger.ONE); -// KapuaId kapuaId = new KapuaIdImpl(BigInteger.TEN); -// KapuaEntity kapuaEntity = entityCache2.get(scopeId, kapuaId); -// -// //COMMENT: kapuaEntity is always null (see Cache.get() method) -// // Due to that reason the following part of code could not be tested in EntityCache.java: -// // if (entity != null) { -// // idCache.put(entity.getId(), entity); -// // } -// -// entityCache1.put(kapuaEntity); -// -// // COMMENT: Once the get() method will be changed, -// // we will be able to test other results also. -// } -// -// @Test -// public void putListTest() { -// String idCacheName = "IdCacheName"; -// EntityCache entityCache = new EntityCache(idCacheName); -// KapuaId[] scopeIds = {null, new KapuaIdImpl(BigInteger.ONE)}; -// KapuaId scopeId1 = new KapuaIdImpl(BigInteger.ONE); -// Serializable key = new ComposedKey(scopeId1, null); -// Serializable[] ids = {null, new ComposedKey(scopeId1, key)}; -// KapuaListResult list = new KapuaListResultImpl<>(); -// -// for (KapuaId scopeId : scopeIds) { -// for (Serializable id : ids) { -// entityCache.putList(scopeId, id, list); -// entityCache.putList(scopeId, id, null); -// } -// } -// -// //COMMENT: this method calls Cache.put(Object key, Object value) method, -// // which has empty body. -// //Once the put(Object key, Object value) method will be changed, -// // we will be able to test assertions. -// } -// -// @Test -// public void removeWithKapuaEntityTest() { -// EntityCache entityCache = new EntityCache("IdCacheName"); -// KapuaId scopeId = new KapuaIdImpl(BigInteger.ONE); -// EntityCache entityCache2 = new EntityCache("Id Cache Name"); -// KapuaId scopeId1 = new KapuaIdImpl(BigInteger.ONE); -// KapuaId kapuaId1 = new KapuaIdImpl(BigInteger.TEN); -// KapuaEntity kapuaEntity = entityCache2.get(scopeId1, kapuaId1); -// NullPointerException nullPointerException = new NullPointerException(); -// -// //COMMENT: kapuaEntity is always null (see Cache.get() method) -// // Due to that reason entity.getId() always gives NullPointerException in EntityCache.java -// -// try { -// entityCache.remove(scopeId, kapuaEntity); -// } catch (Exception e) { -// Assert.assertEquals("NullPointerException expected", nullPointerException.toString(), e.toString()); -// } -// -// try { -// entityCache.remove(null, kapuaEntity); -// } catch (Exception e) { -// Assert.assertEquals("NullPointerException expected", nullPointerException.toString(), e.toString()); -// } -// } -// -// @Test -// public void removeTest() { -// EntityCache entityCache = new EntityCache("IdCacheName"); -// KapuaId scopeId = new KapuaIdImpl(BigInteger.ONE); -// KapuaId kapuaId = new KapuaIdImpl(BigInteger.TEN); -// KapuaId nullKapuaId = null; -// -// //COMMENT: Entity is always null (see Cache.get() method) -// // Due to that reason the following part of code could not be tested in EntityCache.java: -// //if (entity != null) { -// //idCache.remove(kapuaId); -// // cacheRemoval.inc(); -// //return entity; -// //} -// // and this method always returns null -// Assert.assertNull("Null expected", entityCache.remove(scopeId, kapuaId)); -// Assert.assertNull("Null expected", entityCache.remove(null, kapuaId)); -// Assert.assertNull("Null expected", entityCache.remove(scopeId, nullKapuaId)); -// Assert.assertNull("Null expected", entityCache.remove(null, nullKapuaId)); -// -// // COMMENT: Once the get() method will be changed, -// // we will be able to test other results also. -// } -// -// @Test -// public void removeListTest() { -// EntityCache entityCache = new EntityCache("IdCacheName"); -// KapuaId scopeId = new KapuaIdImpl(BigInteger.ONE); -// KapuaId scopeId1 = new KapuaIdImpl(BigInteger.ONE); -// Serializable key = new ComposedKey(scopeId1, null); -// Serializable id = new ComposedKey(scopeId1, key); -// -// //COMMENT: Entity is always null (see Cache.get() method) -// // Due to that reason the following part of code could not be tested in EntityCache.java: -// //if (entity != null) { -// //listsCache.remove(new ComposedKey(scopeId, id)); -// //return entity; -// //} -// // and this method always returns null -// Assert.assertNull("Null expected", entityCache.removeList(scopeId, id)); -// Assert.assertNull("Null expected", entityCache.removeList(null, id)); -// Assert.assertNull("Null expected", entityCache.removeList(scopeId, null)); -// Assert.assertNull("Null expected", entityCache.removeList(null, null)); -// -// // COMMENT: Once the get() method will be changed, -// // we will be able to test other results also. -// } -// -// @Test -// public void checkResultTest() { -// EntityCache entityCache1 = new EntityCache("idCacheName"); -// KapuaId scopeId = new KapuaIdImpl(BigInteger.ONE); -// EntityCache entityCache2 = new EntityCache("idCacheName2"); -// KapuaId kapuaId = new KapuaIdImpl(BigInteger.TEN); -// KapuaEntity kapuaEntity = entityCache2.get(scopeId, kapuaId); -// KapuaEntity kapuaNullEntity = null; -// -// //COMMENT: Entity is always null (see Cache.get() method) -// // Due to that reason the following part of code could not be tested in EntityCache.java: -// //if (entity != null) { -// // if (scopeId == null) { -// // return entity; -// // } else if (entity.getScopeId() == null) { -// // return entity; -// // } else if (entity.getScopeId().equals(scopeId)) { -// // return entity; -// // } else { -// // return null; -// // } -// //and this method always returns null -// Assert.assertNull("Null expected", entityCache1.checkResult(scopeId, kapuaEntity)); -// Assert.assertNull("Null expected", entityCache1.checkResult(null, kapuaEntity)); -// Assert.assertNull("Null expected", entityCache1.checkResult(scopeId, kapuaNullEntity)); -// Assert.assertNull("Null expected", entityCache1.checkResult(null, kapuaNullEntity)); -// -// // COMMENT: Once the get() method will be changed, -// // we will be able to test other results also. -// } -// -// @Test -// public void checkResultListTest() { -// KapuaListResult kapuaNullListResult = null; -// EntityCache entityCache = new EntityCache("idCacheName"); -// KapuaListResult kapuaListResult = new KapuaListResultImpl<>(); -// KapuaId scopeId = new KapuaIdImpl(BigInteger.ONE); -// EntityCache entityCache2 = new EntityCache("idCacheName2"); -// KapuaId scopeId1 = new KapuaIdImpl(BigInteger.ONE); -// KapuaId kapuaId = new KapuaIdImpl(BigInteger.TEN); -// KapuaEntity kapuaEntity = entityCache2.get(scopeId1, kapuaId); -// NullPointerException nullPointerException = new NullPointerException(); -// -// //COMMENT: entity.getFirstItem().getScopeId() returns nullPointerException, because entity is always null (see Cache.get() method) -// // Due to that reason the following part of code could not be tested in EntityCache.java: -// // else if (entity.getFirstItem().getScopeId() == null) { -// //return entity; -// //} else if (entity.getFirstItem().getScopeId().equals(scopeId)) { -// //return entity; -// //} else { -// //return null; -// //} -// -// Assert.assertNull("Null expected", entityCache.checkResult(scopeId, kapuaNullListResult)); -// Assert.assertEquals(kapuaListResult, entityCache.checkResult(scopeId, kapuaListResult)); -// kapuaListResult.addItem(kapuaEntity); -// Assert.assertEquals(kapuaListResult, entityCache.checkResult(null, kapuaListResult)); -// -// try { -// Assert.assertEquals(kapuaListResult, entityCache.checkResult(scopeId, kapuaListResult)); -// } catch (Exception e) { -// Assert.assertEquals("NullPointerException expected", nullPointerException.toString(), e.toString()); -// } -// -// // COMMENT: Once the get() method will be changed, -// // we will be able to test other results also. -// } + // @Before + // public void setFakeLocator() { + // System.setProperty(org.eclipse.kapua.locator.KapuaLocator.LOCATOR_CLASS_NAME_SYSTEM_PROPERTY, MockitoLocator.class.getName()); + // } + // + // @Test + // public void entityCacheTest() { + // String idCacheName = "idCacheName"; + // Cache expectedIdCache = StaticKapuaCacheManager.getCache(idCacheName); + // Cache expectedListsCache = StaticKapuaCacheManager.getCache(idCacheName + "_list"); + // //non sense! test to be removed or at least refactored! + //// Counter expectedCacheMiss = MetricServiceFactory.getInstance().getCounter("commons", "cache", "entity", "miss", "count"); + //// Counter expectedCacheHit = MetricServiceFactory.getInstance().getCounter("commons", "cache", "entity", "hit", "count"); + //// Counter expectedCacheRemoval = MetricServiceFactory.getInstance().getCounter("commons", "cache", "entity", "removal", "count"); + // NullPointerException nullPointerException = new NullPointerException(); + // + // EntityCache entityCache = new EntityCache(idCacheName); + // Assert.assertEquals(expectedIdCache, entityCache.idCache); + // Assert.assertEquals(expectedListsCache, entityCache.listsCache); + // //non sense! test to be removed or at least refactored! + //// Assert.assertEquals(expectedCacheMiss, entityCache.cacheMiss); + //// Assert.assertEquals(expectedCacheHit, entityCache.cacheHit); + //// Assert.assertEquals(expectedCacheRemoval, entityCache.cacheRemoval); + // + // try { + // EntityCache invalidEntityCache = new EntityCache(null); + // } catch (Exception e) { + // Assert.assertEquals("NullPointerException expected", nullPointerException.toString(), e.toString()); + // } + // } + // + // @Test + // public void getTest() { + // String idCacheName = "idCacheName"; + // EntityCache entityCache = new EntityCache(idCacheName); + // KapuaId scopeId = new KapuaIdImpl(BigInteger.ONE); + // KapuaId kapuaId = new KapuaIdImpl(BigInteger.TEN); + // + // //COMMENT: Entity is always null (see Cache.get() method) + // // Due to that reason the following part of code could not be tested in EntityCache.java: + // // else { + // // cacheHit.inc(); + // // } + // //and this method always returns null + // Assert.assertNull("Null expected", entityCache.get(scopeId, kapuaId)); + // Assert.assertNull("Null expected", entityCache.get(null, kapuaId)); + // Assert.assertNull("Null expected", entityCache.get(scopeId, null)); + // Assert.assertNull("Null expected", entityCache.get(null, null)); + // + // // COMMENT: Once the get() method will be changed, + // // we will be able to test other results also. + // } + // + // @Test + // public void getListTest() { + // String idCacheName = "idCacheName"; + // EntityCache entityCache = new EntityCache(idCacheName); + // KapuaId scopeId = new KapuaIdImpl(BigInteger.ONE); + // KapuaId scopeId1 = new KapuaIdImpl(BigInteger.TEN); + // Serializable key = new ComposedKey(scopeId1, null); + // Serializable id = new ComposedKey(scopeId1, key); + // + // //COMMENT: This method always returns null, because entity is always null (see Cache.get() method) + // Assert.assertNull("Null expected", entityCache.getList(scopeId, id)); + // Assert.assertNull("Null expected", entityCache.getList(null, id)); + // Assert.assertNull("Null expected", entityCache.getList(null, null)); + // Assert.assertNull("Null expected", entityCache.getList(scopeId, null)); + // + // // COMMENT: Once the get() method will be changed, + // // we will be able to test other results also. + // } + // + // @Test + // public void putTest() { + // EntityCache entityCache1 = new EntityCache("IdCacheName"); + // EntityCache entityCache2 = new EntityCache("Id Cache Name"); + // KapuaId scopeId = new KapuaIdImpl(BigInteger.ONE); + // KapuaId kapuaId = new KapuaIdImpl(BigInteger.TEN); + // KapuaEntity kapuaEntity = entityCache2.get(scopeId, kapuaId); + // + // //COMMENT: kapuaEntity is always null (see Cache.get() method) + // // Due to that reason the following part of code could not be tested in EntityCache.java: + // // if (entity != null) { + // // idCache.put(entity.getId(), entity); + // // } + // + // entityCache1.put(kapuaEntity); + // + // // COMMENT: Once the get() method will be changed, + // // we will be able to test other results also. + // } + // + // @Test + // public void putListTest() { + // String idCacheName = "IdCacheName"; + // EntityCache entityCache = new EntityCache(idCacheName); + // KapuaId[] scopeIds = {null, new KapuaIdImpl(BigInteger.ONE)}; + // KapuaId scopeId1 = new KapuaIdImpl(BigInteger.ONE); + // Serializable key = new ComposedKey(scopeId1, null); + // Serializable[] ids = {null, new ComposedKey(scopeId1, key)}; + // KapuaListResult list = new KapuaListResult<>(); + // + // for (KapuaId scopeId : scopeIds) { + // for (Serializable id : ids) { + // entityCache.putList(scopeId, id, list); + // entityCache.putList(scopeId, id, null); + // } + // } + // + // //COMMENT: this method calls Cache.put(Object key, Object value) method, + // // which has empty body. + // //Once the put(Object key, Object value) method will be changed, + // // we will be able to test assertions. + // } + // + // @Test + // public void removeWithKapuaEntityTest() { + // EntityCache entityCache = new EntityCache("IdCacheName"); + // KapuaId scopeId = new KapuaIdImpl(BigInteger.ONE); + // EntityCache entityCache2 = new EntityCache("Id Cache Name"); + // KapuaId scopeId1 = new KapuaIdImpl(BigInteger.ONE); + // KapuaId kapuaId1 = new KapuaIdImpl(BigInteger.TEN); + // KapuaEntity kapuaEntity = entityCache2.get(scopeId1, kapuaId1); + // NullPointerException nullPointerException = new NullPointerException(); + // + // //COMMENT: kapuaEntity is always null (see Cache.get() method) + // // Due to that reason entity.getId() always gives NullPointerException in EntityCache.java + // + // try { + // entityCache.remove(scopeId, kapuaEntity); + // } catch (Exception e) { + // Assert.assertEquals("NullPointerException expected", nullPointerException.toString(), e.toString()); + // } + // + // try { + // entityCache.remove(null, kapuaEntity); + // } catch (Exception e) { + // Assert.assertEquals("NullPointerException expected", nullPointerException.toString(), e.toString()); + // } + // } + // + // @Test + // public void removeTest() { + // EntityCache entityCache = new EntityCache("IdCacheName"); + // KapuaId scopeId = new KapuaIdImpl(BigInteger.ONE); + // KapuaId kapuaId = new KapuaIdImpl(BigInteger.TEN); + // KapuaId nullKapuaId = null; + // + // //COMMENT: Entity is always null (see Cache.get() method) + // // Due to that reason the following part of code could not be tested in EntityCache.java: + // //if (entity != null) { + // //idCache.remove(kapuaId); + // // cacheRemoval.inc(); + // //return entity; + // //} + // // and this method always returns null + // Assert.assertNull("Null expected", entityCache.remove(scopeId, kapuaId)); + // Assert.assertNull("Null expected", entityCache.remove(null, kapuaId)); + // Assert.assertNull("Null expected", entityCache.remove(scopeId, nullKapuaId)); + // Assert.assertNull("Null expected", entityCache.remove(null, nullKapuaId)); + // + // // COMMENT: Once the get() method will be changed, + // // we will be able to test other results also. + // } + // + // @Test + // public void removeListTest() { + // EntityCache entityCache = new EntityCache("IdCacheName"); + // KapuaId scopeId = new KapuaIdImpl(BigInteger.ONE); + // KapuaId scopeId1 = new KapuaIdImpl(BigInteger.ONE); + // Serializable key = new ComposedKey(scopeId1, null); + // Serializable id = new ComposedKey(scopeId1, key); + // + // //COMMENT: Entity is always null (see Cache.get() method) + // // Due to that reason the following part of code could not be tested in EntityCache.java: + // //if (entity != null) { + // //listsCache.remove(new ComposedKey(scopeId, id)); + // //return entity; + // //} + // // and this method always returns null + // Assert.assertNull("Null expected", entityCache.removeList(scopeId, id)); + // Assert.assertNull("Null expected", entityCache.removeList(null, id)); + // Assert.assertNull("Null expected", entityCache.removeList(scopeId, null)); + // Assert.assertNull("Null expected", entityCache.removeList(null, null)); + // + // // COMMENT: Once the get() method will be changed, + // // we will be able to test other results also. + // } + // + // @Test + // public void checkResultTest() { + // EntityCache entityCache1 = new EntityCache("idCacheName"); + // KapuaId scopeId = new KapuaIdImpl(BigInteger.ONE); + // EntityCache entityCache2 = new EntityCache("idCacheName2"); + // KapuaId kapuaId = new KapuaIdImpl(BigInteger.TEN); + // KapuaEntity kapuaEntity = entityCache2.get(scopeId, kapuaId); + // KapuaEntity kapuaNullEntity = null; + // + // //COMMENT: Entity is always null (see Cache.get() method) + // // Due to that reason the following part of code could not be tested in EntityCache.java: + // //if (entity != null) { + // // if (scopeId == null) { + // // return entity; + // // } else if (entity.getScopeId() == null) { + // // return entity; + // // } else if (entity.getScopeId().equals(scopeId)) { + // // return entity; + // // } else { + // // return null; + // // } + // //and this method always returns null + // Assert.assertNull("Null expected", entityCache1.checkResult(scopeId, kapuaEntity)); + // Assert.assertNull("Null expected", entityCache1.checkResult(null, kapuaEntity)); + // Assert.assertNull("Null expected", entityCache1.checkResult(scopeId, kapuaNullEntity)); + // Assert.assertNull("Null expected", entityCache1.checkResult(null, kapuaNullEntity)); + // + // // COMMENT: Once the get() method will be changed, + // // we will be able to test other results also. + // } + // + // @Test + // public void checkResultListTest() { + // KapuaListResult kapuaNullListResult = null; + // EntityCache entityCache = new EntityCache("idCacheName"); + // KapuaListResult kapuaListResult = new KapuaListResultImpl<>(); + // KapuaId scopeId = new KapuaIdImpl(BigInteger.ONE); + // EntityCache entityCache2 = new EntityCache("idCacheName2"); + // KapuaId scopeId1 = new KapuaIdImpl(BigInteger.ONE); + // KapuaId kapuaId = new KapuaIdImpl(BigInteger.TEN); + // KapuaEntity kapuaEntity = entityCache2.get(scopeId1, kapuaId); + // NullPointerException nullPointerException = new NullPointerException(); + // + // //COMMENT: entity.getFirstItem().getScopeId() returns nullPointerException, because entity is always null (see Cache.get() method) + // // Due to that reason the following part of code could not be tested in EntityCache.java: + // // else if (entity.getFirstItem().getScopeId() == null) { + // //return entity; + // //} else if (entity.getFirstItem().getScopeId().equals(scopeId)) { + // //return entity; + // //} else { + // //return null; + // //} + // + // Assert.assertNull("Null expected", entityCache.checkResult(scopeId, kapuaNullListResult)); + // Assert.assertEquals(kapuaListResult, entityCache.checkResult(scopeId, kapuaListResult)); + // kapuaListResult.addItem(kapuaEntity); + // Assert.assertEquals(kapuaListResult, entityCache.checkResult(null, kapuaListResult)); + // + // try { + // Assert.assertEquals(kapuaListResult, entityCache.checkResult(scopeId, kapuaListResult)); + // } catch (Exception e) { + // Assert.assertEquals("NullPointerException expected", nullPointerException.toString(), e.toString()); + // } + // + // // COMMENT: Once the get() method will be changed, + // // we will be able to test other results also. + // } } diff --git a/commons/src/test/java/org/eclipse/kapua/commons/util/PropertiesUtilsTest.java b/commons/src/test/java/org/eclipse/kapua/commons/util/PropertiesUtilsTest.java index dae14bfc114..453a7efa809 100644 --- a/commons/src/test/java/org/eclipse/kapua/commons/util/PropertiesUtilsTest.java +++ b/commons/src/test/java/org/eclipse/kapua/commons/util/PropertiesUtilsTest.java @@ -12,17 +12,17 @@ *******************************************************************************/ package org.eclipse.kapua.commons.util; +import java.lang.reflect.Constructor; +import java.util.Date; +import java.util.Properties; + +import org.eclipse.kapua.PropertiesUtils; import org.eclipse.kapua.qa.markers.junit.JUnitTests; import org.junit.Assert; import org.junit.ComparisonFailure; import org.junit.Test; import org.junit.experimental.categories.Category; -import java.lang.reflect.Constructor; -import java.util.Date; -import java.util.Properties; - - @Category(JUnitTests.class) public class PropertiesUtilsTest { @@ -35,8 +35,9 @@ public void testConstructor() throws Exception { @Test public void readPropertiesFromStringTest() throws Exception { - String[] inputString = new String[]{"StringString", "!string\n !string", " #string\n String=S123", " string! Strin=g ", "strin#g : string", "string str1, \\\nstr2, \\\nstr3", "string\\ String 12 34", "123\\:\\=12%#34:String", "Str\ting String", "Strin\fg=String", "string\n "}; - String[] emptyOrNullString = new String[]{null, ""}; + String[] inputString = new String[] { "StringString", "!string\n !string", " #string\n String=S123", " string! Strin=g ", "strin#g : string", + "string str1, \\\nstr2, \\\nstr3", "string\\ String 12 34", "123\\:\\=12%#34:String", "Str\ting String", "Strin\fg=String", "string\n " }; + String[] emptyOrNullString = new String[] { null, "" }; Properties prop1 = new Properties(); prop1.setProperty("StringString", ""); @@ -87,8 +88,9 @@ public void readPropertiesFromStringTest() throws Exception { Properties emptyProp2 = new Properties(); emptyProp2.setProperty("", ""); - Properties[] validPropArray = new Properties[]{prop1, prop2, prop3, prop4, prop5, prop6, prop7, prop8, prop9, prop10, prop11}; - Properties[] invalidPropArray = new Properties[]{invalidProp1, invalidProp2, invalidProp3, invalidProp4, invalidProp5, invalidProp6, invalidProp7, invalidProp8, invalidProp9, invalidProp10, invalidProp11}; + Properties[] validPropArray = new Properties[] { prop1, prop2, prop3, prop4, prop5, prop6, prop7, prop8, prop9, prop10, prop11 }; + Properties[] invalidPropArray = new Properties[] { invalidProp1, invalidProp2, invalidProp3, invalidProp4, invalidProp5, invalidProp6, invalidProp7, invalidProp8, invalidProp9, invalidProp10, + invalidProp11 }; //Positive tests for (int i = 0; i < inputString.length; i++) { @@ -156,9 +158,9 @@ public void writePropertiesToStringTest() throws Exception { String invalidString4 = "#" + new Date().toString() + lineSeparator + "st ring#a=StriNG aaa';" + lineSeparator; String invalidString5 = "#" + new Date().toString() + "\\ String=ssss12_ ;; " + lineSeparator; - String[] validOutputString = new String[]{str1, str2, str3, str4, str5}; - String[] invalidOutputString = new String[]{invalidString1, invalidString2, invalidString3, invalidString4, invalidString5}; - Properties[] propArray = new Properties[]{prop1, prop2, prop3, prop4, prop5}; + String[] validOutputString = new String[] { str1, str2, str3, str4, str5 }; + String[] invalidOutputString = new String[] { invalidString1, invalidString2, invalidString3, invalidString4, invalidString5 }; + Properties[] propArray = new Properties[] { prop1, prop2, prop3, prop4, prop5 }; //Positive tests for (int i = 0; i < propArray.length; i++) { diff --git a/console/core/pom.xml b/console/core/pom.xml index 8506e9aa00f..35a64823a7d 100644 --- a/console/core/pom.xml +++ b/console/core/pom.xml @@ -19,7 +19,7 @@ kapua-console org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-console-core diff --git a/console/core/src/main/java/org/eclipse/kapua/app/console/core/filter/KapuaWebFilter.java b/console/core/src/main/java/org/eclipse/kapua/app/console/core/filter/KapuaWebFilter.java index 906f39f31b4..5bca4f5f791 100644 --- a/console/core/src/main/java/org/eclipse/kapua/app/console/core/filter/KapuaWebFilter.java +++ b/console/core/src/main/java/org/eclipse/kapua/app/console/core/filter/KapuaWebFilter.java @@ -12,6 +12,14 @@ *******************************************************************************/ package org.eclipse.kapua.app.console.core.filter; +import java.io.IOException; +import java.util.Date; + +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; + import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.subject.Subject; @@ -21,18 +29,11 @@ import org.eclipse.kapua.commons.security.KapuaSession; import org.eclipse.kapua.locator.KapuaLocator; import org.eclipse.kapua.service.authentication.AuthenticationService; -import org.eclipse.kapua.service.authentication.CredentialsFactory; +import org.eclipse.kapua.service.authentication.shiro.AccessTokenCredentialsImpl; import org.eclipse.kapua.service.authentication.token.AccessToken; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import java.io.IOException; -import java.util.Date; - /** * {@link ShiroFilter} override. *

    @@ -45,7 +46,6 @@ public class KapuaWebFilter extends ShiroFilter { private static final Logger LOG = LoggerFactory.getLogger(KapuaWebFilter.class); private final AuthenticationService authenticationService = KapuaLocator.getInstance().getService(AuthenticationService.class); - private final CredentialsFactory credentialsFactory = KapuaLocator.getInstance().getFactory(CredentialsFactory.class); @Override protected void executeChain(ServletRequest request, ServletResponse response, FilterChain origChain) @@ -85,8 +85,10 @@ protected KapuaSession getSession() { /** * Check the {@link AccessToken#getExpiresOn()} and refreshes it on behalf of the user. * - * @param accessToken The {@link AccessToken} to check and refresh if needed. - * @throws KapuaException If one of the checks fails or refreshing the token fails. + * @param accessToken + * The {@link AccessToken} to check and refresh if needed. + * @throws KapuaException + * If one of the checks fails or refreshing the token fails. * @since 2.0.0 */ protected void checkAndRefreshAccessTokenIfExpired(AccessToken accessToken) throws KapuaException { @@ -97,7 +99,8 @@ protected void checkAndRefreshAccessTokenIfExpired(AccessToken accessToken) thro Date now = new Date(); if (now.after(accessToken.getExpiresOn()) && now.before(accessToken.getRefreshExpiresOn())) { - LOG.info("Refreshing AccessToken for user {} of scope {} expired on {} - token: {}", accessToken.getUserId(), accessToken.getScopeId(), accessToken.getExpiresOn(), accessToken.getTokenId()); + LOG.info("Refreshing AccessToken for user {} of scope {} expired on {} - token: {}", accessToken.getUserId(), accessToken.getScopeId(), accessToken.getExpiresOn(), + accessToken.getTokenId()); // Remove logout the user to perform a new login with the refreshed token. SecurityUtils.getSubject().logout(); @@ -106,7 +109,7 @@ protected void checkAndRefreshAccessTokenIfExpired(AccessToken accessToken) thro AccessToken refreshAccessToken = authenticationService.refreshAccessToken(accessToken.getTokenId(), accessToken.getRefreshToken()); // Authenticate with the refreshed AccessToken - authenticationService.authenticate(credentialsFactory.newAccessTokenCredentials(refreshAccessToken.getTokenId())); + authenticationService.authenticate(new AccessTokenCredentialsImpl(refreshAccessToken.getTokenId())); } else if (now.after(accessToken.getRefreshExpiresOn())) { throw new AuthenticationException("AccessToken.refreshToken is expired!"); } diff --git a/console/core/src/main/java/org/eclipse/kapua/app/console/core/server/GwtAuthorizationServiceImpl.java b/console/core/src/main/java/org/eclipse/kapua/app/console/core/server/GwtAuthorizationServiceImpl.java index 5fa08ddf2ba..6272d6f8d4c 100644 --- a/console/core/src/main/java/org/eclipse/kapua/app/console/core/server/GwtAuthorizationServiceImpl.java +++ b/console/core/src/main/java/org/eclipse/kapua/app/console/core/server/GwtAuthorizationServiceImpl.java @@ -12,6 +12,11 @@ *******************************************************************************/ package org.eclipse.kapua.app.console.core.server; +import java.util.concurrent.Callable; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; + import org.apache.shiro.SecurityUtils; import org.apache.shiro.session.Session; import org.apache.shiro.subject.Subject; @@ -43,7 +48,6 @@ import org.eclipse.kapua.service.account.Account; import org.eclipse.kapua.service.account.AccountService; import org.eclipse.kapua.service.authentication.AuthenticationService; -import org.eclipse.kapua.service.authentication.CredentialsFactory; import org.eclipse.kapua.service.authentication.JwtCredentials; import org.eclipse.kapua.service.authentication.UsernamePasswordCredentials; import org.eclipse.kapua.service.authentication.exception.KapuaAuthenticationErrorCodes; @@ -70,10 +74,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; -import java.util.concurrent.Callable; - public class GwtAuthorizationServiceImpl extends KapuaRemoteServiceServlet implements GwtAuthorizationService { private static final long serialVersionUID = -3919578632016541047L; @@ -87,7 +87,6 @@ public class GwtAuthorizationServiceImpl extends KapuaRemoteServiceServlet imple private static final AccountService ACCOUNT_SERVICE = LOCATOR.getService(AccountService.class); private static final AuthenticationService AUTHENTICATION_SERVICE = LOCATOR.getService(AuthenticationService.class); - private static final CredentialsFactory CREDENTIALS_FACTORY = LOCATOR.getFactory(CredentialsFactory.class); private static final AccessInfoService ACCESS_INFO_SERVICE = LOCATOR.getService(AccessInfoService.class); private static final AccessPermissionService ACCESS_PERMISSION_SERVICE = LOCATOR.getService(AccessPermissionService.class); @@ -114,7 +113,7 @@ public GwtSession login(GwtLoginCredential gwtLoginCredentials, boolean trustReq ArgumentValidator.notEmptyOrNull(gwtLoginCredentials.getPassword(), "loginCredentials.password"); // Parse Credentials - UsernamePasswordCredentials usernamePasswordCredentials = CREDENTIALS_FACTORY.newUsernamePasswordCredentials(gwtLoginCredentials.getUsername(), gwtLoginCredentials.getPassword()); + UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials(gwtLoginCredentials.getUsername(), gwtLoginCredentials.getPassword()); usernamePasswordCredentials.setAuthenticationCode(gwtLoginCredentials.getAuthenticationCode()); usernamePasswordCredentials.setTrustKey(gwtLoginCredentials.getTrustKey()); usernamePasswordCredentials.setTrustMe(trustReq); @@ -145,7 +144,7 @@ public GwtSession login(GwtJwtCredential gwtAccessTokenCredentials, GwtJwtIdToke ArgumentValidator.notEmptyOrNull(gwtJwtIdToken.getIdToken(), "jwtIdToken.idToken"); // Parse Credentials - JwtCredentials jwtCredentials = CREDENTIALS_FACTORY.newJwtCredentials(gwtAccessTokenCredentials.getAccessToken(), gwtJwtIdToken.getIdToken()); + JwtCredentials jwtCredentials = new JwtCredentials(gwtAccessTokenCredentials.getAccessToken(), gwtJwtIdToken.getIdToken()); // Cleanup any previous session cleanupSession(); diff --git a/console/core/src/main/java/org/eclipse/kapua/app/console/core/servlet/FileServlet.java b/console/core/src/main/java/org/eclipse/kapua/app/console/core/servlet/FileServlet.java index 08235e96e30..0331c176789 100644 --- a/console/core/src/main/java/org/eclipse/kapua/app/console/core/servlet/FileServlet.java +++ b/console/core/src/main/java/org/eclipse/kapua/app/console/core/servlet/FileServlet.java @@ -12,6 +12,17 @@ *******************************************************************************/ package org.eclipse.kapua.app.console.core.servlet; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.util.List; +import java.util.StringTokenizer; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + import org.apache.commons.fileupload.FileItem; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.CharEncoding; @@ -26,7 +37,6 @@ import org.eclipse.kapua.app.console.module.api.shared.model.GwtXSRFToken; import org.eclipse.kapua.commons.model.id.KapuaEid; import org.eclipse.kapua.locator.KapuaLocator; -import org.eclipse.kapua.service.device.management.command.DeviceCommandFactory; import org.eclipse.kapua.service.device.management.command.DeviceCommandInput; import org.eclipse.kapua.service.device.management.command.DeviceCommandManagementService; import org.eclipse.kapua.service.device.management.command.DeviceCommandOutput; @@ -35,16 +45,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.util.List; -import java.util.StringTokenizer; - public class FileServlet extends KapuaHttpServlet { private static final long serialVersionUID = -5016170117606322129L; @@ -55,7 +55,6 @@ public class FileServlet extends KapuaHttpServlet { private final DeviceConfigurationManagementService deviceConfigurationManagementService; private final DeviceCommandManagementService deviceCommandManagementService; - private final DeviceCommandFactory deviceCommandFactory; private final ConsoleSetting config; public FileServlet() { @@ -63,7 +62,6 @@ public FileServlet() { KapuaLocator locator = KapuaLocator.getInstance(); deviceConfigurationManagementService = locator.getService(DeviceConfigurationManagementService.class); deviceCommandManagementService = locator.getService(DeviceCommandManagementService.class); - deviceCommandFactory = locator.getFactory(DeviceCommandFactory.class); config = ConsoleSetting.getInstance(); } @@ -181,7 +179,7 @@ private void doPostCommand(KapuaFormFields kapuaFormFields, HttpServletResponse // FIXME: set a max size on the MQtt payload byte[] data = fileItems.isEmpty() ? null : fileItems.get(0).get(); - DeviceCommandInput commandInput = deviceCommandFactory.newCommandInput(); + DeviceCommandInput commandInput = new DeviceCommandInput(); StringTokenizer st = new StringTokenizer(command); int count = st.countTokens(); diff --git a/console/core/src/main/java/org/eclipse/kapua/app/console/core/shared/service/GwtAuthorizationService.java b/console/core/src/main/java/org/eclipse/kapua/app/console/core/shared/service/GwtAuthorizationService.java index efff85f084d..3fce2532927 100644 --- a/console/core/src/main/java/org/eclipse/kapua/app/console/core/shared/service/GwtAuthorizationService.java +++ b/console/core/src/main/java/org/eclipse/kapua/app/console/core/shared/service/GwtAuthorizationService.java @@ -12,14 +12,15 @@ *******************************************************************************/ package org.eclipse.kapua.app.console.core.shared.service; -import com.google.gwt.user.client.rpc.RemoteService; -import com.google.gwt.user.client.rpc.RemoteServiceRelativePath; import org.eclipse.kapua.app.console.core.shared.model.authentication.GwtJwtCredential; import org.eclipse.kapua.app.console.core.shared.model.authentication.GwtJwtIdToken; import org.eclipse.kapua.app.console.core.shared.model.authentication.GwtLoginCredential; import org.eclipse.kapua.app.console.module.api.client.GwtKapuaException; import org.eclipse.kapua.app.console.module.api.shared.model.session.GwtSession; +import com.google.gwt.user.client.rpc.RemoteService; +import com.google.gwt.user.client.rpc.RemoteServiceRelativePath; + /** * The client side stub for the RPC service. */ @@ -29,21 +30,25 @@ public interface GwtAuthorizationService extends RemoteService { /** * Logins a session based on the given credentials. If credentials are correct a session is established and returned * - * @param gwtLoginCredentials The credentials to authenticate + * @param gwtLoginCredentials + * The credentials to authenticate * @return The session info established. - * @throws GwtKapuaException If credentials are not valid. + * @throws GwtKapuaException + * If credentials are not valid. * @since 1.0.0 */ public GwtSession login(GwtLoginCredential gwtLoginCredentials, boolean trustReq) throws GwtKapuaException; /** - * Logins a session based on the given access token. If the access token is correct a session is established and returned. - * An id token is also passed for identity information about the user. + * Logins a session based on the given access token. If the access token is correct a session is established and returned. An id token is also passed for identity information about the user. * - * @param gwtAccessTokenCredentials The access token to authenticate. - * @param gwtJwtIdToken The id token which identifies the user. + * @param gwtAccessTokenCredentials + * The access token to authenticate. + * @param gwtJwtIdToken + * The id token which identifies the user. * @return The session info established. - * @throws GwtKapuaException If the access token is not valid. + * @throws GwtKapuaException + * If the access token is not valid. * @since 1.0.0 */ public GwtSession login(GwtJwtCredential gwtAccessTokenCredentials, GwtJwtIdToken gwtJwtIdToken) throws GwtKapuaException; @@ -52,7 +57,8 @@ public interface GwtAuthorizationService extends RemoteService { * Return the currently authenticated user or null if no session has been established. * * @return The current active session or null if no session is active. - * @throws GwtKapuaException FIXME: document this + * @throws GwtKapuaException + * FIXME: document this * @since 1.0.0 */ public GwtSession getCurrentSession() @@ -61,7 +67,8 @@ public GwtSession getCurrentSession() /** * Destroy the current active session. * - * @throws GwtKapuaException FIXME: document this + * @throws GwtKapuaException + * FIXME: document this * @since 1.0.0 */ public void logout() diff --git a/console/module/about/pom.xml b/console/module/about/pom.xml index f3db0492ed4..692e612c600 100644 --- a/console/module/about/pom.xml +++ b/console/module/about/pom.xml @@ -18,7 +18,7 @@ kapua-console-module org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-console-module-about diff --git a/console/module/account/pom.xml b/console/module/account/pom.xml index 7363b8896e4..8be93146d82 100644 --- a/console/module/account/pom.xml +++ b/console/module/account/pom.xml @@ -18,7 +18,7 @@ kapua-console-module org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-console-module-account diff --git a/console/module/account/src/main/java/org/eclipse/kapua/app/console/module/account/server/GwtAccountServiceImpl.java b/console/module/account/src/main/java/org/eclipse/kapua/app/console/module/account/server/GwtAccountServiceImpl.java index 8f56d5e7f48..7b013f2750b 100644 --- a/console/module/account/src/main/java/org/eclipse/kapua/app/console/module/account/server/GwtAccountServiceImpl.java +++ b/console/module/account/src/main/java/org/eclipse/kapua/app/console/module/account/server/GwtAccountServiceImpl.java @@ -58,7 +58,6 @@ import org.eclipse.kapua.commons.service.internal.KapuaServiceDisabledException; import org.eclipse.kapua.commons.util.ThrowingRunnable; import org.eclipse.kapua.locator.KapuaLocator; -import org.eclipse.kapua.model.config.metatype.EmptyTocd; import org.eclipse.kapua.model.config.metatype.KapuaTad; import org.eclipse.kapua.model.config.metatype.KapuaTicon; import org.eclipse.kapua.model.config.metatype.KapuaTocd; @@ -66,27 +65,24 @@ import org.eclipse.kapua.model.domain.Actions; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.model.query.KapuaListResult; +import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.service.KapuaService; import org.eclipse.kapua.service.account.Account; import org.eclipse.kapua.service.account.AccountCreator; -import org.eclipse.kapua.service.account.AccountFactory; -import org.eclipse.kapua.service.account.AccountQuery; import org.eclipse.kapua.service.account.AccountService; import org.eclipse.kapua.service.authorization.AuthorizationService; import org.eclipse.kapua.service.authorization.exception.SubjectUnauthorizedException; import org.eclipse.kapua.service.authorization.permission.Permission; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; import org.eclipse.kapua.service.authorization.role.RoleCreator; -import org.eclipse.kapua.service.authorization.role.RoleFactory; import org.eclipse.kapua.service.authorization.role.RoleService; import org.eclipse.kapua.service.config.KapuaConfigurableService; import org.eclipse.kapua.service.endpoint.EndpointInfo; -import org.eclipse.kapua.service.endpoint.EndpointInfoFactory; import org.eclipse.kapua.service.endpoint.EndpointInfoListResult; +import org.eclipse.kapua.service.endpoint.EndpointInfoQuery; import org.eclipse.kapua.service.endpoint.EndpointInfoService; import org.eclipse.kapua.service.user.User; -import org.eclipse.kapua.service.user.UserFactory; import org.eclipse.kapua.service.user.UserListResult; +import org.eclipse.kapua.service.user.UserQuery; import org.eclipse.kapua.service.user.UserService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -110,19 +106,13 @@ public class GwtAccountServiceImpl extends KapuaRemoteServiceServlet implements private static final KapuaLocator LOCATOR = KapuaLocator.getInstance(); private static final AccountService ACCOUNT_SERVICE = LOCATOR.getService(AccountService.class); - private static final AccountFactory ACCOUNT_FACTORY = LOCATOR.getFactory(AccountFactory.class); private static final EndpointInfoService ENDPOINT_INFO_SERVICE = LOCATOR.getService(EndpointInfoService.class); - private static final EndpointInfoFactory ENDPOINT_INFO_FACTORY = LOCATOR.getFactory(EndpointInfoFactory.class); private static final AuthorizationService AUTHORIZATION_SERVICE = LOCATOR.getService(AuthorizationService.class); - private static final PermissionFactory PERMISSION_FACTORY = LOCATOR.getFactory(PermissionFactory.class); - private static final RoleService ROLE_SERVICE = LOCATOR.getService(RoleService.class); - private static final RoleFactory ROLE_FACTORY = LOCATOR.getFactory(RoleFactory.class); private static final UserService USER_SERVICE = LOCATOR.getService(UserService.class); - private static final UserFactory USER_FACTORY = LOCATOR.getFactory(UserFactory.class); @Override public GwtAccount create(GwtXSRFToken xsrfToken, GwtAccountCreator gwtAccountCreator) @@ -133,7 +123,7 @@ public GwtAccount create(GwtXSRFToken xsrfToken, GwtAccountCreator gwtAccountCre GwtAccount gwtAccount = null; KapuaId parentAccountId = KapuaEid.parseCompactId(gwtAccountCreator.getParentAccountId()); try { - AccountCreator accountCreator = ACCOUNT_FACTORY.newCreator(parentAccountId); + AccountCreator accountCreator = new AccountCreator(parentAccountId); accountCreator.setName(gwtAccountCreator.getAccountName()); accountCreator.setOrganizationName(gwtAccountCreator.getOrganizationName()); @@ -156,9 +146,9 @@ public GwtAccount create(GwtXSRFToken xsrfToken, GwtAccountCreator gwtAccountCre @Override public void run() throws Exception { // Admin - Permission adminPermission = PERMISSION_FACTORY.newPermission((String) null, null, account.getId(), null, true); + Permission adminPermission = new Permission((String) null, null, account.getId(), null, true); - RoleCreator adminRoleCreator = ROLE_FACTORY.newCreator(account.getId()); + RoleCreator adminRoleCreator = new RoleCreator(account.getId()); adminRoleCreator.setName("Admin"); adminRoleCreator.setScopeId(account.getId()); adminRoleCreator.setPermissions(Sets.newHashSet(adminPermission)); @@ -166,9 +156,9 @@ public void run() throws Exception { ROLE_SERVICE.create(adminRoleCreator); // Thing - Permission thingPermission = PERMISSION_FACTORY.newPermission(Domains.BROKER, Actions.connect, account.getId(), null, false); + Permission thingPermission = new Permission(Domains.BROKER, Actions.connect, account.getId(), null, false); - RoleCreator thingRoleCreator = ROLE_FACTORY.newCreator(account.getId()); + RoleCreator thingRoleCreator = new RoleCreator(account.getId()); thingRoleCreator.setName("Thing"); thingRoleCreator.setScopeId(account.getId()); thingRoleCreator.setPermissions(Sets.newHashSet(thingPermission)); @@ -214,7 +204,7 @@ public ListLoadResult getAccountInfo(String scopeIdString, Str @Override public UserListResult call() throws Exception { - return USER_SERVICE.query(USER_FACTORY.newQuery(null)); + return USER_SERVICE.query(new UserQuery(null)); } }); @@ -244,14 +234,14 @@ public Account call() throws Exception { } accountPropertiesPairs.add(new GwtGroupedNVPair("accountInfo", "accountName", account.getName())); - if (AUTHORIZATION_SERVICE.isPermitted(PERMISSION_FACTORY.newPermission(Domains.ENDPOINT_INFO, Actions.read, scopeId))) { + if (AUTHORIZATION_SERVICE.isPermitted(new Permission(Domains.ENDPOINT_INFO, Actions.read, scopeId))) { //TODO: #LAYER_VIOLATION - related entities lookup should not be done here EndpointInfoListResult endpointInfos = KapuaSecurityUtils.doPrivileged(new Callable() { @Override public EndpointInfoListResult call() throws Exception { - return ENDPOINT_INFO_SERVICE.query(ENDPOINT_INFO_FACTORY.newQuery(account.getId())); + return ENDPOINT_INFO_SERVICE.query(new EndpointInfoQuery(account.getId())); } }); @@ -368,7 +358,7 @@ public ListLoadResult findAll(String scopeIdString) List gwtAccountList = new ArrayList(); KapuaId scopeId = KapuaEid.parseCompactId(scopeIdString); try { - AccountQuery query = ACCOUNT_FACTORY.newQuery(scopeId); + KapuaQuery query = new KapuaQuery(scopeId); KapuaListResult list = ACCOUNT_SERVICE.query(query); for (Account account : list.getItems()) { @@ -391,7 +381,7 @@ public ListLoadResult findChildren(String parentAccountId, boolean i if (includeSelf) { gwtAccountList.add(find(parentAccountId)); } - AccountQuery query = ACCOUNT_FACTORY.newQuery(scopeId); + KapuaQuery query = new KapuaQuery(scopeId); KapuaListResult list = ACCOUNT_SERVICE.query(query); for (Account account : list.getItems()) { @@ -436,7 +426,7 @@ public List findServiceConfigurations(String scopeId) throws } catch (KapuaServiceDisabledException ex) { continue; } - if (tocd != null && !(tocd instanceof EmptyTocd)) { + if (tocd != null && !tocd.isEmpty()) { GwtConfigComponent gwtConfig = new GwtConfigComponent(); gwtConfig.setId(tocd.getId()); gwtConfig.setName(tocd.getName()); @@ -668,7 +658,7 @@ public PagingLoadResult query(PagingLoadConfig loadConfig, GwtAccoun int totalLength = 0; List gwtAccounts = new ArrayList(); try { - AccountQuery query = GwtKapuaAccountModelConverter.convertAccountQuery(loadConfig, gwtAccountQuery); + KapuaQuery query = GwtKapuaAccountModelConverter.convertAccountQuery(loadConfig, gwtAccountQuery); KapuaListResult accounts = ACCOUNT_SERVICE.query(query); totalLength = accounts.getTotalCount().intValue(); @@ -678,7 +668,7 @@ public PagingLoadResult query(PagingLoadConfig loadConfig, GwtAccoun @Override public UserListResult call() throws Exception { - return USER_SERVICE.query(USER_FACTORY.newQuery(null)); + return USER_SERVICE.query(new UserQuery(null)); } }); diff --git a/console/module/account/src/main/java/org/eclipse/kapua/app/console/module/account/shared/util/GwtKapuaAccountModelConverter.java b/console/module/account/src/main/java/org/eclipse/kapua/app/console/module/account/shared/util/GwtKapuaAccountModelConverter.java index 646263ad66b..b0761ef13c2 100644 --- a/console/module/account/src/main/java/org/eclipse/kapua/app/console/module/account/shared/util/GwtKapuaAccountModelConverter.java +++ b/console/module/account/src/main/java/org/eclipse/kapua/app/console/module/account/shared/util/GwtKapuaAccountModelConverter.java @@ -12,30 +12,26 @@ *******************************************************************************/ package org.eclipse.kapua.app.console.module.account.shared.util; -import com.extjs.gxt.ui.client.Style.SortDir; -import com.extjs.gxt.ui.client.data.PagingLoadConfig; import org.apache.commons.lang3.StringUtils; import org.eclipse.kapua.app.console.module.account.shared.model.GwtAccountQuery; import org.eclipse.kapua.app.console.module.api.shared.util.GwtKapuaCommonsModelConverter; -import org.eclipse.kapua.locator.KapuaLocator; import org.eclipse.kapua.model.query.FieldSortCriteria; +import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.model.query.SortOrder; import org.eclipse.kapua.model.query.predicate.AndPredicate; import org.eclipse.kapua.model.query.predicate.AttributePredicate.Operator; import org.eclipse.kapua.service.account.AccountAttributes; -import org.eclipse.kapua.service.account.AccountFactory; -import org.eclipse.kapua.service.account.AccountQuery; + +import com.extjs.gxt.ui.client.Style.SortDir; +import com.extjs.gxt.ui.client.data.PagingLoadConfig; public class GwtKapuaAccountModelConverter { private GwtKapuaAccountModelConverter() { } - public static AccountQuery convertAccountQuery(PagingLoadConfig loadConfig, GwtAccountQuery gwtAccountQuery) { - KapuaLocator locator = KapuaLocator.getInstance(); - AccountFactory factory = locator.getFactory(AccountFactory.class); - - AccountQuery query = factory.newQuery(GwtKapuaCommonsModelConverter.convertKapuaId(gwtAccountQuery.getScopeId())); + public static KapuaQuery convertAccountQuery(PagingLoadConfig loadConfig, GwtAccountQuery gwtAccountQuery) { + KapuaQuery query = new KapuaQuery(GwtKapuaCommonsModelConverter.convertKapuaId(gwtAccountQuery.getScopeId())); AndPredicate predicate = query.andPredicate(); diff --git a/console/module/api/pom.xml b/console/module/api/pom.xml index b752be2d393..0106966e38a 100644 --- a/console/module/api/pom.xml +++ b/console/module/api/pom.xml @@ -19,7 +19,7 @@ kapua-console-module org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-console-module-api diff --git a/console/module/api/src/main/java/org/eclipse/kapua/app/console/module/api/shared/model/session/GwtSession.java b/console/module/api/src/main/java/org/eclipse/kapua/app/console/module/api/shared/model/session/GwtSession.java index e63ef0986fb..8a738455957 100644 --- a/console/module/api/src/main/java/org/eclipse/kapua/app/console/module/api/shared/model/session/GwtSession.java +++ b/console/module/api/src/main/java/org/eclipse/kapua/app/console/module/api/shared/model/session/GwtSession.java @@ -12,15 +12,14 @@ *******************************************************************************/ package org.eclipse.kapua.app.console.module.api.shared.model.session; -import org.eclipse.kapua.app.console.module.api.shared.model.KapuaBaseModel; -import org.eclipse.kapua.service.authorization.permission.Permission; - import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import org.eclipse.kapua.app.console.module.api.shared.model.KapuaBaseModel; + public class GwtSession extends KapuaBaseModel implements Serializable { private static final long serialVersionUID = -4511854889803351914L; @@ -229,7 +228,8 @@ public boolean isSelectedAccountFirstLevel() { *

  • /1/1234 = level 1
  • * * - * @param level The level to check against + * @param level + * The level to check against * @return {@code true} if it is, {@code false} otherwise * @since 2.0.0 */ @@ -304,12 +304,14 @@ public void addSessionPermission(GwtSessionPermission permission) { } /** - * Checks that the current {@link GwtSession} has the given session. - * This methods uses {@link #hasPermission(GwtSessionPermission)} instantiating the actual {@link GwtSessionPermission}. + * Checks that the current {@link GwtSession} has the given session. This methods uses {@link #hasPermission(GwtSessionPermission)} instantiating the actual {@link GwtSessionPermission}. * - * @param domain The domain to check - * @param action The {@link GwtSessionPermissionAction} to check - * @param targetScope The {@link GwtSessionPermissionScope} to check + * @param domain + * The domain to check + * @param action + * The {@link GwtSessionPermissionAction} to check + * @param targetScope + * The {@link GwtSessionPermissionScope} to check * @return {@code true} if the current {@link GwtSession} has the permission, {@code false} otherwise * @since 1.0.0 */ @@ -320,13 +322,14 @@ public boolean hasPermission(String domain, GwtSessionPermissionAction action, G /** * Checks that the current {@link GwtSession} has the given {@link GwtSessionPermission}. *

    - * This check is done simulating the permission check performed by the {@link org.eclipse.kapua.service.authorization.AuthorizationService#isPermitted(Permission)}. - * This does not introduces any security risk, since it will only allow to see/have access to certain elements of the UI while service access check is still performed on each call. + * This check is done simulating the permission check performed by the {@link org.eclipse.kapua.service.authorization.AuthorizationService#isPermitted(Permission)}. This does not introduces any + * security risk, since it will only allow to see/have access to certain elements of the UI while service access check is still performed on each call. *

    * After the check, the result is cached to allow faster check for subsequent check for the same permission. *

    * - * @param permissionToCheck The {@link GwtSessionPermission} to check + * @param permissionToCheck + * The {@link GwtSessionPermission} to check * @return {@code true} if the current {@link GwtSession} has the permission, {@code false} otherwise * @since 1.0.0 */ @@ -348,10 +351,11 @@ public boolean hasPermission(GwtSessionPermission permissionToCheck) { } /** - * This methods simulates the check that is performed by the {@link org.eclipse.kapua.service.authorization.AuthorizationService#isPermitted(Permission)}. - * {@link Permission#getForwardable()} property is supported in a different way, but produces the same results. + * This methods simulates the check that is performed by the {@link org.eclipse.kapua.service.authorization.AuthorizationService#isPermitted(Permission)}. {@link Permission#getForwardable()} + * property is supported in a different way, but produces the same results. * - * @param permissionToCheck The {@link GwtSessionPermission} to check + * @param permissionToCheck + * The {@link GwtSessionPermission} to check * @return {@code true} if the current {@link GwtSession} has the permission, {@code false} otherwise * @since 1.0.0 */ @@ -365,16 +369,16 @@ private boolean isPermitted(GwtSessionPermission permissionToCheck) { boolean check = false; switch (gsp.getPermissionScope()) { - case ALL: - check = true; - break; - case CHILDREN: - check = (GwtSessionPermissionScope.CHILDREN.equals(permissionToCheckScope) || - GwtSessionPermissionScope.SELF.equals(permissionToCheckScope)); - break; - case SELF: - check = GwtSessionPermissionScope.SELF.equals(permissionToCheckScope); - break; + case ALL: + check = true; + break; + case CHILDREN: + check = (GwtSessionPermissionScope.CHILDREN.equals(permissionToCheckScope) || + GwtSessionPermissionScope.SELF.equals(permissionToCheckScope)); + break; + case SELF: + check = GwtSessionPermissionScope.SELF.equals(permissionToCheckScope); + break; } if (check) { @@ -401,11 +405,11 @@ public boolean isFormDirty() { /** * Set user interface into dirty state. * - * @param formDirty true if user will need to confirm menu change. + * @param formDirty + * true if user will need to confirm menu change. */ public void setFormDirty(boolean formDirty) { this.formDirty = formDirty; } - } diff --git a/console/module/api/src/main/java/org/eclipse/kapua/app/console/module/api/shared/util/KapuaGwtCommonsModelConverter.java b/console/module/api/src/main/java/org/eclipse/kapua/app/console/module/api/shared/util/KapuaGwtCommonsModelConverter.java index f3b777f2e36..ce85885ed12 100644 --- a/console/module/api/src/main/java/org/eclipse/kapua/app/console/module/api/shared/util/KapuaGwtCommonsModelConverter.java +++ b/console/module/api/src/main/java/org/eclipse/kapua/app/console/module/api/shared/util/KapuaGwtCommonsModelConverter.java @@ -15,6 +15,7 @@ import org.eclipse.kapua.app.console.module.api.shared.model.GwtEntityModel; import org.eclipse.kapua.app.console.module.api.shared.model.GwtUpdatableEntityModel; import org.eclipse.kapua.model.KapuaEntity; +import org.eclipse.kapua.model.KapuaEntityBase; import org.eclipse.kapua.model.KapuaUpdatableEntity; import org.eclipse.kapua.model.id.KapuaId; @@ -23,302 +24,302 @@ public class KapuaGwtCommonsModelConverter { private KapuaGwtCommonsModelConverter() { } -// /** -// * Converts a {@link Role} into a {@link GwtRole} object for GWT usage. -// * -// * @param role The {@link Role} to convertKapuaId. -// * @return The converted {@link GwtRole}. -// * @since 1.0.0 -// */ -// public static GwtRole convertKapuaId(Role role) { -// GwtRole gwtRole = new GwtRole(); -// -// // -// // Covert commons attributes -// convertUpdatableEntity(role, gwtRole); -// -// // -// // Convert other attributes -// gwtRole.setName(role.getName()); -// -// // -// // Return converted entity -// return gwtRole; -// } -// -// /** -// * Merges a {@link Role} and a {@link AccessRole} into a {@link GwtAccessRole} object for GWT usage. -// * -// * @param role The {@link Role} to merge. -// * @param accessRole The {@link AccessRole} to merge. -// * @return The converted {@link GwtAccessRole}. -// * @since 1.0.0 -// */ -// public static GwtAccessRole convertKapuaId(Role role, AccessRole accessRole) { -// GwtAccessRole gwtAccessRole = new GwtAccessRole(); -// -// // -// // Covert commons attributes -// convertUpdatableEntity(accessRole, gwtAccessRole); -// -// // -// // Convert other attributes -// gwtAccessRole.setRoleName(role.getName()); -// gwtAccessRole.setRoleId(role.getViewId().toCompactId()); -// gwtAccessRole.setAccessInfoId(accessRole.getAccessInfoId().toCompactId()); -// // -// // Return converted entity -// return gwtAccessRole; -// } -// -// /** -// * Converts a {@link AccessRole} into a {@link GwtAccessRole} object for GWT usage. -// * -// * @param accessRole The {@link AccessRole} to convertKapuaId. -// * @return The converted {@link GwtAccessRole}. -// * @since 1.0.0 -// */ -// public static GwtAccessRole convertKapuaId(AccessRole accessRole) { -// GwtAccessRole gwtAccessRole = new GwtAccessRole(); -// -// // -// // Covert commons attributes -// convertUpdatableEntity(accessRole, gwtAccessRole); -// -// gwtAccessRole.setRoleId(accessRole.getRoleId().toCompactId()); -// gwtAccessRole.setAccessInfoId(accessRole.getAccessInfoId().toCompactId()); -// -// // -// // Return converted entity -// return gwtAccessRole; -// } -// -// /** -// * Converts a {@link AccessPermission} into a {@link GwtAccessPermission} object for GWT usage. -// * -// * @param accessPermission The {@link AccessPermission} to convertKapuaId. -// * @return The converted {@link GwtAccessPermission}. -// * @since 1.0.0 -// */ -// public static GwtAccessPermission convertKapuaId(AccessPermission accessPermission) { -// GwtAccessPermission gwtAccessPermission = new GwtAccessPermission(); -// -// // -// // Covert commons attributes -// convertUpdatableEntity(accessPermission, gwtAccessPermission); -// -// gwtAccessPermission.setAccessInfoId(accessPermission.getAccessInfoId().toCompactId()); -// gwtAccessPermission.setPermissionDomain(accessPermission.getPermission().getDomain()); -// -// if (accessPermission.getPermission().getAction() != null) { -// gwtAccessPermission.setPermissionAction(accessPermission.getPermission().getAction().toString()); -// } else { -// gwtAccessPermission.setPermissionAction("ALL"); -// } -// -// if (accessPermission.getPermission().getTargetScopeId() != null) { -// gwtAccessPermission.setPermissionTargetScopeId(accessPermission.getPermission().getTargetScopeId().toCompactId()); -// } else { -// gwtAccessPermission.setPermissionTargetScopeId("ALL"); -// } -// -// if (accessPermission.getPermission().getGroupId() != null) { -// gwtAccessPermission.setPermissionGroupId(accessPermission.getPermission().getGroupId().toCompactId()); -// } else { -// gwtAccessPermission.setPermissionGroupId("ALL"); -// } -// -// gwtAccessPermission.setPermissionForwardable(accessPermission.getPermission().getForwardable()); -// -// // -// // Return converted entity -// return gwtAccessPermission; -// } -// -// /** -// * Converts a {@link AccessInfo} into a {@link GwtAccessInfo} object for GWT usage. -// * -// * @param accessInfo The {@link AccessInfo} to convertKapuaId. -// * @return The converted {@link GwtAccessInfo}. -// * @since 1.0.0 -// */ -// public static GwtAccessInfo convertKapuaId(AccessInfo accessInfo) { -// GwtAccessInfo gwtAccessInfo = new GwtAccessInfo(); -// // -// // Covert commons attributes -// convertUpdatableEntity(accessInfo, gwtAccessInfo); -// -// gwtAccessInfo.setUserId(accessInfo.getUserId().toCompactId()); -// -// // -// // Return converted entity -// return gwtAccessInfo; -// } -// -// /** -// * Converts a {@link RolePermission} into a {@link GwtRolePermission} object for GWT usage. -// * -// * @param rolePermission The {@link RolePermission} to convertKapuaId -// * @return The converted {@link GwtRolePermission} -// * @since 1.0.0 -// */ -// public static GwtRolePermission convertKapuaId(RolePermission rolePermission) { -// GwtRolePermission gwtRolePermission = new GwtRolePermission(); -// -// // -// // Covert commons attributes -// convertUpdatableEntity(rolePermission, gwtRolePermission); -// -// // -// // Convert other attributes -// GwtPermission gwtPermission = convertKapuaId((Permission) rolePermission.getPermission()); -// -// gwtRolePermission.setRoleId(convertKapuaId(rolePermission.getRoleId())); -// gwtRolePermission.setDomain(gwtPermission.getDomain()); -// gwtRolePermission.setAction(gwtPermission.getAction()); -// gwtRolePermission.setGroupId(gwtPermission.getGroupId()); -// gwtRolePermission.setTargetScopeId(gwtPermission.getTargetScopeId()); -// gwtRolePermission.setForwardable(gwtPermission.getForwardable()); -// -// // -// // Return converted entity -// return gwtRolePermission; -// } -// -// /** -// * Converts a {@link Permission} into a {@link GwtPermission} object for GWT usage. -// * -// * @param permission The {@link Permission} to convertKapuaId. -// * @return The converted {@link GwtPermission}. -// * @since 1.0.0 -// */ -// public static GwtPermission convertKapuaId(Permission permission) { -// return new GwtPermission(convertDomain(permission.getDomain()), -// convertKapuaId(permission.getAction()), -// convertKapuaId(permission.getTargetScopeId()), -// convertKapuaId(permission.getGroupId()), -// permission.getForwardable()); -// } -// -// /** -// * Converts a {@link Action} into a {@link GwtAction} -// * -// * @param action The {@link Action} to convertKapuaId -// * @return The converted {@link GwtAction} -// * @since 1.0.0 -// */ -// public static GwtAction convertKapuaId(Actions action) { -// -// GwtAction gwtAction = null; -// if (action != null) { -// switch (action) { -// case connect: -// gwtAction = GwtAction.connect; -// break; -// case delete: -// gwtAction = GwtAction.delete; -// break; -// case execute: -// gwtAction = GwtAction.execute; -// break; -// case read: -// gwtAction = GwtAction.read; -// break; -// case write: -// gwtAction = GwtAction.write; -// break; -// } -// } -// return gwtAction; -// } -// -// /** -// * Converts a {@link Group} into a {@link GwtGroup} -// * -// * @param group The {@link Group} to convertKapuaId -// * @return The converted {@link GwtGroup} -// * @since 1.0.0 -// */ -// public static GwtGroup convertKapuaId(Group group) { -// -// GwtGroup gwtGroup = new GwtGroup(); -// // -// // Covert commons attributes -// convertUpdatableEntity(group, gwtGroup); -// -// // -// // Convert other attributes -// gwtGroup.setGroupName(group.getName()); -// -// return gwtGroup; -// } -// -// /** -// * Converts a {@link String} domain into a {@link GwtDomain} -// * -// * @param domain The {@link String} domain to convertKapuaId -// * @return The converted {@link GwtDomain} -// * @since 1.0.0 -// */ -// public static GwtDomain convertDomain(String domain) { -// GwtDomain gwtDomain = null; -// -// if (new AccessInfoDomain().getName().equals(domain)) { -// gwtDomain = GwtDomain.access_info; -// } else if (new AccessTokenDomain().getName().equals(domain)) { -// gwtDomain = GwtDomain.access_token; -// } else if (Domains.ACCOUNT.getName().equals(domain)) { -// gwtDomain = GwtDomain.account; -// } else if (new BrokerDomain().getName().equals(domain)) { -// gwtDomain = GwtDomain.broker; -// } else if (new CredentialDomain().getName().equals(domain)) { -// gwtDomain = GwtDomain.credential; -// } else if (new DatastoreDomain().getName().equals(domain)) { -// gwtDomain = GwtDomain.datastore; -// } else if (new DeviceDomain().getName().equals(domain)) { -// gwtDomain = GwtDomain.device; -// } else if (new DeviceConnectionDomain().getName().equals(domain)) { -// gwtDomain = GwtDomain.device_connection; -// } else if (new DeviceEventDomain().getName().equals(domain)) { -// gwtDomain = GwtDomain.device_event; -// } else if (new DeviceLifecycleDomain().getName().equals(domain)) { -// gwtDomain = GwtDomain.device_lifecycle; -// } else if (new DeviceManagementDomain().getName().equals(domain)) { -// gwtDomain = GwtDomain.device_management; -// } else if (new DomainDomain().getName().equals(domain)) { -// gwtDomain = GwtDomain.domain; -// } else if (new GroupDomain().getName().equals(domain)) { -// gwtDomain = GwtDomain.group; -// } else if (new RoleDomain().getName().equals(domain)) { -// gwtDomain = GwtDomain.role; -// } else if (new UserDomain().getName().equals(domain)) { -// gwtDomain = GwtDomain.user; -// } -// -// return gwtDomain; -// } -// -// /** -// * Converts a {@link String} action into a {@link GwtAction} -// * -// * @param action The {@link String} action to convertKapuaId -// * @return The converted {@link GwtAction} -// * @since 1.0.0 -// */ -// public static GwtAction convertAction(String action) { -// return GwtAction.valueOf(action); -// } -// -// /** -// * Converts a {@link Action} action into a {@link GwtAction} -// * -// * @param action The {@link Action} action to convertKapuaId -// * @return The converted {@link GwtAction} -// * @since 1.0.0 -// */ -// public static GwtAction convertAction(Action action) { -// return GwtAction.valueOf(action.toString()); -// } + // /** + // * Converts a {@link Role} into a {@link GwtRole} object for GWT usage. + // * + // * @param role The {@link Role} to convertKapuaId. + // * @return The converted {@link GwtRole}. + // * @since 1.0.0 + // */ + // public static GwtRole convertKapuaId(Role role) { + // GwtRole gwtRole = new GwtRole(); + // + // // + // // Covert commons attributes + // convertUpdatableEntity(role, gwtRole); + // + // // + // // Convert other attributes + // gwtRole.setName(role.getName()); + // + // // + // // Return converted entity + // return gwtRole; + // } + // + // /** + // * Merges a {@link Role} and a {@link AccessRole} into a {@link GwtAccessRole} object for GWT usage. + // * + // * @param role The {@link Role} to merge. + // * @param accessRole The {@link AccessRole} to merge. + // * @return The converted {@link GwtAccessRole}. + // * @since 1.0.0 + // */ + // public static GwtAccessRole convertKapuaId(Role role, AccessRole accessRole) { + // GwtAccessRole gwtAccessRole = new GwtAccessRole(); + // + // // + // // Covert commons attributes + // convertUpdatableEntity(accessRole, gwtAccessRole); + // + // // + // // Convert other attributes + // gwtAccessRole.setRoleName(role.getName()); + // gwtAccessRole.setRoleId(role.getViewId().toCompactId()); + // gwtAccessRole.setAccessInfoId(accessRole.getAccessInfoId().toCompactId()); + // // + // // Return converted entity + // return gwtAccessRole; + // } + // + // /** + // * Converts a {@link AccessRole} into a {@link GwtAccessRole} object for GWT usage. + // * + // * @param accessRole The {@link AccessRole} to convertKapuaId. + // * @return The converted {@link GwtAccessRole}. + // * @since 1.0.0 + // */ + // public static GwtAccessRole convertKapuaId(AccessRole accessRole) { + // GwtAccessRole gwtAccessRole = new GwtAccessRole(); + // + // // + // // Covert commons attributes + // convertUpdatableEntity(accessRole, gwtAccessRole); + // + // gwtAccessRole.setRoleId(accessRole.getRoleId().toCompactId()); + // gwtAccessRole.setAccessInfoId(accessRole.getAccessInfoId().toCompactId()); + // + // // + // // Return converted entity + // return gwtAccessRole; + // } + // + // /** + // * Converts a {@link AccessPermission} into a {@link GwtAccessPermission} object for GWT usage. + // * + // * @param accessPermission The {@link AccessPermission} to convertKapuaId. + // * @return The converted {@link GwtAccessPermission}. + // * @since 1.0.0 + // */ + // public static GwtAccessPermission convertKapuaId(AccessPermission accessPermission) { + // GwtAccessPermission gwtAccessPermission = new GwtAccessPermission(); + // + // // + // // Covert commons attributes + // convertUpdatableEntity(accessPermission, gwtAccessPermission); + // + // gwtAccessPermission.setAccessInfoId(accessPermission.getAccessInfoId().toCompactId()); + // gwtAccessPermission.setPermissionDomain(accessPermission.getPermission().getDomain()); + // + // if (accessPermission.getPermission().getAction() != null) { + // gwtAccessPermission.setPermissionAction(accessPermission.getPermission().getAction().toString()); + // } else { + // gwtAccessPermission.setPermissionAction("ALL"); + // } + // + // if (accessPermission.getPermission().getTargetScopeId() != null) { + // gwtAccessPermission.setPermissionTargetScopeId(accessPermission.getPermission().getTargetScopeId().toCompactId()); + // } else { + // gwtAccessPermission.setPermissionTargetScopeId("ALL"); + // } + // + // if (accessPermission.getPermission().getGroupId() != null) { + // gwtAccessPermission.setPermissionGroupId(accessPermission.getPermission().getGroupId().toCompactId()); + // } else { + // gwtAccessPermission.setPermissionGroupId("ALL"); + // } + // + // gwtAccessPermission.setPermissionForwardable(accessPermission.getPermission().getForwardable()); + // + // // + // // Return converted entity + // return gwtAccessPermission; + // } + // + // /** + // * Converts a {@link AccessInfo} into a {@link GwtAccessInfo} object for GWT usage. + // * + // * @param accessInfo The {@link AccessInfo} to convertKapuaId. + // * @return The converted {@link GwtAccessInfo}. + // * @since 1.0.0 + // */ + // public static GwtAccessInfo convertKapuaId(AccessInfo accessInfo) { + // GwtAccessInfo gwtAccessInfo = new GwtAccessInfo(); + // // + // // Covert commons attributes + // convertUpdatableEntity(accessInfo, gwtAccessInfo); + // + // gwtAccessInfo.setUserId(accessInfo.getUserId().toCompactId()); + // + // // + // // Return converted entity + // return gwtAccessInfo; + // } + // + // /** + // * Converts a {@link RolePermission} into a {@link GwtRolePermission} object for GWT usage. + // * + // * @param rolePermission The {@link RolePermission} to convertKapuaId + // * @return The converted {@link GwtRolePermission} + // * @since 1.0.0 + // */ + // public static GwtRolePermission convertKapuaId(RolePermission rolePermission) { + // GwtRolePermission gwtRolePermission = new GwtRolePermission(); + // + // // + // // Covert commons attributes + // convertUpdatableEntity(rolePermission, gwtRolePermission); + // + // // + // // Convert other attributes + // GwtPermission gwtPermission = convertKapuaId((Permission) rolePermission.getPermission()); + // + // gwtRolePermission.setRoleId(convertKapuaId(rolePermission.getRoleId())); + // gwtRolePermission.setDomain(gwtPermission.getDomain()); + // gwtRolePermission.setAction(gwtPermission.getAction()); + // gwtRolePermission.setGroupId(gwtPermission.getGroupId()); + // gwtRolePermission.setTargetScopeId(gwtPermission.getTargetScopeId()); + // gwtRolePermission.setForwardable(gwtPermission.getForwardable()); + // + // // + // // Return converted entity + // return gwtRolePermission; + // } + // + // /** + // * Converts a {@link Permission} into a {@link GwtPermission} object for GWT usage. + // * + // * @param permission The {@link Permission} to convertKapuaId. + // * @return The converted {@link GwtPermission}. + // * @since 1.0.0 + // */ + // public static GwtPermission convertKapuaId(Permission permission) { + // return new GwtPermission(convertDomain(permission.getDomain()), + // convertKapuaId(permission.getAction()), + // convertKapuaId(permission.getTargetScopeId()), + // convertKapuaId(permission.getGroupId()), + // permission.getForwardable()); + // } + // + // /** + // * Converts a {@link Action} into a {@link GwtAction} + // * + // * @param action The {@link Action} to convertKapuaId + // * @return The converted {@link GwtAction} + // * @since 1.0.0 + // */ + // public static GwtAction convertKapuaId(Actions action) { + // + // GwtAction gwtAction = null; + // if (action != null) { + // switch (action) { + // case connect: + // gwtAction = GwtAction.connect; + // break; + // case delete: + // gwtAction = GwtAction.delete; + // break; + // case execute: + // gwtAction = GwtAction.execute; + // break; + // case read: + // gwtAction = GwtAction.read; + // break; + // case write: + // gwtAction = GwtAction.write; + // break; + // } + // } + // return gwtAction; + // } + // + // /** + // * Converts a {@link Group} into a {@link GwtGroup} + // * + // * @param group The {@link Group} to convertKapuaId + // * @return The converted {@link GwtGroup} + // * @since 1.0.0 + // */ + // public static GwtGroup convertKapuaId(Group group) { + // + // GwtGroup gwtGroup = new GwtGroup(); + // // + // // Covert commons attributes + // convertUpdatableEntity(group, gwtGroup); + // + // // + // // Convert other attributes + // gwtGroup.setGroupName(group.getName()); + // + // return gwtGroup; + // } + // + // /** + // * Converts a {@link String} domain into a {@link GwtDomain} + // * + // * @param domain The {@link String} domain to convertKapuaId + // * @return The converted {@link GwtDomain} + // * @since 1.0.0 + // */ + // public static GwtDomain convertDomain(String domain) { + // GwtDomain gwtDomain = null; + // + // if (new AccessInfoDomain().getName().equals(domain)) { + // gwtDomain = GwtDomain.access_info; + // } else if (new AccessTokenDomain().getName().equals(domain)) { + // gwtDomain = GwtDomain.access_token; + // } else if (Domains.ACCOUNT.getName().equals(domain)) { + // gwtDomain = GwtDomain.account; + // } else if (new BrokerDomain().getName().equals(domain)) { + // gwtDomain = GwtDomain.broker; + // } else if (new CredentialDomain().getName().equals(domain)) { + // gwtDomain = GwtDomain.credential; + // } else if (new DatastoreDomain().getName().equals(domain)) { + // gwtDomain = GwtDomain.datastore; + // } else if (new DeviceDomain().getName().equals(domain)) { + // gwtDomain = GwtDomain.device; + // } else if (new DeviceConnectionDomain().getName().equals(domain)) { + // gwtDomain = GwtDomain.device_connection; + // } else if (new DeviceEventDomain().getName().equals(domain)) { + // gwtDomain = GwtDomain.device_event; + // } else if (new DeviceLifecycleDomain().getName().equals(domain)) { + // gwtDomain = GwtDomain.device_lifecycle; + // } else if (new DeviceManagementDomain().getName().equals(domain)) { + // gwtDomain = GwtDomain.device_management; + // } else if (new DomainDomain().getName().equals(domain)) { + // gwtDomain = GwtDomain.domain; + // } else if (new GroupDomain().getName().equals(domain)) { + // gwtDomain = GwtDomain.group; + // } else if (new RoleDomain().getName().equals(domain)) { + // gwtDomain = GwtDomain.role; + // } else if (new UserDomain().getName().equals(domain)) { + // gwtDomain = GwtDomain.user; + // } + // + // return gwtDomain; + // } + // + // /** + // * Converts a {@link String} action into a {@link GwtAction} + // * + // * @param action The {@link String} action to convertKapuaId + // * @return The converted {@link GwtAction} + // * @since 1.0.0 + // */ + // public static GwtAction convertAction(String action) { + // return GwtAction.valueOf(action); + // } + // + // /** + // * Converts a {@link Action} action into a {@link GwtAction} + // * + // * @param action The {@link Action} action to convertKapuaId + // * @return The converted {@link GwtAction} + // * @since 1.0.0 + // */ + // public static GwtAction convertAction(Action action) { + // return GwtAction.valueOf(action.toString()); + // } /** * Converts a {@link KapuaId} into its {@link String} short id representation. @@ -326,7 +327,8 @@ private KapuaGwtCommonsModelConverter() { * Example: 1 => AQ *

    * - * @param kapuaId The {@link KapuaId} to convertKapuaId + * @param kapuaId + * The {@link KapuaId} to convertKapuaId * @return The short id representation of the {@link KapuaId} * @since 1.0.0 */ @@ -337,162 +339,164 @@ public static String convertKapuaId(KapuaId kapuaId) { // Return converted entity return kapuaId.toCompactId(); } -// /** -// * Converts a {@link User} into a {@link GwtUser} for GWT usage. -// * -// * @param user The {@link User} to convertKapuaId. -// * @return The converted {@link GwtUser} -// * @since 1.0.0 -// */ -// public static GwtUser convertKapuaId(User user) -// throws KapuaException { -// -// GwtUser gwtUser = new GwtUser(); -// -// // -// // Convert commons attributes -// convertUpdatableEntity(user, gwtUser); -// -// // -// // Convert other attributes -// gwtUser.setUsername(user.getName()); -// gwtUser.setDisplayName(user.getDisplayName()); -// gwtUser.setEmail(user.getEmail()); -// gwtUser.setPhoneNumber(user.getPhoneNumber()); -// gwtUser.setStatus(user.getStatus().name()); -// gwtUser.setExpirationDate(user.getExpirationDate()); -// -// // -// // Return converted entity -// return gwtUser; -// } -// -// public static GwtDevice convertKapuaId(Device device) -// throws KapuaException { -// -// GwtDevice gwtDevice = new GwtDevice(); -// gwtDevice.setId(convertKapuaId(device.getViewId())); -// gwtDevice.setScopeId(convertKapuaId(device.getScopeId())); -// gwtDevice.setGwtDeviceStatus(device.getStatus().toString()); -// gwtDevice.setClientId(device.getClientId()); -// gwtDevice.setDisplayName(device.getDisplayName()); -// gwtDevice.setModelId(device.getModelId()); -// gwtDevice.setSerialNumber(device.getSerialNumber()); -// gwtDevice.setGroupId(convertKapuaId(device.getGroupId())); -// gwtDevice.setFirmwareVersion(device.getFirmwareVersion()); -// gwtDevice.setBiosVersion(device.getBiosVersion()); -// gwtDevice.setOsVersion(device.getOsVersion()); -// gwtDevice.setJvmVersion(device.getJvmVersion()); -// gwtDevice.setOsgiVersion(device.getOsgiFrameworkVersion()); -// gwtDevice.setAcceptEncoding(device.getAcceptEncoding()); -// gwtDevice.setApplicationIdentifiers(device.getApplicationIdentifiers()); -// gwtDevice.setIotFrameworkVersion(device.getApplicationFrameworkVersion()); -// gwtDevice.setIccid(device.getIccid()); -// gwtDevice.setImei(device.getImei()); -// gwtDevice.setImsi(device.getImsi()); -// gwtDevice.setCustomAttribute1(device.getCustomAttribute1()); -// gwtDevice.setCustomAttribute2(device.getCustomAttribute2()); -// gwtDevice.setCustomAttribute3(device.getCustomAttribute3()); -// gwtDevice.setCustomAttribute4(device.getCustomAttribute4()); -// gwtDevice.setCustomAttribute5(device.getCustomAttribute5()); -// gwtDevice.setOptlock(device.getOptlock()); -// -// // Last device event -// if (device.getLastEvent() != null) { -// DeviceEvent lastEvent = device.getLastEvent(); -// -// gwtDevice.setLastEventType(lastEvent.getType()); -// gwtDevice.setLastEventOn(lastEvent.getReceivedOn()); -// -// } -// -// // Device connection -// gwtDevice.setConnectionIp(device.getConnectionIp()); -// gwtDevice.setConnectionInterface(device.getConnectionInterface()); -// if (device.getConnection() != null) { -// DeviceConnection connection = device.getConnection(); -// gwtDevice.setClientIp(connection.getClientIp()); -// gwtDevice.setGwtDeviceConnectionStatus(connection.getStatus().toString()); -// gwtDevice.setDeviceUserId(connection.getUserId().toCompactId()); -// } -// return gwtDevice; -// } -// -// public static GwtDeviceEvent convertKapuaId(DeviceEvent deviceEvent) { -// GwtDeviceEvent gwtDeviceEvent = new GwtDeviceEvent(); -// gwtDeviceEvent.setDeviceId(deviceEvent.getDeviceId().toCompactId()); -// gwtDeviceEvent.setSentOn(deviceEvent.getSentOn()); -// gwtDeviceEvent.setReceivedOn(deviceEvent.getReceivedOn()); -// gwtDeviceEvent.setEventType(deviceEvent.getResource()); -// gwtDeviceEvent.setGwtActionType(deviceEvent.getAction().toString()); -// gwtDeviceEvent.setGwtResponseCode(deviceEvent.getResponseCode().toString()); -// String escapedMessage = KapuaSafeHtmlUtils.htmlEscape(deviceEvent.getEventMessage()); -// gwtDeviceEvent.setEventMessage(escapedMessage); -// -// return gwtDeviceEvent; -// } -// -// public static GwtDeviceConnection convertKapuaId(DeviceConnection deviceConnection) { -// GwtDeviceConnection gwtDeviceConnection = new GwtDeviceConnection(); -// -// // -// // Convert commons attributes -// convertUpdatableEntity(deviceConnection, gwtDeviceConnection); -// -// // -// // Convert other attributes -// gwtDeviceConnection.setClientId(deviceConnection.getClientId()); -// gwtDeviceConnection.setUserId(convertKapuaId(deviceConnection.getUserId())); -// gwtDeviceConnection.setClientIp(deviceConnection.getClientIp()); -// gwtDeviceConnection.setServerIp(deviceConnection.getServerIp()); -// gwtDeviceConnection.setProtocol(deviceConnection.getProtocol()); -// gwtDeviceConnection.setConnectionStatus(convertKapuaId(deviceConnection.getStatus())); -// gwtDeviceConnection.setOptlock(deviceConnection.getOptlock()); -// -// // -// // Return converted entity -// return gwtDeviceConnection; -// } -// -// private static String convertKapuaId(DeviceConnectionStatus status) { -// return status.toString(); -// } -// -// public static GwtCredential convertKapuaId(Credential credential, User user) { -// GwtCredential gwtCredential = new GwtCredential(); -// convertUpdatableEntity(credential, gwtCredential); -// gwtCredential.setUserId(credential.getUserId().toCompactId()); -// gwtCredential.setCredentialType(credential.getCredentialType().toString()); -// gwtCredential.setCredentialKey(credential.getCredentialKey()); -// gwtCredential.setCredentialStatus(credential.getStatus().toString()); -// gwtCredential.setExpirationDate(credential.getExpirationDate()); -// if (user != null) { -// gwtCredential.setUsername(user.getName()); -// } -// gwtCredential.setSubjectType(GwtSubjectType.USER.toString()); -// return gwtCredential; -// } -// -// public static GwtTopic convertToTopic(ChannelInfo channelInfo) { -// return new GwtTopic(channelInfo.getName(), channelInfo.getName(), channelInfo.getName(), channelInfo.getLastMessageOn()); -// } -// -// public static GwtDatastoreAsset convertToAssets(ChannelInfo channelInfo) { -// return new GwtDatastoreAsset(channelInfo.getName().substring(6), channelInfo.getName(), channelInfo.getName(), channelInfo.getLastMessageOn()); -// } -// -// public static GwtHeader convertToHeader(MetricInfo metric) { -// GwtHeader header = new GwtHeader(); -// header.setName(metric.getName()); -// header.setType(metric.getMetricType().getSimpleName()); -// return header; -// } + // /** + // * Converts a {@link User} into a {@link GwtUser} for GWT usage. + // * + // * @param user The {@link User} to convertKapuaId. + // * @return The converted {@link GwtUser} + // * @since 1.0.0 + // */ + // public static GwtUser convertKapuaId(User user) + // throws KapuaException { + // + // GwtUser gwtUser = new GwtUser(); + // + // // + // // Convert commons attributes + // convertUpdatableEntity(user, gwtUser); + // + // // + // // Convert other attributes + // gwtUser.setUsername(user.getName()); + // gwtUser.setDisplayName(user.getDisplayName()); + // gwtUser.setEmail(user.getEmail()); + // gwtUser.setPhoneNumber(user.getPhoneNumber()); + // gwtUser.setStatus(user.getStatus().name()); + // gwtUser.setExpirationDate(user.getExpirationDate()); + // + // // + // // Return converted entity + // return gwtUser; + // } + // + // public static GwtDevice convertKapuaId(Device device) + // throws KapuaException { + // + // GwtDevice gwtDevice = new GwtDevice(); + // gwtDevice.setId(convertKapuaId(device.getViewId())); + // gwtDevice.setScopeId(convertKapuaId(device.getScopeId())); + // gwtDevice.setGwtDeviceStatus(device.getStatus().toString()); + // gwtDevice.setClientId(device.getClientId()); + // gwtDevice.setDisplayName(device.getDisplayName()); + // gwtDevice.setModelId(device.getModelId()); + // gwtDevice.setSerialNumber(device.getSerialNumber()); + // gwtDevice.setGroupId(convertKapuaId(device.getGroupId())); + // gwtDevice.setFirmwareVersion(device.getFirmwareVersion()); + // gwtDevice.setBiosVersion(device.getBiosVersion()); + // gwtDevice.setOsVersion(device.getOsVersion()); + // gwtDevice.setJvmVersion(device.getJvmVersion()); + // gwtDevice.setOsgiVersion(device.getOsgiFrameworkVersion()); + // gwtDevice.setAcceptEncoding(device.getAcceptEncoding()); + // gwtDevice.setApplicationIdentifiers(device.getApplicationIdentifiers()); + // gwtDevice.setIotFrameworkVersion(device.getApplicationFrameworkVersion()); + // gwtDevice.setIccid(device.getIccid()); + // gwtDevice.setImei(device.getImei()); + // gwtDevice.setImsi(device.getImsi()); + // gwtDevice.setCustomAttribute1(device.getCustomAttribute1()); + // gwtDevice.setCustomAttribute2(device.getCustomAttribute2()); + // gwtDevice.setCustomAttribute3(device.getCustomAttribute3()); + // gwtDevice.setCustomAttribute4(device.getCustomAttribute4()); + // gwtDevice.setCustomAttribute5(device.getCustomAttribute5()); + // gwtDevice.setOptlock(device.getOptlock()); + // + // // Last device event + // if (device.getLastEvent() != null) { + // DeviceEvent lastEvent = device.getLastEvent(); + // + // gwtDevice.setLastEventType(lastEvent.getType()); + // gwtDevice.setLastEventOn(lastEvent.getReceivedOn()); + // + // } + // + // // Device connection + // gwtDevice.setConnectionIp(device.getConnectionIp()); + // gwtDevice.setConnectionInterface(device.getConnectionInterface()); + // if (device.getConnection() != null) { + // DeviceConnection connection = device.getConnection(); + // gwtDevice.setClientIp(connection.getClientIp()); + // gwtDevice.setGwtDeviceConnectionStatus(connection.getStatus().toString()); + // gwtDevice.setDeviceUserId(connection.getUserId().toCompactId()); + // } + // return gwtDevice; + // } + // + // public static GwtDeviceEvent convertKapuaId(DeviceEvent deviceEvent) { + // GwtDeviceEvent gwtDeviceEvent = new GwtDeviceEvent(); + // gwtDeviceEvent.setDeviceId(deviceEvent.getDeviceId().toCompactId()); + // gwtDeviceEvent.setSentOn(deviceEvent.getSentOn()); + // gwtDeviceEvent.setReceivedOn(deviceEvent.getReceivedOn()); + // gwtDeviceEvent.setEventType(deviceEvent.getResource()); + // gwtDeviceEvent.setGwtActionType(deviceEvent.getAction().toString()); + // gwtDeviceEvent.setGwtResponseCode(deviceEvent.getResponseCode().toString()); + // String escapedMessage = KapuaSafeHtmlUtils.htmlEscape(deviceEvent.getEventMessage()); + // gwtDeviceEvent.setEventMessage(escapedMessage); + // + // return gwtDeviceEvent; + // } + // + // public static GwtDeviceConnection convertKapuaId(DeviceConnection deviceConnection) { + // GwtDeviceConnection gwtDeviceConnection = new GwtDeviceConnection(); + // + // // + // // Convert commons attributes + // convertUpdatableEntity(deviceConnection, gwtDeviceConnection); + // + // // + // // Convert other attributes + // gwtDeviceConnection.setClientId(deviceConnection.getClientId()); + // gwtDeviceConnection.setUserId(convertKapuaId(deviceConnection.getUserId())); + // gwtDeviceConnection.setClientIp(deviceConnection.getClientIp()); + // gwtDeviceConnection.setServerIp(deviceConnection.getServerIp()); + // gwtDeviceConnection.setProtocol(deviceConnection.getProtocol()); + // gwtDeviceConnection.setConnectionStatus(convertKapuaId(deviceConnection.getStatus())); + // gwtDeviceConnection.setOptlock(deviceConnection.getOptlock()); + // + // // + // // Return converted entity + // return gwtDeviceConnection; + // } + // + // private static String convertKapuaId(DeviceConnectionStatus status) { + // return status.toString(); + // } + // + // public static GwtCredential convertKapuaId(Credential credential, User user) { + // GwtCredential gwtCredential = new GwtCredential(); + // convertUpdatableEntity(credential, gwtCredential); + // gwtCredential.setUserId(credential.getUserId().toCompactId()); + // gwtCredential.setCredentialType(credential.getCredentialType().toString()); + // gwtCredential.setCredentialKey(credential.getCredentialKey()); + // gwtCredential.setCredentialStatus(credential.getStatus().toString()); + // gwtCredential.setExpirationDate(credential.getExpirationDate()); + // if (user != null) { + // gwtCredential.setUsername(user.getName()); + // } + // gwtCredential.setSubjectType(GwtSubjectType.USER.toString()); + // return gwtCredential; + // } + // + // public static GwtTopic convertToTopic(ChannelInfo channelInfo) { + // return new GwtTopic(channelInfo.getName(), channelInfo.getName(), channelInfo.getName(), channelInfo.getLastMessageOn()); + // } + // + // public static GwtDatastoreAsset convertToAssets(ChannelInfo channelInfo) { + // return new GwtDatastoreAsset(channelInfo.getName().substring(6), channelInfo.getName(), channelInfo.getName(), channelInfo.getLastMessageOn()); + // } + // + // public static GwtHeader convertToHeader(MetricInfo metric) { + // GwtHeader header = new GwtHeader(); + // header.setName(metric.getName()); + // header.setType(metric.getMetricType().getSimpleName()); + // return header; + // } /** * Utility method to convertKapuaId commons properties of {@link KapuaUpdatableEntity} object to the GWT matching {@link GwtUpdatableEntityModel} object * - * @param kapuaEntity The {@link KapuaUpdatableEntity} from which to copy values - * @param gwtEntity The {@link GwtUpdatableEntityModel} into which copy values + * @param kapuaEntity + * The {@link KapuaUpdatableEntity} from which to copy values + * @param gwtEntity + * The {@link GwtUpdatableEntityModel} into which copy values * @since 1.0.0 */ public static void convertUpdatableEntity(KapuaUpdatableEntity kapuaEntity, GwtUpdatableEntityModel gwtEntity) { @@ -510,8 +514,10 @@ public static void convertUpdatableEntity(KapuaUpdatableEntity kapuaEntity, GwtU /** * Utility method to convertKapuaId commons properties of {@link KapuaEntity} object to the GWT matching {@link GwtEntityModel} object * - * @param kapuaEntity The {@link KapuaEntity} from which to copy values - * @param gwtEntity The {@link GwtEntityModel} into which copy values + * @param kapuaEntity + * The {@link KapuaEntity} from which to copy values + * @param gwtEntity + * The {@link GwtEntityModel} into which copy values * @since 1.0.0 */ public static void convertEntity(KapuaEntity kapuaEntity, GwtEntityModel gwtEntity) { @@ -525,67 +531,78 @@ public static void convertEntity(KapuaEntity kapuaEntity, GwtEntityModel gwtEnti gwtEntity.setCreatedBy(convertKapuaId(kapuaEntity.getCreatedBy())); } -// /** -// * @param client -// * @return -// */ -// public static GwtDatastoreDevice convertToDatastoreDevice(ClientInfo client) { -// return new GwtDatastoreDevice(client.getClientId(), client.getLastMessageOn()); -// } -// -// /** -// * @param message -// * @param headers -// * @return -// */ -// public static GwtMessage convertToMessage(DatastoreMessage message, List headers) { -// GwtMessage gwtMessage = new GwtMessage(); -// List semanticParts = message.getChannel().getSemanticParts(); -// StringBuilder semanticTopic = new StringBuilder(); -// for (int i = 0; i < semanticParts.size() - 1; i++) { -// semanticTopic.append(semanticParts.get(i)); -// semanticTopic.append("/"); -// } -// semanticTopic.append(semanticParts.get(semanticParts.size() - 1)); -// gwtMessage.setChannel(semanticTopic.toString()); -// gwtMessage.setClientId(message.getClientId()); -// gwtMessage.setTimestamp(message.getTimestamp()); -// for (GwtHeader header : headers) { -// gwtMessage.set(header.getName(), message.getPayload().getMetrics().get(header.getName())); -// } -// return gwtMessage; -// } -// -// public static GwtDeviceAssets convertKapuaId(DeviceAssets assets) { -// GwtDeviceAssets gwtAssets = new GwtDeviceAssets(); -// List gwtAssetsList = new ArrayList(); -// for (DeviceAsset asset : assets.getAssets()) { -// gwtAssetsList.add(convertKapuaId(asset)); -// } -// gwtAssets.setAssets(gwtAssetsList); -// return gwtAssets; -// } -// -// public static GwtDeviceAsset convertKapuaId(DeviceAsset asset) { -// GwtDeviceAsset gwtAsset = new GwtDeviceAsset(); -// List gwtChannelsList = new ArrayList(); -// gwtAsset.setName(asset.getName()); -// for (DeviceAssetChannel channel : asset.getChannels()) { -// gwtChannelsList.add(convertKapuaId(channel)); -// } -// gwtAsset.setChannels(gwtChannelsList); -// return gwtAsset; -// } -// -// public static GwtDeviceAssetChannel convertKapuaId(DeviceAssetChannel channel) { -// GwtDeviceAssetChannel gwtChannel = new GwtDeviceAssetChannel(); -// gwtChannel.setName(channel.getName()); -// gwtChannel.setError(channel.getError()); -// gwtChannel.setTimestamp(channel.getTimestamp()); -// gwtChannel.setMode(channel.getMode().toString()); -// gwtChannel.setType(ObjectTypeConverter.toString(channel.getType())); -// gwtChannel.setValue(ObjectValueConverter.toString(channel.getValue())); -// return gwtChannel; -// } + public static void convertEntity(KapuaEntityBase kapuaEntity, GwtEntityModel gwtEntity) { + if (kapuaEntity == null || gwtEntity == null) { + return; + } + + gwtEntity.setScopeId(convertKapuaId(kapuaEntity.getScopeId())); + gwtEntity.setId(convertKapuaId(kapuaEntity.getId())); + gwtEntity.setCreatedOn(kapuaEntity.getCreatedOn()); + gwtEntity.setCreatedBy(convertKapuaId(kapuaEntity.getCreatedBy())); + } + + // /** + // * @param client + // * @return + // */ + // public static GwtDatastoreDevice convertToDatastoreDevice(ClientInfo client) { + // return new GwtDatastoreDevice(client.getClientId(), client.getLastMessageOn()); + // } + // + // /** + // * @param message + // * @param headers + // * @return + // */ + // public static GwtMessage convertToMessage(DatastoreMessage message, List headers) { + // GwtMessage gwtMessage = new GwtMessage(); + // List semanticParts = message.getChannel().getSemanticParts(); + // StringBuilder semanticTopic = new StringBuilder(); + // for (int i = 0; i < semanticParts.size() - 1; i++) { + // semanticTopic.append(semanticParts.get(i)); + // semanticTopic.append("/"); + // } + // semanticTopic.append(semanticParts.get(semanticParts.size() - 1)); + // gwtMessage.setChannel(semanticTopic.toString()); + // gwtMessage.setClientId(message.getClientId()); + // gwtMessage.setTimestamp(message.getTimestamp()); + // for (GwtHeader header : headers) { + // gwtMessage.set(header.getName(), message.getPayload().getMetrics().get(header.getName())); + // } + // return gwtMessage; + // } + // + // public static GwtDeviceAssets convertKapuaId(DeviceAssets assets) { + // GwtDeviceAssets gwtAssets = new GwtDeviceAssets(); + // List gwtAssetsList = new ArrayList(); + // for (DeviceAsset asset : assets.getAssets()) { + // gwtAssetsList.add(convertKapuaId(asset)); + // } + // gwtAssets.setAssets(gwtAssetsList); + // return gwtAssets; + // } + // + // public static GwtDeviceAsset convertKapuaId(DeviceAsset asset) { + // GwtDeviceAsset gwtAsset = new GwtDeviceAsset(); + // List gwtChannelsList = new ArrayList(); + // gwtAsset.setName(asset.getName()); + // for (DeviceAssetChannel channel : asset.getChannels()) { + // gwtChannelsList.add(convertKapuaId(channel)); + // } + // gwtAsset.setChannels(gwtChannelsList); + // return gwtAsset; + // } + // + // public static GwtDeviceAssetChannel convertKapuaId(DeviceAssetChannel channel) { + // GwtDeviceAssetChannel gwtChannel = new GwtDeviceAssetChannel(); + // gwtChannel.setName(channel.getName()); + // gwtChannel.setError(channel.getError()); + // gwtChannel.setTimestamp(channel.getTimestamp()); + // gwtChannel.setMode(channel.getMode().toString()); + // gwtChannel.setType(ObjectTypeConverter.toString(channel.getType())); + // gwtChannel.setValue(ObjectValueConverter.toString(channel.getValue())); + // return gwtChannel; + // } } diff --git a/console/module/authentication/pom.xml b/console/module/authentication/pom.xml index 7a709713a4c..6b99af60ef8 100644 --- a/console/module/authentication/pom.xml +++ b/console/module/authentication/pom.xml @@ -19,7 +19,7 @@ kapua-console-module org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-console-module-authentication diff --git a/console/module/authentication/src/main/java/org/eclipse/kapua/app/console/module/authentication/server/GwtCredentialServiceImpl.java b/console/module/authentication/src/main/java/org/eclipse/kapua/app/console/module/authentication/server/GwtCredentialServiceImpl.java index d17ec5c0d06..1e43a1c90d6 100644 --- a/console/module/authentication/src/main/java/org/eclipse/kapua/app/console/module/authentication/server/GwtCredentialServiceImpl.java +++ b/console/module/authentication/src/main/java/org/eclipse/kapua/app/console/module/authentication/server/GwtCredentialServiceImpl.java @@ -12,9 +12,12 @@ *******************************************************************************/ package org.eclipse.kapua.app.console.module.authentication.server; -import com.extjs.gxt.ui.client.data.BasePagingLoadResult; -import com.extjs.gxt.ui.client.data.PagingLoadConfig; -import com.extjs.gxt.ui.client.data.PagingLoadResult; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.concurrent.Callable; + import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.AuthenticationException; import org.eclipse.kapua.KapuaException; @@ -32,30 +35,25 @@ import org.eclipse.kapua.commons.security.KapuaSecurityUtils; import org.eclipse.kapua.locator.KapuaLocator; import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.service.authentication.AuthenticationService; -import org.eclipse.kapua.service.authentication.CredentialsFactory; import org.eclipse.kapua.service.authentication.UsernamePasswordCredentials; import org.eclipse.kapua.service.authentication.credential.Credential; import org.eclipse.kapua.service.authentication.credential.CredentialCreator; -import org.eclipse.kapua.service.authentication.credential.CredentialFactory; import org.eclipse.kapua.service.authentication.credential.CredentialListResult; -import org.eclipse.kapua.service.authentication.credential.CredentialQuery; import org.eclipse.kapua.service.authentication.credential.CredentialService; import org.eclipse.kapua.service.authentication.shiro.utils.AuthenticationUtils; import org.eclipse.kapua.service.authentication.user.PasswordChangeRequest; import org.eclipse.kapua.service.authentication.user.PasswordResetRequest; -import org.eclipse.kapua.service.authentication.user.UserCredentialsFactory; import org.eclipse.kapua.service.authentication.user.UserCredentialsService; import org.eclipse.kapua.service.user.User; -import org.eclipse.kapua.service.user.UserFactory; import org.eclipse.kapua.service.user.UserListResult; +import org.eclipse.kapua.service.user.UserQuery; import org.eclipse.kapua.service.user.UserService; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.List; -import java.util.concurrent.Callable; +import com.extjs.gxt.ui.client.data.BasePagingLoadResult; +import com.extjs.gxt.ui.client.data.PagingLoadConfig; +import com.extjs.gxt.ui.client.data.PagingLoadResult; public class GwtCredentialServiceImpl extends KapuaRemoteServiceServlet implements GwtCredentialService { @@ -66,15 +64,10 @@ public class GwtCredentialServiceImpl extends KapuaRemoteServiceServlet implemen private static final AuthenticationService AUTHENTICATION_SERVICE = LOCATOR.getService(AuthenticationService.class); private static final CredentialService CREDENTIAL_SERVICE = LOCATOR.getService(CredentialService.class); - private static final CredentialFactory CREDENTIAL_FACTORY = LOCATOR.getFactory(CredentialFactory.class); - - private static final CredentialsFactory CREDENTIALS_FACTORY = LOCATOR.getFactory(CredentialsFactory.class); private static final UserService USER_SERVICE = LOCATOR.getService(UserService.class); - private static final UserFactory USER_FACTORY = LOCATOR.getFactory(UserFactory.class); private static final UserCredentialsService USER_CREDENTIALS_SERVICE = LOCATOR.getService(UserCredentialsService.class); - private static final UserCredentialsFactory USER_CREDENTIALS_FACTORY = LOCATOR.getFactory(UserCredentialsFactory.class); private static final AuthenticationUtils AUTHENTICATION_UTILS = LOCATOR.getComponent(AuthenticationUtils.class); // this should be removed due to the refactoring in fixPasswordValidationBypass method @@ -87,7 +80,7 @@ public PagingLoadResult query(PagingLoadConfig loadConfig, final try { // Convert from GWT entity - CredentialQuery credentialQuery = GwtKapuaAuthenticationModelConverter.convertCredentialQuery(loadConfig, gwtCredentialQuery); + KapuaQuery credentialQuery = GwtKapuaAuthenticationModelConverter.convertCredentialQuery(loadConfig, gwtCredentialQuery); // query CredentialListResult credentials = CREDENTIAL_SERVICE.query(credentialQuery); @@ -101,7 +94,7 @@ public PagingLoadResult query(PagingLoadConfig loadConfig, final @Override public UserListResult call() throws Exception { - return USER_SERVICE.query(USER_FACTORY.newQuery(GwtKapuaCommonsModelConverter.convertKapuaId(gwtCredentialQuery.getScopeId()))); + return USER_SERVICE.query(new UserQuery(GwtKapuaCommonsModelConverter.convertKapuaId(gwtCredentialQuery.getScopeId()))); } }); @@ -209,11 +202,11 @@ public User call() throws Exception { } username = user.getName(); final String finalUsername = username; - UsernamePasswordCredentials loginCredentials = CREDENTIALS_FACTORY.newUsernamePasswordCredentials(finalUsername, oldPassword); + UsernamePasswordCredentials loginCredentials = new UsernamePasswordCredentials(finalUsername, oldPassword); loginCredentials.setAuthenticationCode(mfaCode); AUTHENTICATION_SERVICE.verifyCredentials(loginCredentials); - PasswordChangeRequest passwordChangeRequest = USER_CREDENTIALS_FACTORY.newPasswordChangeRequest(); + PasswordChangeRequest passwordChangeRequest = new PasswordChangeRequest(); passwordChangeRequest.setCurrentPassword(oldPassword); passwordChangeRequest.setNewPassword(newPassword); USER_CREDENTIALS_SERVICE.changePassword(scopeId, userId, passwordChangeRequest); @@ -223,7 +216,6 @@ public User call() throws Exception { } } - @Override public void resetPassword(GwtXSRFToken gwtXsrfToken, String stringScopeId, String gwtCredentialId, final String newPassword) throws GwtKapuaException { checkXSRFToken(gwtXsrfToken); @@ -232,7 +224,7 @@ public void resetPassword(GwtXSRFToken gwtXsrfToken, String stringScopeId, Strin final KapuaId scopeId = GwtKapuaCommonsModelConverter.convertKapuaId(stringScopeId); final KapuaId credentialId = GwtKapuaCommonsModelConverter.convertKapuaId(gwtCredentialId); - PasswordResetRequest passwordResetRequest = USER_CREDENTIALS_FACTORY.newPasswordResetRequest(); + PasswordResetRequest passwordResetRequest = new PasswordResetRequest(); passwordResetRequest.setNewPassword(newPassword); USER_CREDENTIALS_SERVICE.resetPassword(scopeId, credentialId, passwordResetRequest); } catch (KapuaException e) { @@ -240,7 +232,6 @@ public void resetPassword(GwtXSRFToken gwtXsrfToken, String stringScopeId, Strin } } - @Override public void unlock(GwtXSRFToken xsrfToken, String stringScopeId, String gwtCredentialId) throws GwtKapuaException { diff --git a/console/module/authentication/src/main/java/org/eclipse/kapua/app/console/module/authentication/shared/util/GwtKapuaAuthenticationModelConverter.java b/console/module/authentication/src/main/java/org/eclipse/kapua/app/console/module/authentication/shared/util/GwtKapuaAuthenticationModelConverter.java index d895a0d4cd9..a5402b73e00 100644 --- a/console/module/authentication/src/main/java/org/eclipse/kapua/app/console/module/authentication/shared/util/GwtKapuaAuthenticationModelConverter.java +++ b/console/module/authentication/src/main/java/org/eclipse/kapua/app/console/module/authentication/shared/util/GwtKapuaAuthenticationModelConverter.java @@ -12,9 +12,6 @@ *******************************************************************************/ package org.eclipse.kapua.app.console.module.authentication.shared.util; -import com.extjs.gxt.ui.client.Style.SortDir; -import com.extjs.gxt.ui.client.data.BaseModel; -import com.extjs.gxt.ui.client.data.PagingLoadConfig; import org.apache.commons.lang3.StringUtils; import org.eclipse.kapua.app.console.module.api.shared.util.GwtKapuaCommonsModelConverter; import org.eclipse.kapua.app.console.module.authentication.shared.model.GwtCredential; @@ -26,16 +23,19 @@ import org.eclipse.kapua.model.KapuaEntity; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.model.query.FieldSortCriteria; +import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.model.query.SortOrder; import org.eclipse.kapua.model.query.predicate.AndPredicate; import org.eclipse.kapua.service.authentication.credential.Credential; import org.eclipse.kapua.service.authentication.credential.CredentialAttributes; import org.eclipse.kapua.service.authentication.credential.CredentialCreator; import org.eclipse.kapua.service.authentication.credential.CredentialFactory; -import org.eclipse.kapua.service.authentication.credential.CredentialQuery; import org.eclipse.kapua.service.authentication.credential.CredentialStatus; import org.eclipse.kapua.service.authentication.credential.mfa.MfaOptionCreator; -import org.eclipse.kapua.service.authentication.credential.mfa.MfaOptionFactory; + +import com.extjs.gxt.ui.client.Style.SortDir; +import com.extjs.gxt.ui.client.data.BaseModel; +import com.extjs.gxt.ui.client.data.PagingLoadConfig; /** * Utility class for convertKapuaId {@link BaseModel}s to {@link KapuaEntity}ies and other Kapua models @@ -45,22 +45,23 @@ public class GwtKapuaAuthenticationModelConverter { // Get Services private static final KapuaLocator LOCATOR = KapuaLocator.getInstance(); private static final CredentialFactory CREDENTIAL_FACTORY = LOCATOR.getFactory(CredentialFactory.class); - private static final MfaOptionFactory MFA_OPTION_FACTORY = LOCATOR.getFactory(MfaOptionFactory.class); private GwtKapuaAuthenticationModelConverter() { } /** - * Converts a {@link GwtCredentialQuery} into a {@link CredentialQuery} object for backend usage + * Converts a {@link GwtCredentialQuery} into a {@link KapuaQuery} object for backend usage * - * @param loadConfig the load configuration - * @param gwtCredentialQuery the {@link GwtCredentialQuery} to convertKapuaId - * @return the converted {@link CredentialQuery} + * @param loadConfig + * the load configuration + * @param gwtCredentialQuery + * the {@link GwtCredentialQuery} to convertKapuaId + * @return the converted {@link KapuaQuery} */ - public static CredentialQuery convertCredentialQuery(PagingLoadConfig loadConfig, GwtCredentialQuery gwtCredentialQuery) { + public static KapuaQuery convertCredentialQuery(PagingLoadConfig loadConfig, GwtCredentialQuery gwtCredentialQuery) { // Convert query - CredentialQuery query = CREDENTIAL_FACTORY.newQuery(GwtKapuaCommonsModelConverter.convertKapuaId(gwtCredentialQuery.getScopeId())); + KapuaQuery query = new KapuaQuery(GwtKapuaCommonsModelConverter.convertKapuaId(gwtCredentialQuery.getScopeId())); AndPredicate andPredicate = query.andPredicate(); if (gwtCredentialQuery.getUserId() != null && !gwtCredentialQuery.getUserId().trim().isEmpty()) { @@ -93,20 +94,20 @@ public static CredentialQuery convertCredentialQuery(PagingLoadConfig loadConfig /** * Converts a {@link GwtCredentialCreator} into a {@link CredentialCreator} object for backend usage * - * @param gwtCredentialCreator the {@link GwtCredentialCreator} to convertKapuaId + * @param gwtCredentialCreator + * the {@link GwtCredentialCreator} to convertKapuaId * @return the converted {@link CredentialCreator} */ public static CredentialCreator convertCredentialCreator(GwtCredentialCreator gwtCredentialCreator) { // Convert scopeId KapuaId scopeId = GwtKapuaCommonsModelConverter.convertKapuaId(gwtCredentialCreator.getScopeId()); - CredentialCreator credentialCreator = CREDENTIAL_FACTORY - .newCreator(scopeId, - GwtKapuaCommonsModelConverter.convertKapuaId(gwtCredentialCreator.getUserId()), - gwtCredentialCreator.getCredentialType(), - gwtCredentialCreator.getCredentialPlainKey(), - convertCredentialStatus(gwtCredentialCreator.getCredentialStatus()), - gwtCredentialCreator.getExpirationDate()); + CredentialCreator credentialCreator = new CredentialCreator(scopeId, + GwtKapuaCommonsModelConverter.convertKapuaId(gwtCredentialCreator.getUserId()), + gwtCredentialCreator.getCredentialType(), + gwtCredentialCreator.getCredentialPlainKey(), + convertCredentialStatus(gwtCredentialCreator.getCredentialStatus()), + gwtCredentialCreator.getExpirationDate()); // Return converted return credentialCreator; } @@ -114,7 +115,8 @@ public static CredentialCreator convertCredentialCreator(GwtCredentialCreator gw /** * Converts a {@link GwtCredential} into a {@link Credential} object for backend usage * - * @param gwtCredential the {@link GwtCredential} to convertKapuaId + * @param gwtCredential + * the {@link GwtCredential} to convertKapuaId * @return the converted {@link Credential} */ public static Credential convertCredential(GwtCredential gwtCredential) { @@ -146,7 +148,7 @@ public static CredentialStatus convertCredentialStatus(GwtCredentialStatus gwtCr public static MfaOptionCreator convertMfaCredentialOptionsCreator(GwtMfaCredentialOptionsCreator gwtMfaCredentialOptionsCreator) { KapuaId scopeId = GwtKapuaCommonsModelConverter.convertKapuaId(gwtMfaCredentialOptionsCreator.getScopeId()); KapuaId userId = GwtKapuaCommonsModelConverter.convertKapuaId(gwtMfaCredentialOptionsCreator.getUserId()); - return MFA_OPTION_FACTORY.newCreator(scopeId, userId); + return new MfaOptionCreator(scopeId, userId); } } diff --git a/console/module/authorization/pom.xml b/console/module/authorization/pom.xml index 1f36a6a9d74..0cf330f97e7 100644 --- a/console/module/authorization/pom.xml +++ b/console/module/authorization/pom.xml @@ -19,7 +19,7 @@ kapua-console-module org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-console-module-authorization diff --git a/console/module/authorization/src/main/java/org/eclipse/kapua/app/console/module/authorization/server/GwtAccessInfoServiceImpl.java b/console/module/authorization/src/main/java/org/eclipse/kapua/app/console/module/authorization/server/GwtAccessInfoServiceImpl.java index 2d8286a838c..5f1264e8f99 100644 --- a/console/module/authorization/src/main/java/org/eclipse/kapua/app/console/module/authorization/server/GwtAccessInfoServiceImpl.java +++ b/console/module/authorization/src/main/java/org/eclipse/kapua/app/console/module/authorization/server/GwtAccessInfoServiceImpl.java @@ -26,7 +26,6 @@ import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.authorization.access.AccessInfo; import org.eclipse.kapua.service.authorization.access.AccessInfoCreator; -import org.eclipse.kapua.service.authorization.access.AccessInfoFactory; import org.eclipse.kapua.service.authorization.access.AccessInfoService; import org.eclipse.kapua.service.authorization.access.AccessPermission; import org.eclipse.kapua.service.authorization.access.AccessPermissionListResult; @@ -110,8 +109,7 @@ public GwtAccessInfo findByUserIdOrCreate(String scopeShortId, String userShortI AccessInfoService accessInfoService = locator.getService(AccessInfoService.class); AccessInfo accessInfo = accessInfoService.findByUserId(scopeId, userId); if (accessInfo == null) { - AccessInfoFactory accessInfoFactory = locator.getFactory(AccessInfoFactory.class); - AccessInfoCreator accessInfoCreator = accessInfoFactory.newCreator(scopeId); + AccessInfoCreator accessInfoCreator = new AccessInfoCreator(scopeId); accessInfoCreator.setUserId(userId); accessInfo = accessInfoService.create(accessInfoCreator); } diff --git a/console/module/authorization/src/main/java/org/eclipse/kapua/app/console/module/authorization/server/GwtAccessPermissionServiceImpl.java b/console/module/authorization/src/main/java/org/eclipse/kapua/app/console/module/authorization/server/GwtAccessPermissionServiceImpl.java index 37221902f34..0f92c011cd4 100644 --- a/console/module/authorization/src/main/java/org/eclipse/kapua/app/console/module/authorization/server/GwtAccessPermissionServiceImpl.java +++ b/console/module/authorization/src/main/java/org/eclipse/kapua/app/console/module/authorization/server/GwtAccessPermissionServiceImpl.java @@ -12,10 +12,10 @@ *******************************************************************************/ package org.eclipse.kapua.app.console.module.authorization.server; -import com.extjs.gxt.ui.client.Style.SortDir; -import com.extjs.gxt.ui.client.data.BasePagingLoadResult; -import com.extjs.gxt.ui.client.data.PagingLoadConfig; -import com.extjs.gxt.ui.client.data.PagingLoadResult; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.Callable; + import org.apache.commons.lang3.StringUtils; import org.eclipse.kapua.app.console.module.api.client.GwtKapuaException; import org.eclipse.kapua.app.console.module.api.server.KapuaRemoteServiceServlet; @@ -32,6 +32,7 @@ import org.eclipse.kapua.model.KapuaEntityAttributes; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.model.query.FieldSortCriteria; +import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.model.query.SortOrder; import org.eclipse.kapua.service.account.Account; import org.eclipse.kapua.service.account.AccountService; @@ -40,18 +41,17 @@ import org.eclipse.kapua.service.authorization.access.AccessPermission; import org.eclipse.kapua.service.authorization.access.AccessPermissionAttributes; import org.eclipse.kapua.service.authorization.access.AccessPermissionCreator; -import org.eclipse.kapua.service.authorization.access.AccessPermissionFactory; import org.eclipse.kapua.service.authorization.access.AccessPermissionListResult; -import org.eclipse.kapua.service.authorization.access.AccessPermissionQuery; import org.eclipse.kapua.service.authorization.access.AccessPermissionService; import org.eclipse.kapua.service.authorization.group.Group; import org.eclipse.kapua.service.authorization.group.GroupService; import org.eclipse.kapua.service.user.User; import org.eclipse.kapua.service.user.UserService; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.Callable; +import com.extjs.gxt.ui.client.Style.SortDir; +import com.extjs.gxt.ui.client.data.BasePagingLoadResult; +import com.extjs.gxt.ui.client.data.PagingLoadConfig; +import com.extjs.gxt.ui.client.data.PagingLoadResult; public class GwtAccessPermissionServiceImpl extends KapuaRemoteServiceServlet implements GwtAccessPermissionService { @@ -62,7 +62,6 @@ public class GwtAccessPermissionServiceImpl extends KapuaRemoteServiceServlet im private static final AccessInfoService ACCESS_INFO_SERVICE = LOCATOR.getService(AccessInfoService.class); private static final AccessPermissionService ACCESS_PERMISSION_SERVICE = LOCATOR.getService(AccessPermissionService.class); - private static final AccessPermissionFactory ACCESS_PERMISSION_FACTORY = LOCATOR.getFactory(AccessPermissionFactory.class); private static final AccountService ACCOUNT_SERVICE = LOCATOR.getService(AccountService.class); private static final UserService USER_SERVICE = LOCATOR.getService(UserService.class); @@ -124,7 +123,7 @@ public PagingLoadResult findByUserId(PagingLoadConfig loadC AccessInfo accessInfo = ACCESS_INFO_SERVICE.findByUserId(scopeId, userId); if (accessInfo != null) { - AccessPermissionQuery query = ACCESS_PERMISSION_FACTORY.newQuery(scopeId); + final KapuaQuery query = new KapuaQuery(scopeId); query.setPredicate(query.attributePredicate(AccessPermissionAttributes.ACCESS_INFO_ID, accessInfo.getId())); query.setLimit(loadConfig.getLimit()); query.setOffset(loadConfig.getOffset()); diff --git a/console/module/authorization/src/main/java/org/eclipse/kapua/app/console/module/authorization/server/GwtAccessRoleServiceImpl.java b/console/module/authorization/src/main/java/org/eclipse/kapua/app/console/module/authorization/server/GwtAccessRoleServiceImpl.java index 54cf218c494..716fe73b3ae 100644 --- a/console/module/authorization/src/main/java/org/eclipse/kapua/app/console/module/authorization/server/GwtAccessRoleServiceImpl.java +++ b/console/module/authorization/src/main/java/org/eclipse/kapua/app/console/module/authorization/server/GwtAccessRoleServiceImpl.java @@ -12,10 +12,10 @@ *******************************************************************************/ package org.eclipse.kapua.app.console.module.authorization.server; -import com.extjs.gxt.ui.client.Style.SortDir; -import com.extjs.gxt.ui.client.data.BasePagingLoadResult; -import com.extjs.gxt.ui.client.data.PagingLoadConfig; -import com.extjs.gxt.ui.client.data.PagingLoadResult; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.Callable; + import org.apache.commons.lang3.StringUtils; import org.eclipse.kapua.app.console.module.api.client.GwtKapuaException; import org.eclipse.kapua.app.console.module.api.server.KapuaRemoteServiceServlet; @@ -31,6 +31,7 @@ import org.eclipse.kapua.locator.KapuaLocator; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.model.query.FieldSortCriteria; +import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.model.query.SortOrder; import org.eclipse.kapua.service.authorization.access.AccessInfo; import org.eclipse.kapua.service.authorization.access.AccessInfoService; @@ -38,18 +39,17 @@ import org.eclipse.kapua.service.authorization.access.AccessRole; import org.eclipse.kapua.service.authorization.access.AccessRoleAttributes; import org.eclipse.kapua.service.authorization.access.AccessRoleCreator; -import org.eclipse.kapua.service.authorization.access.AccessRoleFactory; import org.eclipse.kapua.service.authorization.access.AccessRoleListResult; -import org.eclipse.kapua.service.authorization.access.AccessRoleQuery; import org.eclipse.kapua.service.authorization.access.AccessRoleService; import org.eclipse.kapua.service.authorization.role.Role; import org.eclipse.kapua.service.authorization.role.RoleService; import org.eclipse.kapua.service.user.User; import org.eclipse.kapua.service.user.UserService; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.Callable; +import com.extjs.gxt.ui.client.Style.SortDir; +import com.extjs.gxt.ui.client.data.BasePagingLoadResult; +import com.extjs.gxt.ui.client.data.PagingLoadConfig; +import com.extjs.gxt.ui.client.data.PagingLoadResult; public class GwtAccessRoleServiceImpl extends KapuaRemoteServiceServlet implements GwtAccessRoleService { @@ -111,7 +111,6 @@ public PagingLoadResult findByUserId(PagingLoadConfig loadConfig, RoleService roleService = locator.getService(RoleService.class); AccessInfoService accessInfoService = locator.getService(AccessInfoService.class); AccessRoleService accessRoleService = locator.getService(AccessRoleService.class); - AccessRoleFactory accessRoleFactory = locator.getFactory(AccessRoleFactory.class); final UserService userService = locator.getService(UserService.class); final KapuaId scopeId = GwtKapuaCommonsModelConverter.convertKapuaId(scopeShortId); @@ -120,7 +119,7 @@ public PagingLoadResult findByUserId(PagingLoadConfig loadConfig, AccessInfo accessInfo = accessInfoService.findByUserId(scopeId, userId); if (accessInfo != null) { - AccessRoleQuery query = accessRoleFactory.newQuery(scopeId); + KapuaQuery query = new KapuaQuery(scopeId); query.setPredicate(query.attributePredicate(AccessPermissionAttributes.ACCESS_INFO_ID, accessInfo.getId())); query.setLimit(loadConfig.getLimit()); query.setOffset(loadConfig.getOffset()); diff --git a/console/module/authorization/src/main/java/org/eclipse/kapua/app/console/module/authorization/server/GwtDomainRegistryServiceImpl.java b/console/module/authorization/src/main/java/org/eclipse/kapua/app/console/module/authorization/server/GwtDomainRegistryServiceImpl.java index 3e4e58861fa..ceb7128ba1c 100644 --- a/console/module/authorization/src/main/java/org/eclipse/kapua/app/console/module/authorization/server/GwtDomainRegistryServiceImpl.java +++ b/console/module/authorization/src/main/java/org/eclipse/kapua/app/console/module/authorization/server/GwtDomainRegistryServiceImpl.java @@ -12,6 +12,10 @@ *******************************************************************************/ package org.eclipse.kapua.app.console.module.authorization.server; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + import org.eclipse.kapua.app.console.module.api.client.GwtKapuaException; import org.eclipse.kapua.app.console.module.api.server.KapuaRemoteServiceServlet; import org.eclipse.kapua.app.console.module.api.server.util.KapuaExceptionHandler; @@ -21,30 +25,24 @@ import org.eclipse.kapua.app.console.module.authorization.shared.util.KapuaGwtAuthorizationModelConverter; import org.eclipse.kapua.locator.KapuaLocator; import org.eclipse.kapua.model.domain.Actions; +import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.service.authorization.domain.Domain; -import org.eclipse.kapua.service.authorization.domain.DomainFactory; import org.eclipse.kapua.service.authorization.domain.DomainListResult; -import org.eclipse.kapua.service.authorization.domain.DomainQuery; import org.eclipse.kapua.service.authorization.domain.DomainRegistryService; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - public class GwtDomainRegistryServiceImpl extends KapuaRemoteServiceServlet implements GwtDomainRegistryService { private static final long serialVersionUID = -699492835893299489L; private final KapuaLocator locator = KapuaLocator.getInstance(); private final DomainRegistryService domainRegistryService = locator.getService(DomainRegistryService.class); - private final DomainFactory domainFactory = locator.getFactory(DomainFactory.class); - @Override public List findAll() throws GwtKapuaException { List gwtDomainList = new ArrayList(); try { - DomainQuery query = domainFactory.newQuery(null); + KapuaQuery query = new KapuaQuery((KapuaId) null); DomainListResult list = domainRegistryService.query(query); for (Domain domain : list.getItems()) { diff --git a/console/module/authorization/src/main/java/org/eclipse/kapua/app/console/module/authorization/server/GwtGroupServiceImpl.java b/console/module/authorization/src/main/java/org/eclipse/kapua/app/console/module/authorization/server/GwtGroupServiceImpl.java index 0268f08bc7e..e5ac3d2b500 100644 --- a/console/module/authorization/src/main/java/org/eclipse/kapua/app/console/module/authorization/server/GwtGroupServiceImpl.java +++ b/console/module/authorization/src/main/java/org/eclipse/kapua/app/console/module/authorization/server/GwtGroupServiceImpl.java @@ -12,11 +12,12 @@ *******************************************************************************/ package org.eclipse.kapua.app.console.module.authorization.server; -import com.extjs.gxt.ui.client.data.BaseListLoadResult; -import com.extjs.gxt.ui.client.data.BasePagingLoadResult; -import com.extjs.gxt.ui.client.data.ListLoadResult; -import com.extjs.gxt.ui.client.data.PagingLoadConfig; -import com.extjs.gxt.ui.client.data.PagingLoadResult; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.Callable; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.app.console.module.api.client.GwtKapuaException; import org.eclipse.kapua.app.console.module.api.server.KapuaRemoteServiceServlet; @@ -35,20 +36,19 @@ import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.authorization.group.Group; import org.eclipse.kapua.service.authorization.group.GroupCreator; -import org.eclipse.kapua.service.authorization.group.GroupFactory; import org.eclipse.kapua.service.authorization.group.GroupListResult; import org.eclipse.kapua.service.authorization.group.GroupQuery; import org.eclipse.kapua.service.authorization.group.GroupService; import org.eclipse.kapua.service.user.User; -import org.eclipse.kapua.service.user.UserFactory; import org.eclipse.kapua.service.user.UserListResult; +import org.eclipse.kapua.service.user.UserQuery; import org.eclipse.kapua.service.user.UserService; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.Callable; +import com.extjs.gxt.ui.client.data.BaseListLoadResult; +import com.extjs.gxt.ui.client.data.BasePagingLoadResult; +import com.extjs.gxt.ui.client.data.ListLoadResult; +import com.extjs.gxt.ui.client.data.PagingLoadConfig; +import com.extjs.gxt.ui.client.data.PagingLoadResult; public class GwtGroupServiceImpl extends KapuaRemoteServiceServlet implements GwtGroupService { @@ -57,10 +57,8 @@ public class GwtGroupServiceImpl extends KapuaRemoteServiceServlet implements Gw private static final KapuaLocator LOCATOR = KapuaLocator.getInstance(); private static final GroupService GROUP_SERVICE = LOCATOR.getService(GroupService.class); - private static final GroupFactory GROUP_FACTORY = LOCATOR.getFactory(GroupFactory.class); private static final UserService USER_SERVICE = LOCATOR.getService(UserService.class); - private static final UserFactory USER_FACTORY = LOCATOR.getFactory(UserFactory.class); private static final String ENTITY_INFO = "entityInfo"; @@ -70,7 +68,7 @@ public GwtGroup create(GwtGroupCreator gwtGroupCreator) throws GwtKapuaException try { KapuaId scopeId = KapuaEid.parseCompactId(gwtGroupCreator.getScopeId()); - GroupCreator groupCreator = GROUP_FACTORY.newCreator(scopeId, gwtGroupCreator.getName()); + GroupCreator groupCreator = new GroupCreator(scopeId, gwtGroupCreator.getName()); groupCreator.setDescription(gwtGroupCreator.getDescription()); Group group = GROUP_SERVICE.create(groupCreator); @@ -123,7 +121,7 @@ public GwtGroup find(String scopeShortId, String groupShortId) throws GwtKapuaEx @Override public PagingLoadResult query(PagingLoadConfig loadConfig, - final GwtGroupQuery gwtGroupQuery) throws GwtKapuaException { + final GwtGroupQuery gwtGroupQuery) throws GwtKapuaException { int totalLength = 0; List gwtGroupList = new ArrayList(); try { @@ -136,7 +134,7 @@ public PagingLoadResult query(PagingLoadConfig loadConfig, @Override public UserListResult call() throws Exception { - return USER_SERVICE.query(USER_FACTORY.newQuery(null)); + return USER_SERVICE.query(new UserQuery(null)); } }); @@ -174,7 +172,7 @@ public void delete(String scopeIdString, String groupIdString) throws GwtKapuaEx @Override public ListLoadResult getGroupDescription(String scopeShortId, - String groupShortId) throws GwtKapuaException { + String groupShortId) throws GwtKapuaException { List gwtGroupDescription = new ArrayList(); try { final KapuaId scopeId = KapuaEid.parseCompactId(scopeShortId); @@ -187,7 +185,7 @@ public ListLoadResult getGroupDescription(String scopeShortId, @Override public UserListResult call() throws Exception { - return USER_SERVICE.query(USER_FACTORY.newQuery(null)); + return USER_SERVICE.query(new UserQuery(null)); } }); @@ -216,7 +214,7 @@ public UserListResult call() throws Exception { @Override public List findAll(String scopeId) throws GwtKapuaException { List groupList = new ArrayList(); - GroupQuery query = GROUP_FACTORY.newQuery(GwtKapuaCommonsModelConverter.convertKapuaId(scopeId)); + GroupQuery query = new GroupQuery(GwtKapuaCommonsModelConverter.convertKapuaId(scopeId)); try { GroupListResult result = GROUP_SERVICE.query(query); for (Group group : result.getItems()) { diff --git a/console/module/authorization/src/main/java/org/eclipse/kapua/app/console/module/authorization/server/GwtRoleServiceImpl.java b/console/module/authorization/src/main/java/org/eclipse/kapua/app/console/module/authorization/server/GwtRoleServiceImpl.java index b9b117893fe..00fc259cd71 100644 --- a/console/module/authorization/src/main/java/org/eclipse/kapua/app/console/module/authorization/server/GwtRoleServiceImpl.java +++ b/console/module/authorization/src/main/java/org/eclipse/kapua/app/console/module/authorization/server/GwtRoleServiceImpl.java @@ -12,12 +12,12 @@ *******************************************************************************/ package org.eclipse.kapua.app.console.module.authorization.server; -import com.extjs.gxt.ui.client.Style.SortDir; -import com.extjs.gxt.ui.client.data.BaseListLoadResult; -import com.extjs.gxt.ui.client.data.BasePagingLoadResult; -import com.extjs.gxt.ui.client.data.ListLoadResult; -import com.extjs.gxt.ui.client.data.PagingLoadConfig; -import com.extjs.gxt.ui.client.data.PagingLoadResult; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.Callable; + import org.apache.commons.lang3.StringUtils; import org.eclipse.kapua.app.console.module.api.client.GwtKapuaException; import org.eclipse.kapua.app.console.module.api.server.KapuaRemoteServiceServlet; @@ -40,6 +40,7 @@ import org.eclipse.kapua.model.KapuaEntityAttributes; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.model.query.FieldSortCriteria; +import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.model.query.SortOrder; import org.eclipse.kapua.service.account.Account; import org.eclipse.kapua.service.account.AccountService; @@ -47,27 +48,25 @@ import org.eclipse.kapua.service.authorization.group.GroupService; import org.eclipse.kapua.service.authorization.role.Role; import org.eclipse.kapua.service.authorization.role.RoleCreator; -import org.eclipse.kapua.service.authorization.role.RoleFactory; import org.eclipse.kapua.service.authorization.role.RoleListResult; import org.eclipse.kapua.service.authorization.role.RolePermission; import org.eclipse.kapua.service.authorization.role.RolePermissionAttributes; import org.eclipse.kapua.service.authorization.role.RolePermissionCreator; -import org.eclipse.kapua.service.authorization.role.RolePermissionFactory; import org.eclipse.kapua.service.authorization.role.RolePermissionListResult; -import org.eclipse.kapua.service.authorization.role.RolePermissionQuery; import org.eclipse.kapua.service.authorization.role.RolePermissionService; import org.eclipse.kapua.service.authorization.role.RoleQuery; import org.eclipse.kapua.service.authorization.role.RoleService; import org.eclipse.kapua.service.user.User; -import org.eclipse.kapua.service.user.UserFactory; import org.eclipse.kapua.service.user.UserListResult; +import org.eclipse.kapua.service.user.UserQuery; import org.eclipse.kapua.service.user.UserService; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.Callable; +import com.extjs.gxt.ui.client.Style.SortDir; +import com.extjs.gxt.ui.client.data.BaseListLoadResult; +import com.extjs.gxt.ui.client.data.BasePagingLoadResult; +import com.extjs.gxt.ui.client.data.ListLoadResult; +import com.extjs.gxt.ui.client.data.PagingLoadConfig; +import com.extjs.gxt.ui.client.data.PagingLoadResult; public class GwtRoleServiceImpl extends KapuaRemoteServiceServlet implements GwtRoleService { @@ -78,13 +77,10 @@ public class GwtRoleServiceImpl extends KapuaRemoteServiceServlet implements Gwt private static final AccountService ACCOUNT_SERVICE = LOCATOR.getService(AccountService.class); private static final RoleService ROLE_SERVICE = LOCATOR.getService(RoleService.class); - private static final RoleFactory ROLE_FACTORY = LOCATOR.getFactory(RoleFactory.class); private static final RolePermissionService ROLE_PERMISSION_SERVICE = LOCATOR.getService(RolePermissionService.class); - private static final RolePermissionFactory ROLE_PERMISSION_FACTORY = LOCATOR.getFactory(RolePermissionFactory.class); private static final UserService USER_SERVICE = LOCATOR.getService(UserService.class); - private static final UserFactory USER_FACTORY = LOCATOR.getFactory(UserFactory.class); private static final GroupService GROUP_SERVICE = LOCATOR.getService(GroupService.class); @@ -175,7 +171,7 @@ public PagingLoadResult query(PagingLoadConfig loadConfig, final GwtRol @Override public UserListResult call() throws Exception { - return USER_SERVICE.query(USER_FACTORY.newQuery(null)); + return USER_SERVICE.query(new UserQuery(null)); } }); @@ -215,7 +211,7 @@ public ListLoadResult getRoleDescription(String scopeShortId, @Override public UserListResult call() throws Exception { - return USER_SERVICE.query(USER_FACTORY.newQuery(null)); + return USER_SERVICE.query(new UserQuery(null)); } }); @@ -252,7 +248,7 @@ public PagingLoadResult getRolePermissions(PagingLoadConfig l KapuaId roleId = GwtKapuaCommonsModelConverter.convertKapuaId(roleShortId); // Get permissions assigned to the Role - RolePermissionQuery query = ROLE_PERMISSION_FACTORY.newQuery(scopeId); + KapuaQuery query = new KapuaQuery(scopeId); query.setPredicate(query.attributePredicate(RolePermissionAttributes.ROLE_ID, roleId)); query.setLimit(loadConfig.getLimit()); query.setOffset(loadConfig.getOffset()); @@ -339,7 +335,7 @@ public GwtRolePermission addRolePermission(GwtXSRFToken gwtXsrfToken, GwtRolePer try { KapuaId scopeId = GwtKapuaCommonsModelConverter.convertKapuaId(gwtRolePermissionCreator.getScopeId()); - RolePermissionCreator rolePermissionCreator = ROLE_PERMISSION_FACTORY.newCreator(scopeId); + RolePermissionCreator rolePermissionCreator = new RolePermissionCreator(scopeId); rolePermissionCreator.setRoleId(GwtKapuaCommonsModelConverter.convertKapuaId(gwtRolePermissionCreator.getRoleId())); rolePermissionCreator.setScopeId(scopeId); rolePermissionCreator.setPermission(GwtKapuaAuthorizationModelConverter.convertPermission(gwtPermission)); @@ -372,7 +368,7 @@ public List findAll(String scopeIdString) throws GwtKapuaException { KapuaId scopeId = KapuaEid.parseCompactId(scopeIdString); List gwtRoleList = new ArrayList(); try { - RoleQuery query = ROLE_FACTORY.newQuery(scopeId); + RoleQuery query = new RoleQuery(scopeId); RoleListResult list = ROLE_SERVICE.query(query); for (Role role : list.getItems()) { diff --git a/console/module/authorization/src/main/java/org/eclipse/kapua/app/console/module/authorization/shared/util/GwtKapuaAuthorizationModelConverter.java b/console/module/authorization/src/main/java/org/eclipse/kapua/app/console/module/authorization/shared/util/GwtKapuaAuthorizationModelConverter.java index d692c1e08a5..11b96b6493e 100644 --- a/console/module/authorization/src/main/java/org/eclipse/kapua/app/console/module/authorization/shared/util/GwtKapuaAuthorizationModelConverter.java +++ b/console/module/authorization/src/main/java/org/eclipse/kapua/app/console/module/authorization/shared/util/GwtKapuaAuthorizationModelConverter.java @@ -12,9 +12,9 @@ *******************************************************************************/ package org.eclipse.kapua.app.console.module.authorization.shared.util; -import com.extjs.gxt.ui.client.Style.SortDir; -import com.extjs.gxt.ui.client.data.BaseModel; -import com.extjs.gxt.ui.client.data.PagingLoadConfig; +import java.util.HashSet; +import java.util.Set; + import org.apache.commons.lang3.StringUtils; import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.KapuaIllegalArgumentException; @@ -22,7 +22,6 @@ import org.eclipse.kapua.app.console.module.authorization.shared.model.GwtAccessInfoCreator; import org.eclipse.kapua.app.console.module.authorization.shared.model.GwtAccessPermissionCreator; import org.eclipse.kapua.app.console.module.authorization.shared.model.GwtAccessRoleCreator; -import org.eclipse.kapua.app.console.module.authorization.shared.model.GwtAccessRoleQuery; import org.eclipse.kapua.app.console.module.authorization.shared.model.GwtDomain; import org.eclipse.kapua.app.console.module.authorization.shared.model.GwtGroupQuery; import org.eclipse.kapua.app.console.module.authorization.shared.model.GwtPermission; @@ -31,33 +30,24 @@ import org.eclipse.kapua.app.console.module.authorization.shared.model.GwtRoleCreator; import org.eclipse.kapua.app.console.module.authorization.shared.model.GwtRolePermission; import org.eclipse.kapua.app.console.module.authorization.shared.model.GwtRoleQuery; -import org.eclipse.kapua.commons.model.id.KapuaEid; import org.eclipse.kapua.locator.KapuaLocator; import org.eclipse.kapua.model.KapuaEntity; import org.eclipse.kapua.model.domain.Actions; import org.eclipse.kapua.model.domain.Domain; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.model.query.FieldSortCriteria; +import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.model.query.SortOrder; import org.eclipse.kapua.model.query.predicate.AndPredicate; import org.eclipse.kapua.model.query.predicate.AttributePredicate.Operator; import org.eclipse.kapua.service.authorization.access.AccessInfoCreator; -import org.eclipse.kapua.service.authorization.access.AccessInfoFactory; import org.eclipse.kapua.service.authorization.access.AccessPermissionCreator; -import org.eclipse.kapua.service.authorization.access.AccessPermissionFactory; -import org.eclipse.kapua.service.authorization.access.AccessRoleAttributes; import org.eclipse.kapua.service.authorization.access.AccessRoleCreator; -import org.eclipse.kapua.service.authorization.access.AccessRoleFactory; -import org.eclipse.kapua.service.authorization.access.AccessRoleQuery; -import org.eclipse.kapua.service.authorization.domain.DomainFactory; import org.eclipse.kapua.service.authorization.domain.DomainListResult; -import org.eclipse.kapua.service.authorization.domain.DomainQuery; import org.eclipse.kapua.service.authorization.domain.DomainRegistryService; import org.eclipse.kapua.service.authorization.group.GroupAttributes; -import org.eclipse.kapua.service.authorization.group.GroupFactory; import org.eclipse.kapua.service.authorization.group.GroupQuery; import org.eclipse.kapua.service.authorization.permission.Permission; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; import org.eclipse.kapua.service.authorization.role.Role; import org.eclipse.kapua.service.authorization.role.RoleAttributes; import org.eclipse.kapua.service.authorization.role.RoleCreator; @@ -66,8 +56,9 @@ import org.eclipse.kapua.service.authorization.role.RolePermissionFactory; import org.eclipse.kapua.service.authorization.role.RoleQuery; -import java.util.HashSet; -import java.util.Set; +import com.extjs.gxt.ui.client.Style.SortDir; +import com.extjs.gxt.ui.client.data.BaseModel; +import com.extjs.gxt.ui.client.data.PagingLoadConfig; /** * Utility class for convertKapuaId {@link BaseModel}s to {@link KapuaEntity}ies and other Kapua models @@ -77,17 +68,13 @@ public class GwtKapuaAuthorizationModelConverter { private static final KapuaLocator LOCATOR = KapuaLocator.getInstance(); private static final DomainRegistryService DOMAIN_REGISTRY_SERVICE = LOCATOR.getService(DomainRegistryService.class); - private static final DomainFactory DOMAIN_FACTORY = LOCATOR.getFactory(DomainFactory.class); private GwtKapuaAuthorizationModelConverter() { } public static GroupQuery convertGroupQuery(PagingLoadConfig loadConfig, - GwtGroupQuery gwtGroupQuery) { - KapuaLocator locator = KapuaLocator.getInstance(); - GroupFactory groupFactory = locator.getFactory(GroupFactory.class); - - GroupQuery query = groupFactory.newQuery(GwtKapuaCommonsModelConverter.convertKapuaId(gwtGroupQuery.getScopeId())); + GwtGroupQuery gwtGroupQuery) { + GroupQuery query = new GroupQuery(GwtKapuaCommonsModelConverter.convertKapuaId(gwtGroupQuery.getScopeId())); AndPredicate predicate = query.andPredicate(); if (gwtGroupQuery.getName() != null && !gwtGroupQuery.getName().isEmpty()) { @@ -116,18 +103,16 @@ public static GroupQuery convertGroupQuery(PagingLoadConfig loadConfig, /** * Converts a {@link GwtRoleQuery} into a {@link Role} object for backend usage * - * @param loadConfig the load configuration - * @param gwtRoleQuery the {@link GwtRoleQuery} to convertKapuaId + * @param loadConfig + * the load configuration + * @param gwtRoleQuery + * the {@link GwtRoleQuery} to convertKapuaId * @return the converted {@link RoleQuery} */ public static RoleQuery convertRoleQuery(PagingLoadConfig loadConfig, GwtRoleQuery gwtRoleQuery) { - // Get Services - KapuaLocator locator = KapuaLocator.getInstance(); - RoleFactory roleFactory = locator.getFactory(RoleFactory.class); - // Convert query - RoleQuery query = roleFactory.newQuery(GwtKapuaCommonsModelConverter.convertKapuaId(gwtRoleQuery.getScopeId())); + RoleQuery query = new RoleQuery(GwtKapuaCommonsModelConverter.convertKapuaId(gwtRoleQuery.getScopeId())); AndPredicate predicate = query.andPredicate(); @@ -154,25 +139,11 @@ public static RoleQuery convertRoleQuery(PagingLoadConfig loadConfig, GwtRoleQue return query; } - public static AccessRoleQuery convertAccessRoleQuery(PagingLoadConfig pagingLoadConfig, - GwtAccessRoleQuery gwtRoleQuery) { - - KapuaLocator locator = KapuaLocator.getInstance(); - AccessRoleFactory accessRoleFactory = locator.getFactory(AccessRoleFactory.class); - - AccessRoleQuery query = accessRoleFactory.newQuery(GwtKapuaCommonsModelConverter.convertKapuaId(gwtRoleQuery.getScopeId())); - query.setPredicate(query.attributePredicate(AccessRoleAttributes.ROLE_ID, KapuaEid.parseCompactId(gwtRoleQuery.getRoleId()))); - query.setOffset(pagingLoadConfig.getOffset()); - query.setLimit(pagingLoadConfig.getLimit()); - query.setAskTotalCount(gwtRoleQuery.getAskTotalCount()); - return query; - - } - /** * Converts a {@link GwtRole} into a {@link Role} object for backend usage * - * @param gwtRole the {@link GwtRole} to convertKapuaId + * @param gwtRole + * the {@link GwtRole} to convertKapuaId * @return the converted {@link Role} */ public static Role convertRole(GwtRole gwtRole) throws KapuaException { @@ -218,18 +189,15 @@ public static Role convertRole(GwtRole gwtRole) throws KapuaException { /** * Converts a {@link GwtRoleCreator} into a {@link RoleCreator} object for backend usage * - * @param gwtRoleCreator the {@link GwtRoleCreator} to convertKapuaId + * @param gwtRoleCreator + * the {@link GwtRoleCreator} to convertKapuaId * @return the converted {@link RoleCreator} */ public static RoleCreator convertRoleCreator(GwtRoleCreator gwtRoleCreator) throws KapuaException { - // Get Services - KapuaLocator locator = KapuaLocator.getInstance(); - RoleFactory roleFactory = locator.getFactory(RoleFactory.class); - // Convert scopeId KapuaId scopeId = GwtKapuaCommonsModelConverter.convertKapuaId(gwtRoleCreator.getScopeId()); - RoleCreator roleCreator = roleFactory.newCreator(scopeId); + RoleCreator roleCreator = new RoleCreator(scopeId); // Convert name roleCreator.setName(gwtRoleCreator.getName()); @@ -251,19 +219,16 @@ public static RoleCreator convertRoleCreator(GwtRoleCreator gwtRoleCreator) thro /** * Converts a {@link GwtAccessRoleCreator} into a {@link AccessRoleCreator} object for backend usage * - * @param gwtAccessRoleCreator the {@link GwtAccessRoleCreator} to convertKapuaId + * @param gwtAccessRoleCreator + * the {@link GwtAccessRoleCreator} to convertKapuaId * @return the converted {@link AccessRoleCreator} * @since 1.0.0 */ public static AccessRoleCreator convertAccessRoleCreator(GwtAccessRoleCreator gwtAccessRoleCreator) { - // Get Services - KapuaLocator locator = KapuaLocator.getInstance(); - AccessRoleFactory accessRoleFactory = locator.getFactory(AccessRoleFactory.class); - // Convert scopeId KapuaId scopeId = GwtKapuaCommonsModelConverter.convertKapuaId(gwtAccessRoleCreator.getScopeId()); - AccessRoleCreator accessRoleCreator = accessRoleFactory.newCreator(scopeId); + AccessRoleCreator accessRoleCreator = new AccessRoleCreator(scopeId); // Convert accessInfoId accessRoleCreator.setAccessInfoId(GwtKapuaCommonsModelConverter.convertKapuaId(gwtAccessRoleCreator.getAccessInfoId())); @@ -277,19 +242,16 @@ public static AccessRoleCreator convertAccessRoleCreator(GwtAccessRoleCreator gw /** * Converts a {@link GwtAccessPermissionCreator} into a {@link AccessPermissionCreator} object for backend usage * - * @param gwtAccessPermissionCreator the {@link GwtAccessPermissionCreator} to convertKapuaId + * @param gwtAccessPermissionCreator + * the {@link GwtAccessPermissionCreator} to convertKapuaId * @return the converted {@link AccessPermissionCreator} * @since 1.0.0 */ public static AccessPermissionCreator convertAccessPermissionCreator(GwtAccessPermissionCreator gwtAccessPermissionCreator) throws KapuaException { - // Get Services - KapuaLocator locator = KapuaLocator.getInstance(); - AccessPermissionFactory accessPermissionFactory = locator.getFactory(AccessPermissionFactory.class); - // Convert scopeId KapuaId scopeId = GwtKapuaCommonsModelConverter.convertKapuaId(gwtAccessPermissionCreator.getScopeId()); - AccessPermissionCreator accessPermissionCreator = accessPermissionFactory.newCreator(scopeId); + AccessPermissionCreator accessPermissionCreator = new AccessPermissionCreator(scopeId); // Convert accessInfoId accessPermissionCreator.setAccessInfoId(GwtKapuaCommonsModelConverter.convertKapuaId(gwtAccessPermissionCreator.getAccessInfoId())); @@ -301,13 +263,9 @@ public static AccessPermissionCreator convertAccessPermissionCreator(GwtAccessPe } public static AccessInfoCreator convertAccessInfoCreator(GwtAccessInfoCreator gwtAccessInfoCreator) { - // Get Services - KapuaLocator locator = KapuaLocator.getInstance(); - AccessInfoFactory accessInfoFactory = locator.getFactory(AccessInfoFactory.class); - // Convert scopeId KapuaId scopeId = GwtKapuaCommonsModelConverter.convertKapuaId(gwtAccessInfoCreator.getScopeId()); - AccessInfoCreator accessInfoCreator = accessInfoFactory.newCreator(scopeId); + AccessInfoCreator accessInfoCreator = new AccessInfoCreator(scopeId); // Convert userId accessInfoCreator.setUserId(GwtKapuaCommonsModelConverter.convertKapuaId(gwtAccessInfoCreator.getUserId())); @@ -318,16 +276,14 @@ public static AccessInfoCreator convertAccessInfoCreator(GwtAccessInfoCreator gw /** * Converts a {@link GwtPermission} into a {@link Permission} object for backend usage. * - * @param gwtPermission The {@link GwtPermission} to convertKapuaId. + * @param gwtPermission + * The {@link GwtPermission} to convertKapuaId. * @return The converted {@link Permission}. * @since 1.0.0 */ public static Permission convertPermission(GwtPermission gwtPermission) throws KapuaException { - // Get Services - KapuaLocator locator = KapuaLocator.getInstance(); - PermissionFactory permissionFactory = locator.getFactory(PermissionFactory.class); // Return converted - return permissionFactory.newPermission(gwtPermission.getDomain(), + return new Permission(gwtPermission.getDomain(), convertAction(gwtPermission.getActionEnum()), GwtKapuaCommonsModelConverter.convertKapuaId(gwtPermission.getTargetScopeId()), GwtKapuaCommonsModelConverter.convertKapuaId(gwtPermission.getGroupId()), @@ -337,7 +293,8 @@ public static Permission convertPermission(GwtPermission gwtPermission) throws K /** * Converts a {@link GwtAction} into the related {@link Actions} * - * @param gwtAction the {@link GwtAction} to convertKapuaId + * @param gwtAction + * the {@link GwtAction} to convertKapuaId * @return the converted {@link Actions} * @since 1.0.0 */ @@ -346,24 +303,24 @@ public static Actions convertAction(GwtAction gwtAction) { Actions action = null; if (gwtAction != null) { switch (gwtAction) { - case connect: - action = Actions.connect; - break; - case delete: - action = Actions.delete; - break; - case execute: - action = Actions.execute; - break; - case read: - action = Actions.read; - break; - case write: - action = Actions.write; - break; - case ALL: - action = null; - break; + case connect: + action = Actions.connect; + break; + case delete: + action = Actions.delete; + break; + case execute: + action = Actions.execute; + break; + case read: + action = Actions.read; + break; + case write: + action = Actions.write; + break; + case ALL: + action = null; + break; } } return action; @@ -372,7 +329,8 @@ public static Actions convertAction(GwtAction gwtAction) { /** * Converts a {@link GwtDomain} into the related equivalent domain string * - * @param gwtDomain the {@link GwtDomain} to convertKapuaId + * @param gwtDomain + * the {@link GwtDomain} to convertKapuaId * @return the converted domain {@link String} * @since 1.0.0 */ @@ -384,8 +342,7 @@ public static Domain convertDomain(GwtDomain gwtDomain) throws KapuaException { return null; } - DomainQuery query = DOMAIN_FACTORY.newQuery(null); - DomainListResult list = DOMAIN_REGISTRY_SERVICE.query(query); + DomainListResult list = DOMAIN_REGISTRY_SERVICE.query(new KapuaQuery((KapuaId) null)); for (org.eclipse.kapua.service.authorization.domain.Domain domain : list.getItems()) { if (gwtDomainName.equals(domain.getName())) { diff --git a/console/module/certificate/pom.xml b/console/module/certificate/pom.xml index 3accafe8a1f..25b936f3dff 100644 --- a/console/module/certificate/pom.xml +++ b/console/module/certificate/pom.xml @@ -18,7 +18,7 @@ kapua-console-module org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-console-module-certificate diff --git a/console/module/certificate/src/main/java/org/eclipse/kapua/app/console/module/certificate/server/GwtCertificateInfoServiceImpl.java b/console/module/certificate/src/main/java/org/eclipse/kapua/app/console/module/certificate/server/GwtCertificateInfoServiceImpl.java index 5939b8a5214..06c82e26618 100644 --- a/console/module/certificate/src/main/java/org/eclipse/kapua/app/console/module/certificate/server/GwtCertificateInfoServiceImpl.java +++ b/console/module/certificate/src/main/java/org/eclipse/kapua/app/console/module/certificate/server/GwtCertificateInfoServiceImpl.java @@ -12,6 +12,9 @@ *******************************************************************************/ package org.eclipse.kapua.app.console.module.certificate.server; +import java.util.ArrayList; +import java.util.List; + import org.eclipse.kapua.app.console.module.api.client.GwtKapuaException; import org.eclipse.kapua.app.console.module.api.server.KapuaRemoteServiceServlet; import org.eclipse.kapua.app.console.module.api.server.util.KapuaExceptionHandler; @@ -22,16 +25,12 @@ import org.eclipse.kapua.locator.KapuaLocator; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.certificate.info.CertificateInfo; -import org.eclipse.kapua.service.certificate.info.CertificateInfoFactory; import org.eclipse.kapua.service.certificate.info.CertificateInfoListResult; import org.eclipse.kapua.service.certificate.info.CertificateInfoQuery; import org.eclipse.kapua.service.certificate.info.CertificateInfoService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.ArrayList; -import java.util.List; - public class GwtCertificateInfoServiceImpl extends KapuaRemoteServiceServlet implements GwtCertificateInfoService { private static final Logger LOG = LoggerFactory.getLogger(GwtCertificateInfoServiceImpl.class); @@ -39,7 +38,6 @@ public class GwtCertificateInfoServiceImpl extends KapuaRemoteServiceServlet imp private static final KapuaLocator LOCATOR = KapuaLocator.getInstance(); private static final CertificateInfoService CERTIFICATE_INFO_SERVICE = LOCATOR.getService(CertificateInfoService.class); - private static final CertificateInfoFactory CERTIFICATE_INFO_FACTORY = LOCATOR.getFactory(CertificateInfoFactory.class); @Override public List findAll(String scopeIdString) throws GwtKapuaException { @@ -48,7 +46,7 @@ public List findAll(String scopeIdString) throws GwtKapuaExc List gwtCertificateInfos = new ArrayList(); - CertificateInfoQuery query = CERTIFICATE_INFO_FACTORY.newQuery(scopeId); + CertificateInfoQuery query = new CertificateInfoQuery(scopeId); query.setIncludeInherited(true); CertificateInfoListResult certificateInfos = CERTIFICATE_INFO_SERVICE.query(query); diff --git a/console/module/data/pom.xml b/console/module/data/pom.xml index 54eb376032a..f79b8d50394 100644 --- a/console/module/data/pom.xml +++ b/console/module/data/pom.xml @@ -19,7 +19,7 @@ kapua-console-module org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-console-module-data diff --git a/console/module/data/src/main/java/org/eclipse/kapua/app/console/module/data/server/GwtDataServiceImpl.java b/console/module/data/src/main/java/org/eclipse/kapua/app/console/module/data/server/GwtDataServiceImpl.java index 23b430d4a45..0e21e2f178e 100644 --- a/console/module/data/src/main/java/org/eclipse/kapua/app/console/module/data/server/GwtDataServiceImpl.java +++ b/console/module/data/src/main/java/org/eclipse/kapua/app/console/module/data/server/GwtDataServiceImpl.java @@ -12,15 +12,14 @@ *******************************************************************************/ package org.eclipse.kapua.app.console.module.data.server; -import com.extjs.gxt.ui.client.Style; -import com.extjs.gxt.ui.client.data.BaseListLoadResult; -import com.extjs.gxt.ui.client.data.BasePagingLoadResult; -import com.extjs.gxt.ui.client.data.ListLoadResult; -import com.extjs.gxt.ui.client.data.LoadConfig; -import com.extjs.gxt.ui.client.data.ModelData; -import com.extjs.gxt.ui.client.data.PagingLoadConfig; -import com.extjs.gxt.ui.client.data.PagingLoadResult; -import com.google.common.base.Strings; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + import org.apache.commons.lang3.StringUtils; import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.app.console.module.api.client.GwtKapuaErrorCode; @@ -40,21 +39,11 @@ import org.eclipse.kapua.locator.KapuaLocator; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.model.type.ObjectTypeConverter; -import org.eclipse.kapua.service.datastore.ChannelInfoFactory; import org.eclipse.kapua.service.datastore.ChannelInfoRegistryService; -import org.eclipse.kapua.service.datastore.ClientInfoFactory; import org.eclipse.kapua.service.datastore.ClientInfoRegistryService; -import org.eclipse.kapua.service.datastore.MessageStoreFactory; import org.eclipse.kapua.service.datastore.MessageStoreService; -import org.eclipse.kapua.service.datastore.MetricInfoFactory; import org.eclipse.kapua.service.datastore.MetricInfoRegistryService; -import org.eclipse.kapua.service.datastore.internal.mediator.ClientInfoField; -import org.eclipse.kapua.service.datastore.internal.mediator.MessageField; -import org.eclipse.kapua.service.datastore.internal.mediator.MetricInfoField; -import org.eclipse.kapua.service.datastore.internal.model.query.ClientInfoQueryImpl; -import org.eclipse.kapua.service.datastore.internal.model.query.MessageQueryImpl; import org.eclipse.kapua.service.datastore.internal.model.query.predicate.ChannelMatchPredicateImpl; -import org.eclipse.kapua.service.datastore.internal.schema.MessageSchema; import org.eclipse.kapua.service.datastore.model.ChannelInfo; import org.eclipse.kapua.service.datastore.model.ChannelInfoListResult; import org.eclipse.kapua.service.datastore.model.ClientInfo; @@ -64,8 +53,12 @@ import org.eclipse.kapua.service.datastore.model.MetricInfo; import org.eclipse.kapua.service.datastore.model.MetricInfoListResult; import org.eclipse.kapua.service.datastore.model.query.ChannelInfoQuery; +import org.eclipse.kapua.service.datastore.model.query.ClientInfoField; import org.eclipse.kapua.service.datastore.model.query.ClientInfoQuery; +import org.eclipse.kapua.service.datastore.model.query.MessageField; import org.eclipse.kapua.service.datastore.model.query.MessageQuery; +import org.eclipse.kapua.service.datastore.model.query.MessageSchema; +import org.eclipse.kapua.service.datastore.model.query.MetricInfoField; import org.eclipse.kapua.service.datastore.model.query.MetricInfoQuery; import org.eclipse.kapua.service.datastore.model.query.predicate.ChannelMatchPredicate; import org.eclipse.kapua.service.datastore.model.query.predicate.DatastorePredicateFactory; @@ -83,13 +76,15 @@ import org.eclipse.kapua.service.storable.model.query.predicate.StorablePredicate; import org.eclipse.kapua.service.storable.model.query.predicate.TermPredicate; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import com.extjs.gxt.ui.client.Style; +import com.extjs.gxt.ui.client.data.BaseListLoadResult; +import com.extjs.gxt.ui.client.data.BasePagingLoadResult; +import com.extjs.gxt.ui.client.data.ListLoadResult; +import com.extjs.gxt.ui.client.data.LoadConfig; +import com.extjs.gxt.ui.client.data.ModelData; +import com.extjs.gxt.ui.client.data.PagingLoadConfig; +import com.extjs.gxt.ui.client.data.PagingLoadResult; +import com.google.common.base.Strings; public class GwtDataServiceImpl extends KapuaRemoteServiceServlet implements GwtDataService { @@ -97,11 +92,6 @@ public class GwtDataServiceImpl extends KapuaRemoteServiceServlet implements Gwt private static final KapuaLocator LOCATOR = KapuaLocator.getInstance(); - private static final ChannelInfoFactory CHANNEL_INFO_FACTORY = LOCATOR.getFactory(ChannelInfoFactory.class); - private static final ClientInfoFactory CLIENT_INFO_FACTORY = LOCATOR.getFactory(ClientInfoFactory.class); - private static final MessageStoreFactory MESSAGE_STORE_FACTORY = LOCATOR.getFactory(MessageStoreFactory.class); - private static final MetricInfoFactory METRIC_INFO_FACTORY = LOCATOR.getFactory(MetricInfoFactory.class); - private static final DatastorePredicateFactory DATASTORE_PREDICATE_FACTORY = LOCATOR.getFactory(DatastorePredicateFactory.class); @Override @@ -109,7 +99,7 @@ public List findTopicsTree(String scopeId) throws GwtKapuaException { List channelInfoList = new ArrayList(); HashMap topicMap = new HashMap(); ChannelInfoRegistryService channelInfoService = LOCATOR.getService(ChannelInfoRegistryService.class); - ChannelInfoQuery query = CHANNEL_INFO_FACTORY.newQuery(GwtKapuaCommonsModelConverter.convertKapuaId(scopeId)); + ChannelInfoQuery query = new ChannelInfoQuery(GwtKapuaCommonsModelConverter.convertKapuaId(scopeId)); int offset = 0; int limit = 250; try { @@ -155,7 +145,7 @@ public List updateTopicTimestamps(String gwtScopeId, List t List sort = new ArrayList(); sort.add(SortField.descending(MessageSchema.MESSAGE_TIMESTAMP)); - MessageQuery messageQuery = new MessageQueryImpl(scopeId); + MessageQuery messageQuery = new MessageQuery(scopeId); messageQuery.setAskTotalCount(true); messageQuery.setFetchStyle(StorableFetchStyle.FIELDS); messageQuery.setLimit(1); @@ -195,7 +185,7 @@ public List updateDeviceTimestamps(String gwtScopeId, List findDevices(PagingLoadConfig config, List devices = new ArrayList(); KapuaId convertedScopeId = GwtKapuaCommonsModelConverter.convertKapuaId(scopeId); //TODO: #LAYER_VIOLATION - entity lookup would be much more efficient at a lower layer - ClientInfoQuery clientInfoQuery = CLIENT_INFO_FACTORY.newQuery(convertedScopeId); + ClientInfoQuery clientInfoQuery = new ClientInfoQuery(convertedScopeId); if (!Strings.isNullOrEmpty(filter)) { StorablePredicate predicate = new ChannelMatchPredicateImpl(ClientInfoField.CLIENT_ID, filter); clientInfoQuery.setPredicate(predicate); @@ -307,7 +297,7 @@ public PagingLoadResult findDevices(PagingLoadConfig config, for (ClientInfo client : result.getItems()) { clientIds.add(client.getClientId()); } - DeviceQuery deviceQuery = deviceFactory.newQuery(convertedScopeId); + DeviceQuery deviceQuery = new DeviceQuery(convertedScopeId); DeviceListResult deviceListResult = deviceRegistryService.query(deviceQuery); Map clientIdsMap = buildClientIdsMap(clientIds, deviceListResult); @@ -350,7 +340,7 @@ public ListLoadResult findAssets(LoadConfig config, String sc ChannelInfoRegistryService clientInfoService = LOCATOR.getService(ChannelInfoRegistryService.class); List asset = new ArrayList(); KapuaId convertedScopeId = GwtKapuaCommonsModelConverter.convertKapuaId(scopeId); - ChannelInfoQuery query = CHANNEL_INFO_FACTORY.newQuery(convertedScopeId); + ChannelInfoQuery query = new ChannelInfoQuery(convertedScopeId); //TODO: #LAYER_VIOLATION - searching should be done at a lower layer, here it is horribly inefficient (and potentially wrong) query.setLimit(10000); try { @@ -423,7 +413,8 @@ public PagingLoadResult findMessagesByDevice(PagingLoadConfig loadCo } @Override - public PagingLoadResult findMessagesByAssets(PagingLoadConfig loadConfig, String scopeId, GwtDatastoreDevice device, GwtDatastoreAsset asset, List headers, Date startDate, Date endDate) + public PagingLoadResult findMessagesByAssets(PagingLoadConfig loadConfig, String scopeId, GwtDatastoreDevice device, GwtDatastoreAsset asset, List headers, Date startDate, + Date endDate) throws GwtKapuaException { ChannelMatchPredicate assetPredicate = DATASTORE_PREDICATE_FACTORY.newChannelMatchPredicate(asset.getTopick()); TermPredicate devicePredicate = DATASTORE_PREDICATE_FACTORY.newTermPredicate(MessageField.CLIENT_ID, device.getDevice()); @@ -435,7 +426,7 @@ public PagingLoadResult findMessagesByAssets(PagingLoadConfig loadCo private ListLoadResult findHeaders(String scopeId, StorablePredicate predicate) throws GwtKapuaException { MetricInfoRegistryService metricService = LOCATOR.getService(MetricInfoRegistryService.class); - MetricInfoQuery query = METRIC_INFO_FACTORY.newQuery(GwtKapuaCommonsModelConverter.convertKapuaId(scopeId)); + MetricInfoQuery query = new MetricInfoQuery(GwtKapuaCommonsModelConverter.convertKapuaId(scopeId)); query.setLimit(10000); if (predicate != null) { query.setPredicate(predicate); @@ -461,7 +452,7 @@ private PagingLoadResult findMessages(PagingLoadConfig loadConfig, S MessageStoreService messageService = LOCATOR.getService(MessageStoreService.class); List messages; int totalLength = 0; - MessageQuery query = MESSAGE_STORE_FACTORY.newQuery(GwtKapuaCommonsModelConverter.convertKapuaId(scopeId)); + MessageQuery query = new MessageQuery(GwtKapuaCommonsModelConverter.convertKapuaId(scopeId)); query.setLimit(loadConfig.getLimit()); query.setOffset(loadConfig.getOffset()); AndPredicate andPredicate = DATASTORE_PREDICATE_FACTORY.newAndPredicate(); @@ -474,7 +465,8 @@ private PagingLoadResult findMessages(PagingLoadConfig loadConfig, S OrPredicate metricsPredicate = DATASTORE_PREDICATE_FACTORY.newOrPredicate(); for (GwtHeader header : headers) { try { - metricsPredicate.getPredicates().add(DATASTORE_PREDICATE_FACTORY.newMetricExistsPredicate(header.getName(), (Class) ObjectTypeConverter.fromString(header.getType().toLowerCase()))); + metricsPredicate.getPredicates() + .add(DATASTORE_PREDICATE_FACTORY.newMetricExistsPredicate(header.getName(), (Class) ObjectTypeConverter.fromString(header.getType().toLowerCase()))); } catch (ClassNotFoundException e) { throw new GwtKapuaException(GwtKapuaErrorCode.INTERNAL_ERROR, e); } diff --git a/console/module/data/src/main/java/org/eclipse/kapua/app/console/module/data/servlet/DataExporterServlet.java b/console/module/data/src/main/java/org/eclipse/kapua/app/console/module/data/servlet/DataExporterServlet.java index b6104829367..8a1204d5a0a 100644 --- a/console/module/data/src/main/java/org/eclipse/kapua/app/console/module/data/servlet/DataExporterServlet.java +++ b/console/module/data/src/main/java/org/eclipse/kapua/app/console/module/data/servlet/DataExporterServlet.java @@ -12,6 +12,16 @@ *******************************************************************************/ package org.eclipse.kapua.app.console.module.data.servlet; +import java.io.IOException; +import java.text.MessageFormat; +import java.util.Collections; +import java.util.Date; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + import org.eclipse.kapua.KapuaEntityNotFoundException; import org.eclipse.kapua.KapuaIllegalAccessException; import org.eclipse.kapua.KapuaUnauthenticatedException; @@ -20,11 +30,10 @@ import org.eclipse.kapua.app.console.module.api.shared.util.GwtKapuaCommonsModelConverter; import org.eclipse.kapua.app.console.module.data.shared.util.KapuaGwtDataModelConverter; import org.eclipse.kapua.locator.KapuaLocator; -import org.eclipse.kapua.service.datastore.MessageStoreFactory; import org.eclipse.kapua.service.datastore.MessageStoreService; -import org.eclipse.kapua.service.datastore.internal.mediator.MessageField; import org.eclipse.kapua.service.datastore.model.DatastoreMessage; import org.eclipse.kapua.service.datastore.model.MessageListResult; +import org.eclipse.kapua.service.datastore.model.query.MessageField; import org.eclipse.kapua.service.datastore.model.query.MessageQuery; import org.eclipse.kapua.service.datastore.model.query.predicate.DatastorePredicateFactory; import org.eclipse.kapua.service.storable.model.query.SortDirection; @@ -34,15 +43,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.text.MessageFormat; -import java.util.Collections; -import java.util.Date; - public class DataExporterServlet extends HttpServlet { private static final long serialVersionUID = 226461063207179649L; @@ -51,8 +51,6 @@ public class DataExporterServlet extends HttpServlet { private static final KapuaLocator LOCATOR = KapuaLocator.getInstance(); - private static final MessageStoreFactory MESSAGE_STORE_FACTORY = LOCATOR.getFactory(MessageStoreFactory.class); - private static final DatastorePredicateFactory DATASTORE_PREDICATE_FACTORY = LOCATOR.getFactory(DatastorePredicateFactory.class); private static final MessageStoreService MESSAGE_STORE_SERVICE = LOCATOR.getService(MessageStoreService.class); @@ -121,7 +119,7 @@ private void internalDoGet(HttpServletRequest request, HttpServletResponse respo throw new IllegalArgumentException("format"); } dataExporter.init(headers); - MessageQuery query = MESSAGE_STORE_FACTORY.newQuery(GwtKapuaCommonsModelConverter.convertKapuaId(scopeIdString)); + MessageQuery query = new MessageQuery(GwtKapuaCommonsModelConverter.convertKapuaId(scopeIdString)); Date start = new Date(Long.valueOf(startDate)); Date end = new Date(Long.valueOf(endDate)); RangePredicate datePredicate = DATASTORE_PREDICATE_FACTORY.newRangePredicate(MessageField.TIMESTAMP, start, end); diff --git a/console/module/data/src/main/java/org/eclipse/kapua/app/console/module/data/shared/util/GwtKapuaDataModelConverter.java b/console/module/data/src/main/java/org/eclipse/kapua/app/console/module/data/shared/util/GwtKapuaDataModelConverter.java index b894b5d60e8..070e63a47d6 100644 --- a/console/module/data/src/main/java/org/eclipse/kapua/app/console/module/data/shared/util/GwtKapuaDataModelConverter.java +++ b/console/module/data/src/main/java/org/eclipse/kapua/app/console/module/data/shared/util/GwtKapuaDataModelConverter.java @@ -12,24 +12,19 @@ *******************************************************************************/ package org.eclipse.kapua.app.console.module.data.shared.util; -import com.extjs.gxt.ui.client.data.PagingLoadConfig; import org.eclipse.kapua.app.console.module.api.shared.util.GwtKapuaCommonsModelConverter; import org.eclipse.kapua.app.console.module.data.shared.model.GwtDataChannelInfoQuery; -import org.eclipse.kapua.locator.KapuaLocator; -import org.eclipse.kapua.service.datastore.ChannelInfoFactory; import org.eclipse.kapua.service.datastore.model.query.ChannelInfoQuery; -public class GwtKapuaDataModelConverter { - - private static final KapuaLocator LOCATOR = KapuaLocator.getInstance(); +import com.extjs.gxt.ui.client.data.PagingLoadConfig; - private static final ChannelInfoFactory CHANNEL_INFO_FACTORY = LOCATOR.getFactory(ChannelInfoFactory.class); +public class GwtKapuaDataModelConverter { private GwtKapuaDataModelConverter() { } public static ChannelInfoQuery convertChannelInfoQuery(GwtDataChannelInfoQuery query, PagingLoadConfig pagingLoadConfig) { - ChannelInfoQuery channelInfoQuery = CHANNEL_INFO_FACTORY.newQuery(GwtKapuaCommonsModelConverter.convertKapuaId(query.getScopeId())); + ChannelInfoQuery channelInfoQuery = new ChannelInfoQuery(GwtKapuaCommonsModelConverter.convertKapuaId(query.getScopeId())); channelInfoQuery.setOffset(pagingLoadConfig.getOffset()); channelInfoQuery.setLimit(pagingLoadConfig.getLimit()); return channelInfoQuery; diff --git a/console/module/device/pom.xml b/console/module/device/pom.xml index 599cee6930a..d48dabf5692 100644 --- a/console/module/device/pom.xml +++ b/console/module/device/pom.xml @@ -19,7 +19,7 @@ kapua-console-module org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-console-module-device diff --git a/console/module/device/src/main/java/org/eclipse/kapua/app/console/module/device/server/GwtDeviceConnectionServiceImpl.java b/console/module/device/src/main/java/org/eclipse/kapua/app/console/module/device/server/GwtDeviceConnectionServiceImpl.java index cd228fb84cf..f152b59d842 100644 --- a/console/module/device/src/main/java/org/eclipse/kapua/app/console/module/device/server/GwtDeviceConnectionServiceImpl.java +++ b/console/module/device/src/main/java/org/eclipse/kapua/app/console/module/device/server/GwtDeviceConnectionServiceImpl.java @@ -12,11 +12,12 @@ *******************************************************************************/ package org.eclipse.kapua.app.console.module.device.server; -import com.extjs.gxt.ui.client.data.BaseListLoadResult; -import com.extjs.gxt.ui.client.data.BasePagingLoadResult; -import com.extjs.gxt.ui.client.data.ListLoadResult; -import com.extjs.gxt.ui.client.data.PagingLoadConfig; -import com.extjs.gxt.ui.client.data.PagingLoadResult; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.Callable; + import org.eclipse.kapua.app.console.module.api.client.GwtKapuaException; import org.eclipse.kapua.app.console.module.api.server.KapuaRemoteServiceServlet; import org.eclipse.kapua.app.console.module.api.server.util.KapuaExceptionHandler; @@ -36,26 +37,26 @@ import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.model.query.KapuaListResult; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; +import org.eclipse.kapua.service.authorization.permission.Permission; import org.eclipse.kapua.service.device.registry.connection.DeviceConnection; import org.eclipse.kapua.service.device.registry.connection.DeviceConnectionQuery; import org.eclipse.kapua.service.device.registry.connection.DeviceConnectionService; import org.eclipse.kapua.service.user.User; -import org.eclipse.kapua.service.user.UserFactory; import org.eclipse.kapua.service.user.UserListResult; import org.eclipse.kapua.service.user.UserQuery; import org.eclipse.kapua.service.user.UserService; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.Callable; +import com.extjs.gxt.ui.client.data.BaseListLoadResult; +import com.extjs.gxt.ui.client.data.BasePagingLoadResult; +import com.extjs.gxt.ui.client.data.ListLoadResult; +import com.extjs.gxt.ui.client.data.PagingLoadConfig; +import com.extjs.gxt.ui.client.data.PagingLoadResult; /** * The server side implementation of the RPC service. */ public class GwtDeviceConnectionServiceImpl extends KapuaRemoteServiceServlet implements GwtDeviceConnectionService { + private static final long serialVersionUID = 3314502846487119577L; private static final KapuaLocator LOCATOR = KapuaLocator.getInstance(); @@ -63,9 +64,7 @@ public class GwtDeviceConnectionServiceImpl extends KapuaRemoteServiceServlet im private static final DeviceConnectionService DEVICE_CONNECTION_SERVICE = LOCATOR.getService(DeviceConnectionService.class); private static final AuthorizationService AUTHORIZATION_SERVICE = LOCATOR.getService(AuthorizationService.class); - private static final PermissionFactory PERMISSION_FACTORY = LOCATOR.getFactory(PermissionFactory.class); private static final UserService USER_SERVICE = LOCATOR.getService(UserService.class); - private static final UserFactory USER_FACTORY = LOCATOR.getFactory(UserFactory.class); private static final String CONNECTION_INFO = "connectionInfo"; private static final String CONNECTION_USER_COUPLING_MODE_INFO = "connectionUserCouplingModeInfo"; @@ -83,9 +82,9 @@ public PagingLoadResult query(PagingLoadConfig loadConfig, if (!deviceConnections.isEmpty()) { Map users = new HashMap(); - final UserQuery userQuery = USER_FACTORY.newQuery(GwtKapuaCommonsModelConverter.convertKapuaId(gwtDeviceConnectionQuery.getScopeId())); + final UserQuery userQuery = new UserQuery(GwtKapuaCommonsModelConverter.convertKapuaId(gwtDeviceConnectionQuery.getScopeId())); -//TODO: #LAYER_VIOLATION - user lookup logic should not be done here (fetching all users is incredibly inefficient anyway) + //TODO: #LAYER_VIOLATION - user lookup logic should not be done here (fetching all users is incredibly inefficient anyway) UserListResult userList = KapuaSecurityUtils.doPrivileged(new Callable() { @Override @@ -141,7 +140,7 @@ public ListLoadResult getConnectionInfo(String scopeIdString, List deviceConnectionPropertiesPairs = new ArrayList(); try { final DeviceConnection deviceConnection = DEVICE_CONNECTION_SERVICE.find(scopeId, deviceConnectionId); -//TODO: #LAYER_VIOLATION - user lookup logic should not be done here + //TODO: #LAYER_VIOLATION - user lookup logic should not be done here User connectionUser = KapuaSecurityUtils.doPrivileged(new Callable() { @Override @@ -190,8 +189,9 @@ public User call() throws Exception { gwtConnectionUserCouplingMode = GwtConnectionUserCouplingMode.valueOf(deviceConnection.getUserCouplingMode().name()); } deviceConnectionPropertiesPairs - .add(new GwtGroupedNVPair(CONNECTION_USER_COUPLING_MODE_INFO, "connectionUserCouplingMode", gwtConnectionUserCouplingMode != null ? gwtConnectionUserCouplingMode.getLabel() : null)); - if (AUTHORIZATION_SERVICE.isPermitted(PERMISSION_FACTORY.newPermission(Domains.USER, Actions.read, scopeId))) { + .add(new GwtGroupedNVPair(CONNECTION_USER_COUPLING_MODE_INFO, "connectionUserCouplingMode", + gwtConnectionUserCouplingMode != null ? gwtConnectionUserCouplingMode.getLabel() : null)); + if (AUTHORIZATION_SERVICE.isPermitted(new Permission(Domains.USER, Actions.read, scopeId))) { deviceConnectionPropertiesPairs.add(new GwtGroupedNVPair(CONNECTION_USER_COUPLING_MODE_INFO, "connectionReservedUser", reservedUser != null ? reservedUser.getName() : null)); deviceConnectionPropertiesPairs.add(new GwtGroupedNVPair(CONNECTION_USER_COUPLING_MODE_INFO, "allowUserChange", deviceConnection.getAllowUserChange())); } diff --git a/console/module/device/src/main/java/org/eclipse/kapua/app/console/module/device/server/GwtDeviceInventoryManagementServiceImpl.java b/console/module/device/src/main/java/org/eclipse/kapua/app/console/module/device/server/GwtDeviceInventoryManagementServiceImpl.java index 2593bdec1a9..0a26f47b9bd 100644 --- a/console/module/device/src/main/java/org/eclipse/kapua/app/console/module/device/server/GwtDeviceInventoryManagementServiceImpl.java +++ b/console/module/device/src/main/java/org/eclipse/kapua/app/console/module/device/server/GwtDeviceInventoryManagementServiceImpl.java @@ -12,12 +12,12 @@ *******************************************************************************/ package org.eclipse.kapua.app.console.module.device.server; -import com.extjs.gxt.ui.client.data.BaseListLoadResult; -import com.extjs.gxt.ui.client.data.ListLoadResult; +import java.util.ArrayList; +import java.util.List; + import org.eclipse.kapua.app.console.module.api.client.GwtKapuaException; import org.eclipse.kapua.app.console.module.api.server.KapuaRemoteServiceServlet; import org.eclipse.kapua.app.console.module.api.server.util.KapuaExceptionHandler; -import org.eclipse.kapua.app.console.module.api.setting.ConsoleSetting; import org.eclipse.kapua.app.console.module.api.shared.model.GwtXSRFToken; import org.eclipse.kapua.app.console.module.device.shared.model.management.inventory.GwtInventoryBundle; import org.eclipse.kapua.app.console.module.device.shared.model.management.inventory.GwtInventoryContainer; @@ -28,7 +28,6 @@ import org.eclipse.kapua.commons.model.id.KapuaEid; import org.eclipse.kapua.locator.KapuaLocator; import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.device.management.inventory.DeviceInventoryManagementFactory; import org.eclipse.kapua.service.device.management.inventory.DeviceInventoryManagementService; import org.eclipse.kapua.service.device.management.inventory.model.bundle.DeviceInventoryBundle; import org.eclipse.kapua.service.device.management.inventory.model.bundle.DeviceInventoryBundleAction; @@ -44,8 +43,8 @@ import org.eclipse.kapua.service.device.management.inventory.model.system.DeviceInventorySystemPackage; import org.eclipse.kapua.service.device.management.inventory.model.system.DeviceInventorySystemPackages; -import java.util.ArrayList; -import java.util.List; +import com.extjs.gxt.ui.client.data.BaseListLoadResult; +import com.extjs.gxt.ui.client.data.ListLoadResult; /** * The server side implementation of the Device RPC service. @@ -54,12 +53,9 @@ public class GwtDeviceInventoryManagementServiceImpl extends KapuaRemoteServiceS private static final long serialVersionUID = -1391026997499175151L; - private static final ConsoleSetting CONSOLE_SETTING = ConsoleSetting.getInstance(); - private static final KapuaLocator LOCATOR = KapuaLocator.getInstance(); private static final DeviceInventoryManagementService DEVICE_INVENTORY_MANAGEMENT_SERVICE = LOCATOR.getService(DeviceInventoryManagementService.class); - private static final DeviceInventoryManagementFactory DEVICE_INVENTORY_MANAGEMENT_FACTORY = LOCATOR.getFactory(DeviceInventoryManagementFactory.class); @Override public ListLoadResult findDeviceInventory(String scopeIdString, String deviceIdString) @@ -121,7 +117,7 @@ public void execDeviceBundle(GwtXSRFToken xsrfToken, String scopeIdString, Strin KapuaId scopeId = KapuaEid.parseCompactId(scopeIdString); KapuaId deviceId = KapuaEid.parseCompactId(deviceIdString); - DeviceInventoryBundle deviceInventoryBundle = DEVICE_INVENTORY_MANAGEMENT_FACTORY.newDeviceInventoryBundle(); + DeviceInventoryBundle deviceInventoryBundle = new DeviceInventoryBundle(); deviceInventoryBundle.setId(gwtInventoryBundle.getId()); deviceInventoryBundle.setName(gwtInventoryBundle.getName()); deviceInventoryBundle.setVersion(gwtInventoryBundle.getVersion()); @@ -174,7 +170,7 @@ public void execDeviceContainer(GwtXSRFToken xsrfToken, String scopeIdString, St KapuaId scopeId = KapuaEid.parseCompactId(scopeIdString); KapuaId deviceId = KapuaEid.parseCompactId(deviceIdString); - DeviceInventoryContainer deviceInventoryContainer = DEVICE_INVENTORY_MANAGEMENT_FACTORY.newDeviceInventoryContainer(); + DeviceInventoryContainer deviceInventoryContainer = new DeviceInventoryContainer(); deviceInventoryContainer.setName(gwtInventoryContainer.getName()); deviceInventoryContainer.setVersion(gwtInventoryContainer.getVersion()); deviceInventoryContainer.setContainerType(gwtInventoryContainer.getType()); diff --git a/console/module/device/src/main/java/org/eclipse/kapua/app/console/module/device/server/GwtDeviceKeystoreManagementServiceImpl.java b/console/module/device/src/main/java/org/eclipse/kapua/app/console/module/device/server/GwtDeviceKeystoreManagementServiceImpl.java index 8f306369e25..e34d710386d 100644 --- a/console/module/device/src/main/java/org/eclipse/kapua/app/console/module/device/server/GwtDeviceKeystoreManagementServiceImpl.java +++ b/console/module/device/src/main/java/org/eclipse/kapua/app/console/module/device/server/GwtDeviceKeystoreManagementServiceImpl.java @@ -12,10 +12,12 @@ *******************************************************************************/ package org.eclipse.kapua.app.console.module.device.server; +import java.util.ArrayList; +import java.util.List; + import org.eclipse.kapua.app.console.module.api.client.GwtKapuaException; import org.eclipse.kapua.app.console.module.api.server.KapuaRemoteServiceServlet; import org.eclipse.kapua.app.console.module.api.server.util.KapuaExceptionHandler; -import org.eclipse.kapua.app.console.module.api.setting.ConsoleSetting; import org.eclipse.kapua.app.console.module.api.shared.model.GwtXSRFToken; import org.eclipse.kapua.app.console.module.device.shared.model.management.keystore.GwtDeviceKeystore; import org.eclipse.kapua.app.console.module.device.shared.model.management.keystore.GwtDeviceKeystoreCertificate; @@ -26,7 +28,6 @@ import org.eclipse.kapua.commons.model.id.KapuaEid; import org.eclipse.kapua.locator.KapuaLocator; import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.device.management.keystore.DeviceKeystoreManagementFactory; import org.eclipse.kapua.service.device.management.keystore.DeviceKeystoreManagementService; import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystore; import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystoreCSR; @@ -38,9 +39,6 @@ import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystoreKeypair; import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystores; -import java.util.ArrayList; -import java.util.List; - /** * The server side implementation of the Device RPC service. */ @@ -48,12 +46,9 @@ public class GwtDeviceKeystoreManagementServiceImpl extends KapuaRemoteServiceSe private static final long serialVersionUID = -1391026997499175151L; - private static final ConsoleSetting CONSOLE_SETTING = ConsoleSetting.getInstance(); - private static final KapuaLocator LOCATOR = KapuaLocator.getInstance(); private static final DeviceKeystoreManagementService DEVICE_KEYSTORE_MANAGEMENT_SERVICE = LOCATOR.getService(DeviceKeystoreManagementService.class); - private static final DeviceKeystoreManagementFactory DEVICE_KEYSTORE_MANAGEMENT_FACTORY = LOCATOR.getFactory(DeviceKeystoreManagementFactory.class); @Override public List getKeystores(String scopeIdString, String deviceIdString) throws GwtKapuaException { @@ -99,14 +94,13 @@ public List getKeystoreItems(String scopeIdString, String } } - @Override public List getKeystoreItems(String scopeIdString, String deviceIdString, String keystoreId) throws GwtKapuaException { try { KapuaId scopeId = KapuaEid.parseCompactId(scopeIdString); KapuaId deviceId = KapuaEid.parseCompactId(deviceIdString); - DeviceKeystoreItemQuery itemQuery = DEVICE_KEYSTORE_MANAGEMENT_FACTORY.newDeviceKeystoreItemQuery(); + DeviceKeystoreItemQuery itemQuery = new DeviceKeystoreItemQuery(); itemQuery.setKeystoreId(keystoreId); DeviceKeystoreItems deviceKeystores = DEVICE_KEYSTORE_MANAGEMENT_SERVICE.getKeystoreItems(scopeId, deviceId, itemQuery, null); @@ -144,7 +138,7 @@ public void createKeystoreCertificateRaw(GwtXSRFToken xsrfToken, String scopeIdS KapuaId scopeId = KapuaEid.parseCompactId(scopeIdString); KapuaId deviceId = KapuaEid.parseCompactId(deviceIdString); - DeviceKeystoreCertificate deviceKeystoreCertificate = DEVICE_KEYSTORE_MANAGEMENT_FACTORY.newDeviceKeystoreCertificate(); + DeviceKeystoreCertificate deviceKeystoreCertificate = new DeviceKeystoreCertificate(); deviceKeystoreCertificate.setKeystoreId(gwtKeystoreCertificate.getKeystoreId()); deviceKeystoreCertificate.setAlias(gwtKeystoreCertificate.getAlias()); deviceKeystoreCertificate.setCertificate(gwtKeystoreCertificate.getCertificate()); @@ -156,7 +150,8 @@ public void createKeystoreCertificateRaw(GwtXSRFToken xsrfToken, String scopeIdS } @Override - public void createKeystoreCertificateInfo(GwtXSRFToken xsrfToken, String scopeIdString, String deviceIdString, String keystoreId, String alias, String certificateInfoIdString) throws GwtKapuaException { + public void createKeystoreCertificateInfo(GwtXSRFToken xsrfToken, String scopeIdString, String deviceIdString, String keystoreId, String alias, String certificateInfoIdString) + throws GwtKapuaException { try { checkXSRFToken(xsrfToken); @@ -178,7 +173,7 @@ public void createKeystoreKeypair(GwtXSRFToken xsrfToken, String scopeIdString, KapuaId scopeId = KapuaEid.parseCompactId(scopeIdString); KapuaId deviceId = KapuaEid.parseCompactId(deviceIdString); - DeviceKeystoreKeypair deviceKeystoreKeypair = DEVICE_KEYSTORE_MANAGEMENT_FACTORY.newDeviceKeystoreKeypair(); + DeviceKeystoreKeypair deviceKeystoreKeypair = new DeviceKeystoreKeypair(); deviceKeystoreKeypair.setKeystoreId(gwtKeystoreKeypair.getKeystoreId()); deviceKeystoreKeypair.setAlias(gwtKeystoreKeypair.getAlias()); deviceKeystoreKeypair.setAlgorithm(gwtKeystoreKeypair.getAlgorithm()); @@ -200,7 +195,7 @@ public GwtDeviceKeystoreCertificate createKeystoreCsr(GwtXSRFToken xsrfToken, St KapuaId scopeId = KapuaEid.parseCompactId(scopeIdString); KapuaId deviceId = KapuaEid.parseCompactId(deviceIdString); - DeviceKeystoreCSRInfo deviceKeystoreCsrInfo = DEVICE_KEYSTORE_MANAGEMENT_FACTORY.newDeviceKeystoreCSRInfo(); + DeviceKeystoreCSRInfo deviceKeystoreCsrInfo = new DeviceKeystoreCSRInfo(); deviceKeystoreCsrInfo.setKeystoreId(gwtKeystoreCsr.getKeystoreId()); deviceKeystoreCsrInfo.setAlias(gwtKeystoreCsr.getAlias()); deviceKeystoreCsrInfo.setSignatureAlgorithm(gwtKeystoreCsr.getSignatureAlgorithm()); @@ -219,7 +214,6 @@ public GwtDeviceKeystoreCertificate createKeystoreCsr(GwtXSRFToken xsrfToken, St } } - @Override public void deleteKeystoreItem(GwtXSRFToken xsrfToken, String scopeIdString, String deviceIdString, String keystoreId, String alias) throws GwtKapuaException { try { diff --git a/console/module/device/src/main/java/org/eclipse/kapua/app/console/module/device/server/GwtDeviceManagementOperationServiceImpl.java b/console/module/device/src/main/java/org/eclipse/kapua/app/console/module/device/server/GwtDeviceManagementOperationServiceImpl.java index 19615830b73..f7734ce4fdb 100644 --- a/console/module/device/src/main/java/org/eclipse/kapua/app/console/module/device/server/GwtDeviceManagementOperationServiceImpl.java +++ b/console/module/device/src/main/java/org/eclipse/kapua/app/console/module/device/server/GwtDeviceManagementOperationServiceImpl.java @@ -12,10 +12,9 @@ *******************************************************************************/ package org.eclipse.kapua.app.console.module.device.server; -import com.extjs.gxt.ui.client.data.BasePagingLoadResult; -import com.extjs.gxt.ui.client.data.PagingLoadConfig; -import com.extjs.gxt.ui.client.data.PagingLoadResult; -import com.google.common.base.Strings; +import java.util.ArrayList; +import java.util.List; + import org.eclipse.kapua.app.console.module.api.client.GwtKapuaException; import org.eclipse.kapua.app.console.module.api.server.KapuaRemoteServiceServlet; import org.eclipse.kapua.app.console.module.api.server.util.KapuaExceptionHandler; @@ -32,13 +31,14 @@ import org.eclipse.kapua.service.device.management.registry.operation.DeviceManagementOperationRegistryService; import org.eclipse.kapua.service.device.management.registry.operation.notification.ManagementOperationNotification; import org.eclipse.kapua.service.device.management.registry.operation.notification.ManagementOperationNotificationAttributes; -import org.eclipse.kapua.service.device.management.registry.operation.notification.ManagementOperationNotificationFactory; import org.eclipse.kapua.service.device.management.registry.operation.notification.ManagementOperationNotificationListResult; import org.eclipse.kapua.service.device.management.registry.operation.notification.ManagementOperationNotificationQuery; import org.eclipse.kapua.service.device.management.registry.operation.notification.ManagementOperationNotificationService; -import java.util.ArrayList; -import java.util.List; +import com.extjs.gxt.ui.client.data.BasePagingLoadResult; +import com.extjs.gxt.ui.client.data.PagingLoadConfig; +import com.extjs.gxt.ui.client.data.PagingLoadResult; +import com.google.common.base.Strings; /** * The server side implementation of the RPC service. @@ -50,7 +50,6 @@ public class GwtDeviceManagementOperationServiceImpl extends KapuaRemoteServiceS private static final DeviceManagementOperationRegistryService DEVICE_MANAGEMENT_OPERATION_REGISTRY_SERVICE = LOCATOR.getService(DeviceManagementOperationRegistryService.class); private static final ManagementOperationNotificationService MANAGEMENT_OPERATION_NOTIFICATION_SERVICE = LOCATOR.getService(ManagementOperationNotificationService.class); - private static final ManagementOperationNotificationFactory MANAGEMENT_OPERATION_NOTIFICATION_FACTORY = LOCATOR.getFactory(ManagementOperationNotificationFactory.class); private static final long serialVersionUID = 958857278895524016L; @Override @@ -69,7 +68,7 @@ public PagingLoadResult query(PagingLoadConfig loa if (dmo.getEndedOn() == null) { //TODO: #LAYER_VIOLATION - entity lookup should be done elsewhere - ManagementOperationNotificationQuery notificationQuery = MANAGEMENT_OPERATION_NOTIFICATION_FACTORY.newQuery(dmo.getScopeId()); + ManagementOperationNotificationQuery notificationQuery = new ManagementOperationNotificationQuery(dmo.getScopeId()); notificationQuery.setPredicate(notificationQuery.attributePredicate(ManagementOperationNotificationAttributes.OPERATION_ID, dmo.getId())); notificationQuery.setSortCriteria(notificationQuery.fieldSortCriteria(ManagementOperationNotificationAttributes.SENT_ON, SortOrder.ASCENDING)); diff --git a/console/module/device/src/main/java/org/eclipse/kapua/app/console/module/device/server/GwtDeviceManagementServiceImpl.java b/console/module/device/src/main/java/org/eclipse/kapua/app/console/module/device/server/GwtDeviceManagementServiceImpl.java index 5c7e51a348a..2576cd11392 100644 --- a/console/module/device/src/main/java/org/eclipse/kapua/app/console/module/device/server/GwtDeviceManagementServiceImpl.java +++ b/console/module/device/src/main/java/org/eclipse/kapua/app/console/module/device/server/GwtDeviceManagementServiceImpl.java @@ -73,19 +73,16 @@ import org.eclipse.kapua.service.device.management.bundle.DeviceBundle; import org.eclipse.kapua.service.device.management.bundle.DeviceBundleManagementService; import org.eclipse.kapua.service.device.management.bundle.DeviceBundles; -import org.eclipse.kapua.service.device.management.command.DeviceCommandFactory; import org.eclipse.kapua.service.device.management.command.DeviceCommandInput; import org.eclipse.kapua.service.device.management.command.DeviceCommandManagementService; import org.eclipse.kapua.service.device.management.command.DeviceCommandOutput; import org.eclipse.kapua.service.device.management.configuration.DeviceComponentConfiguration; import org.eclipse.kapua.service.device.management.configuration.DeviceConfiguration; -import org.eclipse.kapua.service.device.management.configuration.DeviceConfigurationFactory; import org.eclipse.kapua.service.device.management.configuration.DeviceConfigurationManagementService; import org.eclipse.kapua.service.device.management.configuration.store.DeviceConfigurationStoreFactory; import org.eclipse.kapua.service.device.management.configuration.store.DeviceConfigurationStoreService; import org.eclipse.kapua.service.device.management.configuration.store.settings.DeviceConfigurationStoreEnablementPolicy; import org.eclipse.kapua.service.device.management.configuration.store.settings.DeviceConfigurationStoreSettings; -import org.eclipse.kapua.service.device.management.packages.DevicePackageFactory; import org.eclipse.kapua.service.device.management.packages.DevicePackageManagementService; import org.eclipse.kapua.service.device.management.packages.model.DevicePackage; import org.eclipse.kapua.service.device.management.packages.model.DevicePackageBundleInfo; @@ -94,8 +91,10 @@ import org.eclipse.kapua.service.device.management.packages.model.FileType; import org.eclipse.kapua.service.device.management.packages.model.download.AdvancedPackageDownloadOptions; import org.eclipse.kapua.service.device.management.packages.model.download.DevicePackageDownloadOperation; +import org.eclipse.kapua.service.device.management.packages.model.download.DevicePackageDownloadOptions; import org.eclipse.kapua.service.device.management.packages.model.download.DevicePackageDownloadRequest; import org.eclipse.kapua.service.device.management.packages.model.download.DevicePackageDownloadStatus; +import org.eclipse.kapua.service.device.management.packages.model.uninstall.DevicePackageUninstallOptions; import org.eclipse.kapua.service.device.management.packages.model.uninstall.DevicePackageUninstallRequest; import org.eclipse.kapua.service.device.management.snapshot.DeviceSnapshot; import org.eclipse.kapua.service.device.management.snapshot.DeviceSnapshotManagementService; @@ -124,17 +123,14 @@ public class GwtDeviceManagementServiceImpl extends KapuaRemoteServiceServlet im private static final DeviceBundleManagementService BUNDLE_MANAGEMENT_SERVICE = LOCATOR.getService(DeviceBundleManagementService.class); private static final DeviceCommandManagementService COMMAND_MANAGEMENT_SERVICE = LOCATOR.getService(DeviceCommandManagementService.class); - private static final DeviceCommandFactory DEVICE_COMMAND_FACTORY = LOCATOR.getFactory(DeviceCommandFactory.class); private static final DeviceConfigurationManagementService CONFIGURATION_MANAGEMENT_SERVICE = LOCATOR.getService(DeviceConfigurationManagementService.class); - private static final DeviceConfigurationFactory DEVICE_CONFIGURATION_FACTORY = LOCATOR.getFactory(DeviceConfigurationFactory.class); private static final DeviceConfigurationStoreService DEVICE_CONFIGURATION_STORE_SERVICE = LOCATOR.getService(DeviceConfigurationStoreService.class); private static final DeviceConfigurationStoreFactory DEVICE_CONFIGURATION_STORE_FACTORY = LOCATOR.getFactory(DeviceConfigurationStoreFactory.class); private static final DevicePackageManagementService PACKAGE_MANAGEMENT_SERVICE = LOCATOR.getService(DevicePackageManagementService.class); - private static final DevicePackageFactory DEVICE_PACKAGE_FACTORY = LOCATOR.getFactory(DevicePackageFactory.class); private static final DeviceSnapshotManagementService SNAPSHOT_MANAGEMENT_SERVICE = LOCATOR.getService(DeviceSnapshotManagementService.class); @@ -192,7 +188,7 @@ public void installPackage(GwtXSRFToken xsrfToken, GwtPackageInstallRequest gwtP throw new GwtKapuaException(GwtKapuaErrorCode.PACKAGE_URI_SYNTAX_ERROR, e, e.getLocalizedMessage()); } - DevicePackageDownloadRequest packageDownloadRequest = DEVICE_PACKAGE_FACTORY.newPackageDownloadRequest(); + DevicePackageDownloadRequest packageDownloadRequest = new DevicePackageDownloadRequest(); packageDownloadRequest.setUri(packageUri); packageDownloadRequest.setName(gwtPackageInstallRequest.getPackageName()); packageDownloadRequest.setVersion(gwtPackageInstallRequest.getPackageVersion()); @@ -212,7 +208,7 @@ public void installPackage(GwtXSRFToken xsrfToken, GwtPackageInstallRequest gwtP advancedOptions.setNotifyBlockSize(gwtPackageInstallRequest.getNotifyBlockSize()); advancedOptions.setInstallVerifierURI(gwtPackageInstallRequest.getInstallVerifierURI()); - PACKAGE_MANAGEMENT_SERVICE.downloadExec(scopeId, deviceId, packageDownloadRequest, DEVICE_PACKAGE_FACTORY.newPackageDownloadOptions()); + PACKAGE_MANAGEMENT_SERVICE.downloadExec(scopeId, deviceId, packageDownloadRequest, new DevicePackageDownloadOptions()); } catch (Throwable t) { throw KapuaExceptionHandler.buildExceptionFromError(t); } @@ -254,13 +250,13 @@ public void uninstallPackage(GwtXSRFToken xsrfToken, GwtPackageUninstallRequest KapuaId scopeId = KapuaEid.parseCompactId(gwtPackageUninstallRequest.getScopeId()); KapuaId deviceId = KapuaEid.parseCompactId(gwtPackageUninstallRequest.getDeviceId()); - DevicePackageUninstallRequest packageUninstallRequest = DEVICE_PACKAGE_FACTORY.newPackageUninstallRequest(); + DevicePackageUninstallRequest packageUninstallRequest = new DevicePackageUninstallRequest(); packageUninstallRequest.setName(gwtPackageUninstallRequest.getPackageName()); packageUninstallRequest.setVersion(gwtPackageUninstallRequest.getPackageVersion()); packageUninstallRequest.setReboot(gwtPackageUninstallRequest.isReboot()); packageUninstallRequest.setRebootDelay(gwtPackageUninstallRequest.getRebootDelay()); - PACKAGE_MANAGEMENT_SERVICE.uninstallExec(scopeId, deviceId, packageUninstallRequest, DEVICE_PACKAGE_FACTORY.newPackageUninstallOptions()); + PACKAGE_MANAGEMENT_SERVICE.uninstallExec(scopeId, deviceId, packageUninstallRequest, new DevicePackageUninstallOptions()); } catch (Throwable t) { throw KapuaExceptionHandler.buildExceptionFromError(t); } @@ -398,7 +394,7 @@ public void updateComponentConfiguration(GwtXSRFToken xsrfToken, GwtDevice gwtDe // Checking validity of the given XSRF Token checkXSRFToken(xsrfToken); // Set name and properties - DeviceComponentConfiguration compConfig = DEVICE_CONFIGURATION_FACTORY.newComponentConfigurationInstance(gwtCompConfig.getUnescapedComponentId()); + DeviceComponentConfiguration compConfig = new DeviceComponentConfiguration(gwtCompConfig.getUnescapedComponentId()); compConfig.setName(gwtCompConfig.getUnescapedComponentName()); Map compProps = new HashMap(); @@ -625,7 +621,7 @@ public GwtDeviceCommandOutput executeCommand(GwtXSRFToken xsrfToken, GwtDevice g args[i++] = st.nextToken(); } - DeviceCommandInput commandInput = DEVICE_COMMAND_FACTORY.newCommandInput(); + DeviceCommandInput commandInput = new DeviceCommandInput(); commandInput.setArguments(args); commandInput.setCommand(command); commandInput.setEnvironment(gwtCommandInput.getEnvironment()); diff --git a/console/module/device/src/main/java/org/eclipse/kapua/app/console/module/device/server/GwtDeviceServiceImpl.java b/console/module/device/src/main/java/org/eclipse/kapua/app/console/module/device/server/GwtDeviceServiceImpl.java index 7644fc0c4fe..9b94b215435 100644 --- a/console/module/device/src/main/java/org/eclipse/kapua/app/console/module/device/server/GwtDeviceServiceImpl.java +++ b/console/module/device/src/main/java/org/eclipse/kapua/app/console/module/device/server/GwtDeviceServiceImpl.java @@ -18,12 +18,6 @@ import java.util.Set; import java.util.concurrent.Callable; -import com.extjs.gxt.ui.client.data.BaseListLoadResult; -import com.extjs.gxt.ui.client.data.BasePagingLoadConfig; -import com.extjs.gxt.ui.client.data.BasePagingLoadResult; -import com.extjs.gxt.ui.client.data.ListLoadResult; -import com.extjs.gxt.ui.client.data.PagingLoadConfig; -import com.extjs.gxt.ui.client.data.PagingLoadResult; import org.eclipse.kapua.KapuaDuplicateNameException; import org.eclipse.kapua.app.console.module.api.client.GwtKapuaException; import org.eclipse.kapua.app.console.module.api.server.KapuaRemoteServiceServlet; @@ -56,12 +50,11 @@ import org.eclipse.kapua.service.authorization.AuthorizationService; import org.eclipse.kapua.service.authorization.group.Group; import org.eclipse.kapua.service.authorization.group.GroupService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; +import org.eclipse.kapua.service.authorization.permission.Permission; import org.eclipse.kapua.service.device.registry.Device; import org.eclipse.kapua.service.device.registry.DeviceAttributes; import org.eclipse.kapua.service.device.registry.DeviceCreator; import org.eclipse.kapua.service.device.registry.DeviceExtendedProperty; -import org.eclipse.kapua.service.device.registry.DeviceFactory; import org.eclipse.kapua.service.device.registry.DeviceQuery; import org.eclipse.kapua.service.device.registry.DeviceRegistryService; import org.eclipse.kapua.service.device.registry.DeviceStatus; @@ -70,7 +63,6 @@ import org.eclipse.kapua.service.device.registry.connection.DeviceConnectionStatus; import org.eclipse.kapua.service.device.registry.event.DeviceEvent; import org.eclipse.kapua.service.device.registry.event.DeviceEventAttributes; -import org.eclipse.kapua.service.device.registry.event.DeviceEventFactory; import org.eclipse.kapua.service.device.registry.event.DeviceEventQuery; import org.eclipse.kapua.service.device.registry.event.DeviceEventService; import org.eclipse.kapua.service.tag.Tag; @@ -78,6 +70,13 @@ import org.eclipse.kapua.service.user.User; import org.eclipse.kapua.service.user.UserService; +import com.extjs.gxt.ui.client.data.BaseListLoadResult; +import com.extjs.gxt.ui.client.data.BasePagingLoadConfig; +import com.extjs.gxt.ui.client.data.BasePagingLoadResult; +import com.extjs.gxt.ui.client.data.ListLoadResult; +import com.extjs.gxt.ui.client.data.PagingLoadConfig; +import com.extjs.gxt.ui.client.data.PagingLoadResult; + /** * The server side implementation of the Device RPC service. */ @@ -87,7 +86,6 @@ public class GwtDeviceServiceImpl extends KapuaRemoteServiceServlet implements G private static final KapuaLocator LOCATOR = KapuaLocator.getInstance(); private static final AuthorizationService AUTHORIZATION_SERVICE = LOCATOR.getService(AuthorizationService.class); - private static final PermissionFactory PERMISSION_FACTORY = LOCATOR.getFactory(PermissionFactory.class); private boolean isSameId; @@ -180,7 +178,7 @@ public User call() throws Exception { pairs.add(new GwtGroupedNVPair(CONN_INFO, "connConnectionStatus", deviceConnection.getStatus().toString())); pairs.add(new GwtGroupedNVPair(CONN_INFO, "connClientId", device.getClientId())); pairs.add(new GwtGroupedNVPair(CONN_INFO, "connUserName", lastConnectedUser != null ? lastConnectedUser.getName() : null)); - if (AUTHORIZATION_SERVICE.isPermitted(PERMISSION_FACTORY.newPermission(Domains.USER, Actions.read, scopeId))) { + if (AUTHORIZATION_SERVICE.isPermitted(new Permission(Domains.USER, Actions.read, scopeId))) { pairs.add(new GwtGroupedNVPair(CONN_INFO, "connReservedUserId", reservedUser != null ? reservedUser.getName() : null)); } pairs.add(new GwtGroupedNVPair(CONN_INFO, "connUserCouplingMode", GwtConnectionUserCouplingMode.valueOf(deviceConnection.getUserCouplingMode().name()).getLabel())); @@ -194,7 +192,7 @@ public User call() throws Exception { pairs.add(new GwtGroupedNVPair(CONN_INFO, "connConnectionStatus", DeviceConnectionStatus.DISCONNECTED.toString())); pairs.add(new GwtGroupedNVPair(CONN_INFO, "connClientId", null)); pairs.add(new GwtGroupedNVPair(CONN_INFO, "connUserName", null)); - if (AUTHORIZATION_SERVICE.isPermitted(PERMISSION_FACTORY.newPermission(Domains.USER, Actions.read, scopeId))) { + if (AUTHORIZATION_SERVICE.isPermitted(new Permission(Domains.USER, Actions.read, scopeId))) { pairs.add(new GwtGroupedNVPair(CONN_INFO, "connReservedUserId", null)); } pairs.add(new GwtGroupedNVPair(CONN_INFO, "connUserCouplingMode", null)); @@ -208,7 +206,7 @@ public User call() throws Exception { pairs.add(new GwtGroupedNVPair(DEV_INFO, "devClientId", device.getClientId())); pairs.add(new GwtGroupedNVPair(DEV_INFO, "devDisplayName", device.getDisplayName())); - if (AUTHORIZATION_SERVICE.isPermitted(PERMISSION_FACTORY.newPermission(Domains.GROUP, Actions.read, device.getScopeId()))) { + if (AUTHORIZATION_SERVICE.isPermitted(new Permission(Domains.GROUP, Actions.read, device.getScopeId()))) { if (device.getGroupId() != null) { Group group = groupService.find(scopeId, device.getGroupId()); @@ -220,7 +218,7 @@ public User call() throws Exception { } } - if (AUTHORIZATION_SERVICE.isPermitted(PERMISSION_FACTORY.newPermission(Domains.DEVICE_EVENT, Actions.read, device.getScopeId()))) { + if (AUTHORIZATION_SERVICE.isPermitted(new Permission(Domains.DEVICE_EVENT, Actions.read, device.getScopeId()))) { if (device.getLastEventId() != null) { DeviceEvent lastEvent = deviceEventService.find(scopeId, device.getLastEventId()); @@ -263,9 +261,8 @@ public User call() throws Exception { pairs.add(new GwtGroupedNVPair("devJava", "devJvmVersion", device.getJvmVersion())); // GPS infos retrieval - if (AUTHORIZATION_SERVICE.isPermitted(PERMISSION_FACTORY.newPermission(Domains.DEVICE_EVENT, Actions.read, device.getScopeId()))) { - DeviceEventFactory deviceEventFactory = locator.getFactory(DeviceEventFactory.class); - DeviceEventQuery query = deviceEventFactory.newQuery(device.getScopeId()); + if (AUTHORIZATION_SERVICE.isPermitted(new Permission(Domains.DEVICE_EVENT, Actions.read, device.getScopeId()))) { + DeviceEventQuery query = new DeviceEventQuery(device.getScopeId()); query.setLimit(1); query.setSortCriteria(query.fieldSortCriteria(DeviceEventAttributes.RECEIVED_ON, SortOrder.DESCENDING)); @@ -378,13 +375,12 @@ public GwtDevice createDevice(GwtXSRFToken xsrfToken, GwtDeviceCreator gwtDevice KapuaLocator locator = KapuaLocator.getInstance(); DeviceRegistryService deviceRegistryService = locator.getService(DeviceRegistryService.class); - DeviceFactory deviceFactory = locator.getFactory(DeviceFactory.class); GwtDevice gwtDevice = null; try { KapuaId scopeId = KapuaEid.parseCompactId(gwtDeviceCreator.getScopeId()); - DeviceCreator deviceCreator = deviceFactory.newCreator(scopeId, gwtDeviceCreator.getClientId()); + DeviceCreator deviceCreator = new DeviceCreator(scopeId, gwtDeviceCreator.getClientId()); deviceCreator.setDisplayName(gwtDeviceCreator.getDisplayName()); deviceCreator.setGroupId(GwtKapuaCommonsModelConverter.convertKapuaId(gwtDeviceCreator.getGroupId())); deviceCreator.setStatus((DeviceStatus.valueOf(gwtDeviceCreator.getDeviceStatus()))); @@ -534,22 +530,21 @@ public void deleteDeviceTag(GwtXSRFToken xsrfToken, String scopeIdString, String @Override public PagingLoadResult findDeviceEvents(PagingLoadConfig loadConfig, - GwtDevice gwtDevice, - Date startDate, - Date endDate) + GwtDevice gwtDevice, + Date startDate, + Date endDate) throws GwtKapuaException { ArrayList gwtDeviceEvents = new ArrayList(); BasePagingLoadResult gwtResults = null; KapuaLocator locator = KapuaLocator.getInstance(); DeviceEventService des = locator.getService(DeviceEventService.class); - DeviceEventFactory deviceEventFactory = locator.getFactory(DeviceEventFactory.class); try { // prepare the query BasePagingLoadConfig bplc = (BasePagingLoadConfig) loadConfig; - DeviceEventQuery query = deviceEventFactory.newQuery(KapuaEid.parseCompactId(gwtDevice.getScopeId())); + DeviceEventQuery query = new DeviceEventQuery(KapuaEid.parseCompactId(gwtDevice.getScopeId())); AndPredicate andPredicate = query.andPredicate( query.attributePredicate(DeviceEventAttributes.DEVICE_ID, KapuaEid.parseCompactId(gwtDevice.getId())), diff --git a/console/module/device/src/main/java/org/eclipse/kapua/app/console/module/device/servlet/DeviceEventExporterServlet.java b/console/module/device/src/main/java/org/eclipse/kapua/app/console/module/device/servlet/DeviceEventExporterServlet.java index 88d80d63547..012725e121a 100644 --- a/console/module/device/src/main/java/org/eclipse/kapua/app/console/module/device/servlet/DeviceEventExporterServlet.java +++ b/console/module/device/src/main/java/org/eclipse/kapua/app/console/module/device/servlet/DeviceEventExporterServlet.java @@ -12,6 +12,15 @@ *******************************************************************************/ package org.eclipse.kapua.app.console.module.device.servlet; +import java.io.IOException; +import java.util.Date; +import java.util.concurrent.Callable; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + import org.eclipse.kapua.KapuaEntityNotFoundException; import org.eclipse.kapua.KapuaIllegalAccessException; import org.eclipse.kapua.KapuaUnauthenticatedException; @@ -28,20 +37,11 @@ import org.eclipse.kapua.service.device.registry.DeviceRegistryService; import org.eclipse.kapua.service.device.registry.event.DeviceEvent; import org.eclipse.kapua.service.device.registry.event.DeviceEventAttributes; -import org.eclipse.kapua.service.device.registry.event.DeviceEventFactory; import org.eclipse.kapua.service.device.registry.event.DeviceEventQuery; import org.eclipse.kapua.service.device.registry.event.DeviceEventService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.util.Date; -import java.util.concurrent.Callable; - public class DeviceEventExporterServlet extends HttpServlet { private static final long serialVersionUID = -2533869595709953567L; @@ -87,13 +87,13 @@ private void internalDoGet(HttpServletRequest request, HttpServletResponse respo // get the devices and append them to the exporter KapuaLocator locator = KapuaLocator.getInstance(); DeviceEventService des = locator.getService(DeviceEventService.class); - DeviceEventFactory def = locator.getFactory(DeviceEventFactory.class); final AccountService as = locator.getService(AccountService.class); final DeviceRegistryService deviceRegistryService = locator.getService(DeviceRegistryService.class); final KapuaIdFactory kif = locator.getFactory(KapuaIdFactory.class); Device device = KapuaSecurityUtils.doPrivileged(new Callable() { + @Override public Device call() throws Exception { return deviceRegistryService.find(KapuaEid.parseCompactId(scopeId), KapuaEid.parseCompactId(deviceId)); @@ -113,7 +113,7 @@ public Account call() throws Exception { int offset = 0; // paginate through the matching message - DeviceEventQuery query = def.newQuery(KapuaEid.parseCompactId(scopeId)); + DeviceEventQuery query = new DeviceEventQuery(KapuaEid.parseCompactId(scopeId)); query.setLimit(250); // Inserting filter parameter if specified diff --git a/console/module/device/src/main/java/org/eclipse/kapua/app/console/module/device/servlet/DeviceExporterServlet.java b/console/module/device/src/main/java/org/eclipse/kapua/app/console/module/device/servlet/DeviceExporterServlet.java index bad21ee8e21..f5dd0e4b02e 100644 --- a/console/module/device/src/main/java/org/eclipse/kapua/app/console/module/device/servlet/DeviceExporterServlet.java +++ b/console/module/device/src/main/java/org/eclipse/kapua/app/console/module/device/servlet/DeviceExporterServlet.java @@ -12,6 +12,14 @@ *******************************************************************************/ package org.eclipse.kapua.app.console.module.device.servlet; +import java.io.IOException; +import java.util.concurrent.Callable; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + import org.eclipse.kapua.KapuaEntityNotFoundException; import org.eclipse.kapua.KapuaIllegalAccessException; import org.eclipse.kapua.KapuaUnauthenticatedException; @@ -36,13 +44,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.util.concurrent.Callable; - public class DeviceExporterServlet extends HttpServlet { private static final long serialVersionUID = -2533869595709953567L; @@ -96,7 +97,7 @@ public Account call() throws Exception { int offset = 0; // paginate through the matching message - DeviceQuery query = drf.newQuery(KapuaEid.parseCompactId(scopeIdString)); + DeviceQuery query = new DeviceQuery(KapuaEid.parseCompactId(scopeIdString)); query.setLimit(250); // Inserting filter parameter if specified @@ -154,7 +155,7 @@ public Account call() throws Exception { String tagId = request.getParameter("tag"); if (tagId != null && !tagId.isEmpty()) { - andPred = andPred.and(query.attributePredicate(DeviceAttributes.TAG_IDS, new KapuaId[]{KapuaEid.parseCompactId(tagId)})); + andPred = andPred.and(query.attributePredicate(DeviceAttributes.TAG_IDS, new KapuaId[] { KapuaEid.parseCompactId(tagId) })); } String sortAttribute = request.getParameter("sortAttribute"); diff --git a/console/module/device/src/main/java/org/eclipse/kapua/app/console/module/device/shared/util/GwtKapuaDeviceModelConverter.java b/console/module/device/src/main/java/org/eclipse/kapua/app/console/module/device/shared/util/GwtKapuaDeviceModelConverter.java index 4a70ef4d824..f6908bf4cb7 100644 --- a/console/module/device/src/main/java/org/eclipse/kapua/app/console/module/device/shared/util/GwtKapuaDeviceModelConverter.java +++ b/console/module/device/src/main/java/org/eclipse/kapua/app/console/module/device/shared/util/GwtKapuaDeviceModelConverter.java @@ -12,8 +12,9 @@ *******************************************************************************/ package org.eclipse.kapua.app.console.module.device.shared.util; -import com.extjs.gxt.ui.client.Style.SortDir; -import com.extjs.gxt.ui.client.data.PagingLoadConfig; +import java.util.ArrayList; +import java.util.List; + import org.apache.commons.lang3.StringUtils; import org.eclipse.kapua.app.console.module.api.shared.util.GwtKapuaCommonsModelConverter; import org.eclipse.kapua.app.console.module.device.shared.model.GwtDeviceQuery; @@ -26,7 +27,6 @@ import org.eclipse.kapua.app.console.module.device.shared.model.management.assets.GwtDeviceAssets; import org.eclipse.kapua.app.console.module.device.shared.model.management.registry.GwtDeviceManagementOperationQuery; import org.eclipse.kapua.commons.model.id.KapuaEid; -import org.eclipse.kapua.locator.KapuaLocator; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.model.query.FieldSortCriteria; import org.eclipse.kapua.model.query.SortOrder; @@ -37,39 +37,26 @@ import org.eclipse.kapua.service.device.management.asset.DeviceAsset; import org.eclipse.kapua.service.device.management.asset.DeviceAssetChannel; import org.eclipse.kapua.service.device.management.asset.DeviceAssetChannelMode; -import org.eclipse.kapua.service.device.management.asset.DeviceAssetFactory; import org.eclipse.kapua.service.device.management.asset.DeviceAssets; import org.eclipse.kapua.service.device.management.registry.operation.DeviceManagementOperationAttributes; -import org.eclipse.kapua.service.device.management.registry.operation.DeviceManagementOperationFactory; import org.eclipse.kapua.service.device.management.registry.operation.DeviceManagementOperationQuery; import org.eclipse.kapua.service.device.registry.DeviceAttributes; -import org.eclipse.kapua.service.device.registry.DeviceFactory; import org.eclipse.kapua.service.device.registry.DeviceQuery; import org.eclipse.kapua.service.device.registry.DeviceStatus; import org.eclipse.kapua.service.device.registry.connection.DeviceConnectionAttributes; -import org.eclipse.kapua.service.device.registry.connection.DeviceConnectionFactory; import org.eclipse.kapua.service.device.registry.connection.DeviceConnectionQuery; import org.eclipse.kapua.service.device.registry.connection.DeviceConnectionStatus; -import java.util.ArrayList; -import java.util.List; +import com.extjs.gxt.ui.client.Style.SortDir; +import com.extjs.gxt.ui.client.data.PagingLoadConfig; public class GwtKapuaDeviceModelConverter { - private static final KapuaLocator LOCATOR = KapuaLocator.getInstance(); - - private static final DeviceFactory DEVICE_FACTORY = LOCATOR.getFactory(DeviceFactory.class); - private static final DeviceConnectionFactory DEVICE_CONNECTION_FACTORY = LOCATOR.getFactory(DeviceConnectionFactory.class); - private static final DeviceManagementOperationFactory DEVICE_MANAGEMENT_OPERATION_FACTORY = LOCATOR.getFactory(DeviceManagementOperationFactory.class); - - private static final DeviceAssetFactory ASSET_FACTORY = LOCATOR.getFactory(DeviceAssetFactory.class); - - private GwtKapuaDeviceModelConverter() { } public static DeviceConnectionQuery convertConnectionQuery(PagingLoadConfig loadConfig, GwtDeviceConnectionQuery gwtDeviceConnectionQuery) { - DeviceConnectionQuery query = DEVICE_CONNECTION_FACTORY.newQuery(GwtKapuaCommonsModelConverter.convertKapuaId(gwtDeviceConnectionQuery.getScopeId())); + DeviceConnectionQuery query = new DeviceConnectionQuery(GwtKapuaCommonsModelConverter.convertKapuaId(gwtDeviceConnectionQuery.getScopeId())); AndPredicate predicate = query.andPredicate(); if (gwtDeviceConnectionQuery.getClientId() != null && !gwtDeviceConnectionQuery.getClientId().trim().isEmpty()) { @@ -89,11 +76,11 @@ public static DeviceConnectionQuery convertConnectionQuery(PagingLoadConfig load } if (gwtDeviceConnectionQuery.getGwtDeviceConnectionReservedUser() != null) { switch (gwtDeviceConnectionQuery.getGwtDeviceConnectionReservedUser()) { - case NONE: - predicate = predicate.and(query.attributePredicate(DeviceConnectionAttributes.RESERVED_USER_ID, null, Operator.IS_NULL)); - break; - default: - predicate = predicate.and(query.attributePredicate(DeviceConnectionAttributes.RESERVED_USER_ID, KapuaEid.parseCompactId(gwtDeviceConnectionQuery.getReservedUserId()))); + case NONE: + predicate = predicate.and(query.attributePredicate(DeviceConnectionAttributes.RESERVED_USER_ID, null, Operator.IS_NULL)); + break; + default: + predicate = predicate.and(query.attributePredicate(DeviceConnectionAttributes.RESERVED_USER_ID, KapuaEid.parseCompactId(gwtDeviceConnectionQuery.getReservedUserId()))); } } @@ -122,7 +109,7 @@ public static DeviceConnectionStatus convertConnectionStatus(String connectionSt } public static DeviceAssets convertDeviceAssets(GwtDeviceAssets deviceAssets) { - DeviceAssets assets = ASSET_FACTORY.newAssetListResult(); + DeviceAssets assets = new DeviceAssets(); List assetList = new ArrayList(); for (GwtDeviceAsset gwtDeviceAsset : deviceAssets.getAssets()) { assetList.add(convertDeviceAsset(gwtDeviceAsset)); @@ -133,7 +120,7 @@ public static DeviceAssets convertDeviceAssets(GwtDeviceAssets deviceAssets) { public static DeviceAsset convertDeviceAsset(GwtDeviceAsset gwtDeviceAsset) { - DeviceAsset deviceAsset = ASSET_FACTORY.newDeviceAsset(); + DeviceAsset deviceAsset = new DeviceAsset(); deviceAsset.setName(gwtDeviceAsset.getName()); for (GwtDeviceAssetChannel gwtDeviceAssetChannel : gwtDeviceAsset.getChannels()) { deviceAsset.getChannels().add(convertDeviceAssetChannel(gwtDeviceAssetChannel)); @@ -143,7 +130,7 @@ public static DeviceAsset convertDeviceAsset(GwtDeviceAsset gwtDeviceAsset) { public static DeviceAssetChannel convertDeviceAssetChannel(GwtDeviceAssetChannel gwtDeviceAssetChannel) { - DeviceAssetChannel channel = ASSET_FACTORY.newDeviceAssetChannel(); + DeviceAssetChannel channel = new DeviceAssetChannel(); channel.setName(gwtDeviceAssetChannel.getName()); try { channel.setType(ObjectTypeConverter.fromString(gwtDeviceAssetChannel.getType())); @@ -163,7 +150,7 @@ public static DeviceAssetChannelMode convertDeviceAssetChannel(GwtDeviceAssetCha } public static DeviceQuery convertDeviceQuery(PagingLoadConfig loadConfig, GwtDeviceQuery gwtDeviceQuery) { - DeviceQuery query = DEVICE_FACTORY.newQuery(KapuaEid.parseCompactId(gwtDeviceQuery.getScopeId())); + DeviceQuery query = new DeviceQuery(KapuaEid.parseCompactId(gwtDeviceQuery.getScopeId())); if (loadConfig != null) { query.setLimit(loadConfig.getLimit()); @@ -199,22 +186,22 @@ public static DeviceQuery convertDeviceQuery(PagingLoadConfig loadConfig, GwtDev } if (predicates.getDeviceConnectionStatus() != null) { switch (predicates.getDeviceConnectionStatusEnum()) { - case UNKNOWN: - andPred = andPred.and(query.attributePredicate(DeviceAttributes.CONNECTION_ID, DeviceConnectionStatus.NULL, Operator.IS_NULL)); - break; - default: - andPred = andPred.and(query.attributePredicate(DeviceAttributes.CONNECTION_STATUS, DeviceConnectionStatus.valueOf(predicates.getDeviceConnectionStatus()))); + case UNKNOWN: + andPred = andPred.and(query.attributePredicate(DeviceAttributes.CONNECTION_ID, DeviceConnectionStatus.NULL, Operator.IS_NULL)); + break; + default: + andPred = andPred.and(query.attributePredicate(DeviceAttributes.CONNECTION_STATUS, DeviceConnectionStatus.valueOf(predicates.getDeviceConnectionStatus()))); } } if (predicates.getGroupDevice() != null) { switch (predicates.getGroupDeviceEnum()) { - case NO_GROUP: - andPred = andPred.and(query.attributePredicate(DeviceAttributes.GROUP_ID, null, Operator.IS_NULL)); - break; - default: - if (predicates.getGroupId() != null) { - andPred = andPred.and(query.attributePredicate(DeviceAttributes.GROUP_ID, KapuaEid.parseCompactId(predicates.getGroupId()))); - } + case NO_GROUP: + andPred = andPred.and(query.attributePredicate(DeviceAttributes.GROUP_ID, null, Operator.IS_NULL)); + break; + default: + if (predicates.getGroupId() != null) { + andPred = andPred.and(query.attributePredicate(DeviceAttributes.GROUP_ID, KapuaEid.parseCompactId(predicates.getGroupId()))); + } } } if (predicates.getTagIds() != null) { @@ -241,10 +228,9 @@ public static DeviceQuery convertDeviceQuery(PagingLoadConfig loadConfig, GwtDev return query; } - public static DeviceManagementOperationQuery convertDeviceManagementOperationQuery(PagingLoadConfig loadConfig, GwtDeviceManagementOperationQuery gwtQuery) { - DeviceManagementOperationQuery query = DEVICE_MANAGEMENT_OPERATION_FACTORY.newQuery(KapuaEid.parseCompactId(gwtQuery.getScopeId())); + DeviceManagementOperationQuery query = new DeviceManagementOperationQuery(KapuaEid.parseCompactId(gwtQuery.getScopeId())); String deviceId = gwtQuery.getDeviceId(); AndPredicate andPredicate = query.andPredicate(); diff --git a/console/module/endpoint/pom.xml b/console/module/endpoint/pom.xml index 8648d5dc7b3..208224109ec 100644 --- a/console/module/endpoint/pom.xml +++ b/console/module/endpoint/pom.xml @@ -19,7 +19,7 @@ kapua-console-module org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-console-module-endpoint diff --git a/console/module/endpoint/src/main/java/org/eclipse/kapua/app/console/module/endpoint/server/GwtEndpointServiceImpl.java b/console/module/endpoint/src/main/java/org/eclipse/kapua/app/console/module/endpoint/server/GwtEndpointServiceImpl.java index 23e8fd15552..c62077d1287 100644 --- a/console/module/endpoint/src/main/java/org/eclipse/kapua/app/console/module/endpoint/server/GwtEndpointServiceImpl.java +++ b/console/module/endpoint/src/main/java/org/eclipse/kapua/app/console/module/endpoint/server/GwtEndpointServiceImpl.java @@ -12,11 +12,14 @@ *******************************************************************************/ package org.eclipse.kapua.app.console.module.endpoint.server; -import com.extjs.gxt.ui.client.data.BaseListLoadResult; -import com.extjs.gxt.ui.client.data.BasePagingLoadResult; -import com.extjs.gxt.ui.client.data.ListLoadResult; -import com.extjs.gxt.ui.client.data.PagingLoadConfig; -import com.extjs.gxt.ui.client.data.PagingLoadResult; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.Callable; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.app.console.module.api.client.GwtKapuaException; import org.eclipse.kapua.app.console.module.api.server.KapuaRemoteServiceServlet; @@ -37,23 +40,20 @@ import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.endpoint.EndpointInfo; import org.eclipse.kapua.service.endpoint.EndpointInfoCreator; -import org.eclipse.kapua.service.endpoint.EndpointInfoFactory; import org.eclipse.kapua.service.endpoint.EndpointInfoListResult; import org.eclipse.kapua.service.endpoint.EndpointInfoQuery; import org.eclipse.kapua.service.endpoint.EndpointInfoService; import org.eclipse.kapua.service.endpoint.EndpointUsage; import org.eclipse.kapua.service.user.User; -import org.eclipse.kapua.service.user.UserFactory; import org.eclipse.kapua.service.user.UserListResult; +import org.eclipse.kapua.service.user.UserQuery; import org.eclipse.kapua.service.user.UserService; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.Callable; +import com.extjs.gxt.ui.client.data.BaseListLoadResult; +import com.extjs.gxt.ui.client.data.BasePagingLoadResult; +import com.extjs.gxt.ui.client.data.ListLoadResult; +import com.extjs.gxt.ui.client.data.PagingLoadConfig; +import com.extjs.gxt.ui.client.data.PagingLoadResult; public class GwtEndpointServiceImpl extends KapuaRemoteServiceServlet implements GwtEndpointService { @@ -62,10 +62,8 @@ public class GwtEndpointServiceImpl extends KapuaRemoteServiceServlet implements private static final KapuaLocator LOCATOR = KapuaLocator.getInstance(); private static final EndpointInfoService ENDPOINT_INFO_SERVICE = LOCATOR.getService(EndpointInfoService.class); - private static final EndpointInfoFactory ENDPOINT_INFO_FACTORY = LOCATOR.getFactory(EndpointInfoFactory.class); private static final UserService USER_SERVICE = LOCATOR.getService(UserService.class); - private static final UserFactory USER_FACTORY = LOCATOR.getFactory(UserFactory.class); private static final String ENDPOINT_INFO = "endpointInfo"; private static final String ENTITY_INFO = "entityInfo"; @@ -77,7 +75,7 @@ public GwtEndpoint create(GwtXSRFToken xsrfToken, GwtEndpointCreator gwtEndpoint try { KapuaId scopeId = KapuaEid.parseCompactId(gwtEndpointCreator.getScopeId()); - EndpointInfoCreator endpointCreator = ENDPOINT_INFO_FACTORY.newCreator(scopeId); + EndpointInfoCreator endpointCreator = new EndpointInfoCreator(scopeId); endpointCreator.setSchema(gwtEndpointCreator.getSchema()); endpointCreator.setDns(gwtEndpointCreator.getDns()); endpointCreator.setPort(gwtEndpointCreator.getPort().intValue()); @@ -153,7 +151,7 @@ public PagingLoadResult query(PagingLoadConfig loadConfig, final Gw @Override public UserListResult call() throws Exception { - return USER_SERVICE.query(USER_FACTORY.newQuery(null)); + return USER_SERVICE.query(new UserQuery(null)); } }); @@ -205,7 +203,7 @@ public ListLoadResult getEndpointDescription(String scopeShort @Override public UserListResult call() throws Exception { - return USER_SERVICE.query(USER_FACTORY.newQuery(null)); + return USER_SERVICE.query(new UserQuery(null)); } }); @@ -244,7 +242,7 @@ public List findAll(String scopeId) throws GwtKapuaException { List endpointList = new ArrayList(); try { - EndpointInfoQuery query = ENDPOINT_INFO_FACTORY.newQuery(GwtKapuaCommonsModelConverter.convertKapuaId(scopeId)); + EndpointInfoQuery query = new EndpointInfoQuery(GwtKapuaCommonsModelConverter.convertKapuaId(scopeId)); EndpointInfoListResult result = ENDPOINT_INFO_SERVICE.query(query); for (EndpointInfo endpoint : result.getItems()) { diff --git a/console/module/endpoint/src/main/java/org/eclipse/kapua/app/console/module/endpoint/shared/util/GwtKapuaEndpointModelConverter.java b/console/module/endpoint/src/main/java/org/eclipse/kapua/app/console/module/endpoint/shared/util/GwtKapuaEndpointModelConverter.java index 34869622759..6aa8b7eea48 100644 --- a/console/module/endpoint/src/main/java/org/eclipse/kapua/app/console/module/endpoint/shared/util/GwtKapuaEndpointModelConverter.java +++ b/console/module/endpoint/src/main/java/org/eclipse/kapua/app/console/module/endpoint/shared/util/GwtKapuaEndpointModelConverter.java @@ -12,25 +12,21 @@ *******************************************************************************/ package org.eclipse.kapua.app.console.module.endpoint.shared.util; -import com.extjs.gxt.ui.client.Style.SortDir; -import com.extjs.gxt.ui.client.data.PagingLoadConfig; -import com.google.common.base.Strings; import org.apache.commons.lang3.StringUtils; import org.eclipse.kapua.app.console.module.api.shared.util.GwtKapuaCommonsModelConverter; import org.eclipse.kapua.app.console.module.endpoint.shared.model.GwtEndpointQuery; import org.eclipse.kapua.model.query.FieldSortCriteria; import org.eclipse.kapua.model.query.SortOrder; -import org.eclipse.kapua.locator.KapuaLocator; import org.eclipse.kapua.model.query.predicate.AndPredicate; import org.eclipse.kapua.model.query.predicate.AttributePredicate; import org.eclipse.kapua.service.endpoint.EndpointInfoAttributes; -import org.eclipse.kapua.service.endpoint.EndpointInfoFactory; import org.eclipse.kapua.service.endpoint.EndpointInfoQuery; -public class GwtKapuaEndpointModelConverter { +import com.extjs.gxt.ui.client.Style.SortDir; +import com.extjs.gxt.ui.client.data.PagingLoadConfig; +import com.google.common.base.Strings; - private static final KapuaLocator LOCATOR = KapuaLocator.getInstance(); - private static final EndpointInfoFactory ENDPOINT_FACTORY = LOCATOR.getFactory(EndpointInfoFactory.class); +public class GwtKapuaEndpointModelConverter { private GwtKapuaEndpointModelConverter() { } @@ -38,13 +34,15 @@ private GwtKapuaEndpointModelConverter() { /** * Converts a {@link GwtEndpointQuery} into a {@link EndpointInfoQuery} object for backend usage * - * @param loadConfig the load configuration - * @param gwtEndpointQuery the {@link GwtEndpointQuery} to convertKapuaId + * @param loadConfig + * the load configuration + * @param gwtEndpointQuery + * the {@link GwtEndpointQuery} to convertKapuaId * @return the converted {@link EndpointInfoQuery} */ public static EndpointInfoQuery convertEndpointQuery(PagingLoadConfig loadConfig, GwtEndpointQuery gwtEndpointQuery) { - EndpointInfoQuery query = ENDPOINT_FACTORY.newQuery(GwtKapuaCommonsModelConverter.convertKapuaId(gwtEndpointQuery.getScopeId())); + EndpointInfoQuery query = new EndpointInfoQuery(GwtKapuaCommonsModelConverter.convertKapuaId(gwtEndpointQuery.getScopeId())); // Predicates conversion AndPredicate andPredicate = query.andPredicate(); diff --git a/console/module/job/pom.xml b/console/module/job/pom.xml index 8344a29a1b8..584329c8ef6 100644 --- a/console/module/job/pom.xml +++ b/console/module/job/pom.xml @@ -19,7 +19,7 @@ kapua-console-module org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-console-module-job diff --git a/console/module/job/src/main/java/org/eclipse/kapua/app/console/module/job/server/GwtJobEngineServiceImpl.java b/console/module/job/src/main/java/org/eclipse/kapua/app/console/module/job/server/GwtJobEngineServiceImpl.java index 7788a431dc5..1d22ef9b723 100644 --- a/console/module/job/src/main/java/org/eclipse/kapua/app/console/module/job/server/GwtJobEngineServiceImpl.java +++ b/console/module/job/src/main/java/org/eclipse/kapua/app/console/module/job/server/GwtJobEngineServiceImpl.java @@ -12,6 +12,9 @@ *******************************************************************************/ package org.eclipse.kapua.app.console.module.job.server; +import java.util.ArrayList; +import java.util.Collections; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.app.console.module.api.client.GwtKapuaErrorCode; import org.eclipse.kapua.app.console.module.api.client.GwtKapuaException; @@ -21,30 +24,23 @@ import org.eclipse.kapua.app.console.module.job.shared.model.GwtJobStartOptions; import org.eclipse.kapua.app.console.module.job.shared.service.GwtJobEngineService; import org.eclipse.kapua.app.console.module.job.shared.util.GwtKapuaJobModelConverter; -import org.eclipse.kapua.job.engine.JobEngineFactory; import org.eclipse.kapua.job.engine.JobEngineService; import org.eclipse.kapua.job.engine.JobStartOptions; import org.eclipse.kapua.locator.KapuaLocator; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.model.query.SortOrder; import org.eclipse.kapua.service.job.execution.JobExecutionAttributes; -import org.eclipse.kapua.service.job.execution.JobExecutionFactory; import org.eclipse.kapua.service.job.execution.JobExecutionListResult; import org.eclipse.kapua.service.job.execution.JobExecutionQuery; import org.eclipse.kapua.service.job.execution.JobExecutionService; -import java.util.ArrayList; -import java.util.Collections; - public class GwtJobEngineServiceImpl extends KapuaRemoteServiceServlet implements GwtJobEngineService { private static final KapuaLocator LOCATOR = KapuaLocator.getInstance(); private static final JobEngineService JOB_ENGINE_SERVICE = LOCATOR.getService(JobEngineService.class); - private static final JobEngineFactory JOB_ENGINE_FACTORY = LOCATOR.getFactory(JobEngineFactory.class); private static final JobExecutionService JOB_EXECUTION_SERVICE = LOCATOR.getService(JobExecutionService.class); - private static final JobExecutionFactory JOB_EXECUTION_FACTORY = LOCATOR.getFactory(JobExecutionFactory.class); @Override public void start(String gwtScopeId, String gwtJobId) throws GwtKapuaException { @@ -62,7 +58,7 @@ public void start(String gwtScopeId, String gwtJobId, GwtJobStartOptions gwtJobS if (gwtJobStartOptions != null) { jobStartOptions = GwtKapuaJobModelConverter.convertJobStartOptions(gwtJobStartOptions); } else { - jobStartOptions = JOB_ENGINE_FACTORY.newJobStartOptions(); + jobStartOptions = new JobStartOptions(); } @@ -88,7 +84,7 @@ public void stopExecution(String gwtScopeId, String gwtJobId, String gwtJobExecu try { if (jobExecutionId == null) { //TODO: #LAYER_VIOLATION - job execution lookup should not be done here (horribly inefficient) - JobExecutionQuery query = JOB_EXECUTION_FACTORY.newQuery(scopeId); + JobExecutionQuery query = new JobExecutionQuery(scopeId); query.setPredicate( query.andPredicate( diff --git a/console/module/job/src/main/java/org/eclipse/kapua/app/console/module/job/server/GwtJobServiceImpl.java b/console/module/job/src/main/java/org/eclipse/kapua/app/console/module/job/server/GwtJobServiceImpl.java index 2824b9d7f1b..8c22430d29a 100644 --- a/console/module/job/src/main/java/org/eclipse/kapua/app/console/module/job/server/GwtJobServiceImpl.java +++ b/console/module/job/src/main/java/org/eclipse/kapua/app/console/module/job/server/GwtJobServiceImpl.java @@ -12,11 +12,12 @@ *******************************************************************************/ package org.eclipse.kapua.app.console.module.job.server; -import com.extjs.gxt.ui.client.data.BaseListLoadResult; -import com.extjs.gxt.ui.client.data.BasePagingLoadResult; -import com.extjs.gxt.ui.client.data.ListLoadResult; -import com.extjs.gxt.ui.client.data.PagingLoadConfig; -import com.extjs.gxt.ui.client.data.PagingLoadResult; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.Callable; + import org.eclipse.kapua.app.console.module.api.client.GwtKapuaException; import org.eclipse.kapua.app.console.module.api.server.KapuaRemoteServiceServlet; import org.eclipse.kapua.app.console.module.api.server.util.KapuaExceptionHandler; @@ -35,30 +36,27 @@ import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.job.Job; import org.eclipse.kapua.service.job.JobCreator; -import org.eclipse.kapua.service.job.JobFactory; import org.eclipse.kapua.service.job.JobListResult; import org.eclipse.kapua.service.job.JobQuery; import org.eclipse.kapua.service.job.JobService; import org.eclipse.kapua.service.user.User; -import org.eclipse.kapua.service.user.UserFactory; import org.eclipse.kapua.service.user.UserListResult; +import org.eclipse.kapua.service.user.UserQuery; import org.eclipse.kapua.service.user.UserService; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.Callable; +import com.extjs.gxt.ui.client.data.BaseListLoadResult; +import com.extjs.gxt.ui.client.data.BasePagingLoadResult; +import com.extjs.gxt.ui.client.data.ListLoadResult; +import com.extjs.gxt.ui.client.data.PagingLoadConfig; +import com.extjs.gxt.ui.client.data.PagingLoadResult; public class GwtJobServiceImpl extends KapuaRemoteServiceServlet implements GwtJobService { private static final KapuaLocator LOCATOR = KapuaLocator.getInstance(); private static final JobService JOB_SERVICE = LOCATOR.getService(JobService.class); - private static final JobFactory JOB_FACTORY = LOCATOR.getFactory(JobFactory.class); private static final UserService USER_SERVICE = LOCATOR.getService(UserService.class); - private static final UserFactory USER_FACTORY = LOCATOR.getFactory(UserFactory.class); private static final String ENTITY_INFO = "entityInfo"; @@ -83,7 +81,7 @@ public PagingLoadResult query(PagingLoadConfig loadConfig, GwtJobQuery g @Override public UserListResult call() throws Exception { - return USER_SERVICE.query(USER_FACTORY.newQuery(null)); + return USER_SERVICE.query(new UserQuery(null)); } }); @@ -114,7 +112,7 @@ public GwtJob create(GwtXSRFToken xsrfToken, GwtJobCreator gwtJobCreator) throws GwtJob gwtJob = null; try { KapuaId scopeId = KapuaEid.parseCompactId(gwtJobCreator.getScopeId()); - JobCreator jobCreator = JOB_FACTORY.newCreator(scopeId); + JobCreator jobCreator = new JobCreator(scopeId); jobCreator.setName(gwtJobCreator.getName()); jobCreator.setDescription(gwtJobCreator.getDescription()); // Create the Job @@ -207,7 +205,7 @@ public void deleteForced(GwtXSRFToken xsrfToken, String gwtScopeId, String gwtJo @Override public ListLoadResult findJobDescription(String gwtScopeId, - String gwtJobId) throws GwtKapuaException { + String gwtJobId) throws GwtKapuaException { List gwtJobDescription = new ArrayList(); try { KapuaId scopeId = KapuaEid.parseCompactId(gwtScopeId); @@ -219,7 +217,7 @@ public ListLoadResult findJobDescription(String gwtScopeId, @Override public UserListResult call() throws Exception { - return USER_SERVICE.query(USER_FACTORY.newQuery(null)); + return USER_SERVICE.query(new UserQuery(null)); } }); diff --git a/console/module/job/src/main/java/org/eclipse/kapua/app/console/module/job/server/GwtJobStepDefinitionServiceImpl.java b/console/module/job/src/main/java/org/eclipse/kapua/app/console/module/job/server/GwtJobStepDefinitionServiceImpl.java index 6ed918244e2..12858ce4ea4 100644 --- a/console/module/job/src/main/java/org/eclipse/kapua/app/console/module/job/server/GwtJobStepDefinitionServiceImpl.java +++ b/console/module/job/src/main/java/org/eclipse/kapua/app/console/module/job/server/GwtJobStepDefinitionServiceImpl.java @@ -12,9 +12,9 @@ *******************************************************************************/ package org.eclipse.kapua.app.console.module.job.server; -import com.extjs.gxt.ui.client.data.BaseListLoadResult; -import com.extjs.gxt.ui.client.data.ListLoadResult; -import com.google.common.base.Strings; +import java.util.ArrayList; +import java.util.List; + import org.eclipse.kapua.app.console.module.api.client.GwtKapuaException; import org.eclipse.kapua.app.console.module.api.server.KapuaRemoteServiceServlet; import org.eclipse.kapua.app.console.module.api.server.util.KapuaExceptionHandler; @@ -29,19 +29,19 @@ import org.eclipse.kapua.locator.KapuaLocator; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.job.step.definition.JobStepDefinition; -import org.eclipse.kapua.service.job.step.definition.JobStepDefinitionFactory; import org.eclipse.kapua.service.job.step.definition.JobStepDefinitionListResult; +import org.eclipse.kapua.service.job.step.definition.JobStepDefinitionQuery; import org.eclipse.kapua.service.job.step.definition.JobStepDefinitionService; -import java.util.ArrayList; -import java.util.List; +import com.extjs.gxt.ui.client.data.BaseListLoadResult; +import com.extjs.gxt.ui.client.data.ListLoadResult; +import com.google.common.base.Strings; public class GwtJobStepDefinitionServiceImpl extends KapuaRemoteServiceServlet implements GwtJobStepDefinitionService { private static final KapuaLocator LOCATOR = KapuaLocator.getInstance(); private static final JobStepDefinitionService JOB_STEP_DEFINITION_SERVICE = LOCATOR.getService(JobStepDefinitionService.class); - private static final JobStepDefinitionFactory JOB_STEP_DEFINITION_FACTORY = LOCATOR.getFactory(JobStepDefinitionFactory.class); private static final ConsoleSetting CONSOLE_SETTING = ConsoleSetting.getInstance(); @@ -54,7 +54,7 @@ public ListLoadResult findAll(String scopeIdString) throws try { KapuaId scopeId = GwtKapuaCommonsModelConverter.convertKapuaId(scopeIdString); - JobStepDefinitionListResult result = JOB_STEP_DEFINITION_SERVICE.query(JOB_STEP_DEFINITION_FACTORY.newQuery(scopeId)); + JobStepDefinitionListResult result = JOB_STEP_DEFINITION_SERVICE.query(new JobStepDefinitionQuery(scopeId)); for (JobStepDefinition jsd : result.getItems()) { if (!Strings.isNullOrEmpty(JOB_STEP_DEFINITION_EXCLUDE_REGEX) && jsd.getName().matches(JOB_STEP_DEFINITION_EXCLUDE_REGEX)) { @@ -100,8 +100,8 @@ public GwtJobStepProperty trickGwt() { } /** - * Set the {@link GwtJobStepProperty#isEnum()} property. - * This cannot be performed in *.shared.* packages (entity converters are in that package), since `Class.forName` is not present in the JRE Emulation library. + * Set the {@link GwtJobStepProperty#isEnum()} property. This cannot be performed in *.shared.* packages (entity converters are in that package), since `Class.forName` is not present in the JRE + * Emulation library. * * @param jobStepProperties * @throws ClassNotFoundException diff --git a/console/module/job/src/main/java/org/eclipse/kapua/app/console/module/job/server/GwtJobStepServiceImpl.java b/console/module/job/src/main/java/org/eclipse/kapua/app/console/module/job/server/GwtJobStepServiceImpl.java index adfc96ed4be..695197aa776 100644 --- a/console/module/job/src/main/java/org/eclipse/kapua/app/console/module/job/server/GwtJobStepServiceImpl.java +++ b/console/module/job/src/main/java/org/eclipse/kapua/app/console/module/job/server/GwtJobStepServiceImpl.java @@ -12,9 +12,9 @@ *******************************************************************************/ package org.eclipse.kapua.app.console.module.job.server; -import com.extjs.gxt.ui.client.data.BasePagingLoadResult; -import com.extjs.gxt.ui.client.data.PagingLoadConfig; -import com.extjs.gxt.ui.client.data.PagingLoadResult; +import java.util.ArrayList; +import java.util.List; + import org.eclipse.kapua.app.console.module.api.client.GwtKapuaException; import org.eclipse.kapua.app.console.module.api.server.KapuaRemoteServiceServlet; import org.eclipse.kapua.app.console.module.api.server.util.KapuaExceptionHandler; @@ -30,25 +30,24 @@ import org.eclipse.kapua.commons.model.id.KapuaEid; import org.eclipse.kapua.locator.KapuaLocator; import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.service.job.step.JobStep; import org.eclipse.kapua.service.job.step.JobStepAttributes; import org.eclipse.kapua.service.job.step.JobStepCreator; -import org.eclipse.kapua.service.job.step.JobStepFactory; import org.eclipse.kapua.service.job.step.JobStepListResult; -import org.eclipse.kapua.service.job.step.JobStepQuery; import org.eclipse.kapua.service.job.step.JobStepService; import org.eclipse.kapua.service.job.step.definition.JobStepDefinition; import org.eclipse.kapua.service.job.step.definition.JobStepDefinitionService; -import java.util.ArrayList; -import java.util.List; +import com.extjs.gxt.ui.client.data.BasePagingLoadResult; +import com.extjs.gxt.ui.client.data.PagingLoadConfig; +import com.extjs.gxt.ui.client.data.PagingLoadResult; public class GwtJobStepServiceImpl extends KapuaRemoteServiceServlet implements GwtJobStepService { private static final KapuaLocator LOCATOR = KapuaLocator.getInstance(); private static final JobStepService JOB_STEP_SERVICE = LOCATOR.getService(JobStepService.class); - private static final JobStepFactory JOB_STEP_FACTORY = LOCATOR.getFactory(JobStepFactory.class); private static final JobStepDefinitionService JOB_STEP_DEFINITION_SERVICE = LOCATOR.getService(JobStepDefinitionService.class); private static final long serialVersionUID = 6248597422415080827L; @@ -60,7 +59,7 @@ public PagingLoadResult query(PagingLoadConfig loadConfig, GwtJobSte List gwtJobStepList = new ArrayList(); try { // Convert from GWT entity - JobStepQuery jobStepQuery = GwtKapuaJobModelConverter.convertJobStepQuery(gwtJobStepQuery, loadConfig); + KapuaQuery jobStepQuery = GwtKapuaJobModelConverter.convertJobStepQuery(gwtJobStepQuery, loadConfig); // query JobStepListResult jobStepList = JOB_STEP_SERVICE.query(jobStepQuery); @@ -94,7 +93,7 @@ public Integer count(String scopeIdString, String jobIdString) throws GwtKapuaEx KapuaId jobId = GwtKapuaCommonsModelConverter.convertKapuaId(jobIdString); // query - JobStepQuery jobStepQuery = JOB_STEP_FACTORY.newQuery(scopeId); + KapuaQuery jobStepQuery = new KapuaQuery(scopeId); jobStepQuery.setPredicate(jobStepQuery.attributePredicate(JobStepAttributes.JOB_ID, jobId)); return new Long(JOB_STEP_SERVICE.count(jobStepQuery)).intValue(); @@ -223,8 +222,8 @@ public int getJobStepPropertyLengthMax() throws GwtKapuaException { } /** - * Set the {@link GwtJobStepProperty#isEnum()} property. - * This cannot be performed in *.shared.* packages (entity converters are in that package), since `Class.forName` is not present in the JRE Emulation library. + * Set the {@link GwtJobStepProperty#isEnum()} property. This cannot be performed in *.shared.* packages (entity converters are in that package), since `Class.forName` is not present in the JRE + * Emulation library. * * @param jobStepProperties * @throws ClassNotFoundException diff --git a/console/module/job/src/main/java/org/eclipse/kapua/app/console/module/job/server/GwtJobTargetServiceImpl.java b/console/module/job/src/main/java/org/eclipse/kapua/app/console/module/job/server/GwtJobTargetServiceImpl.java index 4936241711e..d8b2dfb80a9 100644 --- a/console/module/job/src/main/java/org/eclipse/kapua/app/console/module/job/server/GwtJobTargetServiceImpl.java +++ b/console/module/job/src/main/java/org/eclipse/kapua/app/console/module/job/server/GwtJobTargetServiceImpl.java @@ -12,9 +12,11 @@ *******************************************************************************/ package org.eclipse.kapua.app.console.module.job.server; -import com.extjs.gxt.ui.client.data.BasePagingLoadResult; -import com.extjs.gxt.ui.client.data.PagingLoadConfig; -import com.extjs.gxt.ui.client.data.PagingLoadResult; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + import org.eclipse.kapua.KapuaErrorCodes; import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.app.console.module.api.client.GwtKapuaException; @@ -31,23 +33,20 @@ import org.eclipse.kapua.commons.model.id.KapuaEid; import org.eclipse.kapua.locator.KapuaLocator; import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.service.device.registry.Device; import org.eclipse.kapua.service.device.registry.DeviceAttributes; -import org.eclipse.kapua.service.device.registry.DeviceFactory; import org.eclipse.kapua.service.device.registry.DeviceListResult; import org.eclipse.kapua.service.device.registry.DeviceQuery; import org.eclipse.kapua.service.device.registry.DeviceRegistryService; import org.eclipse.kapua.service.job.targets.JobTarget; import org.eclipse.kapua.service.job.targets.JobTargetCreator; -import org.eclipse.kapua.service.job.targets.JobTargetFactory; import org.eclipse.kapua.service.job.targets.JobTargetListResult; -import org.eclipse.kapua.service.job.targets.JobTargetQuery; import org.eclipse.kapua.service.job.targets.JobTargetService; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import com.extjs.gxt.ui.client.data.BasePagingLoadResult; +import com.extjs.gxt.ui.client.data.PagingLoadConfig; +import com.extjs.gxt.ui.client.data.PagingLoadResult; public class GwtJobTargetServiceImpl extends KapuaRemoteServiceServlet implements GwtJobTargetService { @@ -58,10 +57,8 @@ public class GwtJobTargetServiceImpl extends KapuaRemoteServiceServlet implement private static final KapuaLocator LOCATOR = KapuaLocator.getInstance(); private static final JobTargetService JOB_TARGET_SERVICE = LOCATOR.getService(JobTargetService.class); - private static final JobTargetFactory JOB_TARGET_FACTORY = LOCATOR.getFactory(JobTargetFactory.class); private static final DeviceRegistryService DEVICE_REGISTRY_SERVICE = LOCATOR.getService(DeviceRegistryService.class); - private static final DeviceFactory DEVICE_FACTORY = LOCATOR.getFactory(DeviceFactory.class); @Override public PagingLoadResult query(PagingLoadConfig loadConfig, GwtJobTargetQuery gwtJobTargetQuery) throws GwtKapuaException { @@ -70,7 +67,7 @@ public PagingLoadResult query(PagingLoadConfig loadConfig, GwtJobT List gwtJobTargetList = new ArrayList(); try { // Convert from GWT entity - JobTargetQuery jobTargetQuery = GwtKapuaJobModelConverter.convertJobTargetQuery(gwtJobTargetQuery, loadConfig); + KapuaQuery jobTargetQuery = GwtKapuaJobModelConverter.convertJobTargetQuery(gwtJobTargetQuery, loadConfig); // query JobTargetListResult jobTargetList = JOB_TARGET_SERVICE.query(jobTargetQuery); @@ -83,7 +80,7 @@ public PagingLoadResult query(PagingLoadConfig loadConfig, GwtJobT //TODO: #LAYER_VIOLATION - manual device lookup - DeviceQuery query = DEVICE_FACTORY.newQuery(jobTargetQuery.getScopeId()); + DeviceQuery query = new DeviceQuery(jobTargetQuery.getScopeId()); query.setPredicate(query.attributePredicate(DeviceAttributes.ENTITY_ID, deviceIds)); DeviceListResult deviceListResult = DEVICE_REGISTRY_SERVICE.query(query); @@ -146,7 +143,7 @@ public List create(GwtXSRFToken xsrfToken, String scopeId, String devices.add(device); } KapuaId creatorScopeId = KapuaEid.parseCompactId(gwtJobTargetCreator.getScopeId()); - JobTargetCreator jobTargetCreator = JOB_TARGET_FACTORY.newCreator(creatorScopeId); + JobTargetCreator jobTargetCreator = new JobTargetCreator(creatorScopeId); jobTargetCreator.setJobId(GwtKapuaCommonsModelConverter.convertKapuaId(gwtJobTargetCreator.getJobId())); jobTargetCreator.setJobTargetId(GwtKapuaCommonsModelConverter.convertKapuaId(gwtJobTargetCreator.getJobTargetId())); @@ -192,8 +189,10 @@ public void delete(GwtXSRFToken xsrfToken, String gwtScopeId, String gwtJobTarge /** * For each item query clientId by its foreign key and insert it into existing list. * - * @param gwtJobTarget existing target that is updated - * @param device existing device + * @param gwtJobTarget + * existing target that is updated + * @param device + * existing device * @throws KapuaException */ private void insertClientId(GwtJobTarget gwtJobTarget, Device device) { diff --git a/console/module/job/src/main/java/org/eclipse/kapua/app/console/module/job/server/GwtTriggerDefinitionServiceImpl.java b/console/module/job/src/main/java/org/eclipse/kapua/app/console/module/job/server/GwtTriggerDefinitionServiceImpl.java index f91e4c39114..6ad32e95d99 100644 --- a/console/module/job/src/main/java/org/eclipse/kapua/app/console/module/job/server/GwtTriggerDefinitionServiceImpl.java +++ b/console/module/job/src/main/java/org/eclipse/kapua/app/console/module/job/server/GwtTriggerDefinitionServiceImpl.java @@ -12,8 +12,9 @@ *******************************************************************************/ package org.eclipse.kapua.app.console.module.job.server; -import com.extjs.gxt.ui.client.data.BaseListLoadResult; -import com.extjs.gxt.ui.client.data.ListLoadResult; +import java.util.ArrayList; +import java.util.List; + import org.eclipse.kapua.app.console.module.api.client.GwtKapuaException; import org.eclipse.kapua.app.console.module.api.server.KapuaRemoteServiceServlet; import org.eclipse.kapua.app.console.module.api.server.util.KapuaExceptionHandler; @@ -24,26 +25,25 @@ import org.eclipse.kapua.commons.model.id.KapuaEid; import org.eclipse.kapua.locator.KapuaLocator; import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.service.scheduler.trigger.definition.TriggerDefinition; -import org.eclipse.kapua.service.scheduler.trigger.definition.TriggerDefinitionFactory; import org.eclipse.kapua.service.scheduler.trigger.definition.TriggerDefinitionListResult; import org.eclipse.kapua.service.scheduler.trigger.definition.TriggerDefinitionService; -import java.util.ArrayList; -import java.util.List; +import com.extjs.gxt.ui.client.data.BaseListLoadResult; +import com.extjs.gxt.ui.client.data.ListLoadResult; public class GwtTriggerDefinitionServiceImpl extends KapuaRemoteServiceServlet implements GwtTriggerDefinitionService { private static final KapuaLocator LOCATOR = KapuaLocator.getInstance(); private static final TriggerDefinitionService TRIGGER_DEFINITION_SERVICE = LOCATOR.getService(TriggerDefinitionService.class); - private static final TriggerDefinitionFactory TRIGGER_DEFINITION_FACTORY = LOCATOR.getFactory(TriggerDefinitionFactory.class); @Override public ListLoadResult findAll() throws GwtKapuaException { List gwtTriggerDefinitionList = new ArrayList(); try { - TriggerDefinitionListResult result = TRIGGER_DEFINITION_SERVICE.query(TRIGGER_DEFINITION_FACTORY.newQuery(null)); + TriggerDefinitionListResult result = TRIGGER_DEFINITION_SERVICE.query(new KapuaQuery((KapuaId) null)); for (TriggerDefinition jsd : result.getItems()) { GwtTriggerDefinition gwtTriggerDefinition = KapuaGwtJobModelConverter.convertTriggerDefinition(jsd); @@ -84,8 +84,8 @@ public GwtTriggerProperty trickGwt() { } /** - * Set the {@link GwtTriggerProperty#isEnum()} property. - * This cannot be performed in *.shared.* packages (entity converters are in that package), since `Class.forName` is not present in the JRE Emulation library. + * Set the {@link GwtTriggerProperty#isEnum()} property. This cannot be performed in *.shared.* packages (entity converters are in that package), since `Class.forName` is not present in the JRE + * Emulation library. * * @param triggerProperties * @throws ClassNotFoundException diff --git a/console/module/job/src/main/java/org/eclipse/kapua/app/console/module/job/server/GwtTriggerServiceImpl.java b/console/module/job/src/main/java/org/eclipse/kapua/app/console/module/job/server/GwtTriggerServiceImpl.java index 9a58ca82bdb..885812a9ae7 100644 --- a/console/module/job/src/main/java/org/eclipse/kapua/app/console/module/job/server/GwtTriggerServiceImpl.java +++ b/console/module/job/src/main/java/org/eclipse/kapua/app/console/module/job/server/GwtTriggerServiceImpl.java @@ -12,10 +12,11 @@ *******************************************************************************/ package org.eclipse.kapua.app.console.module.job.server; -import com.extjs.gxt.ui.client.data.BasePagingLoadResult; -import com.extjs.gxt.ui.client.data.PagingLoadConfig; -import com.extjs.gxt.ui.client.data.PagingLoadResult; -import com.google.common.base.Strings; +import java.text.ParseException; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.Callable; + import org.eclipse.kapua.app.console.module.api.client.GwtKapuaErrorCode; import org.eclipse.kapua.app.console.module.api.client.GwtKapuaException; import org.eclipse.kapua.app.console.module.api.server.KapuaRemoteServiceServlet; @@ -33,23 +34,22 @@ import org.eclipse.kapua.commons.security.KapuaSecurityUtils; import org.eclipse.kapua.locator.KapuaLocator; import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.service.scheduler.trigger.Trigger; import org.eclipse.kapua.service.scheduler.trigger.TriggerCreator; import org.eclipse.kapua.service.scheduler.trigger.TriggerFactory; import org.eclipse.kapua.service.scheduler.trigger.TriggerListResult; -import org.eclipse.kapua.service.scheduler.trigger.TriggerQuery; import org.eclipse.kapua.service.scheduler.trigger.TriggerService; import org.eclipse.kapua.service.scheduler.trigger.definition.TriggerDefinition; -import org.eclipse.kapua.service.scheduler.trigger.definition.TriggerDefinitionFactory; import org.eclipse.kapua.service.scheduler.trigger.definition.TriggerDefinitionListResult; import org.eclipse.kapua.service.scheduler.trigger.definition.TriggerDefinitionQuery; import org.eclipse.kapua.service.scheduler.trigger.definition.TriggerDefinitionService; import org.quartz.CronExpression; -import java.text.ParseException; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.Callable; +import com.extjs.gxt.ui.client.data.BasePagingLoadResult; +import com.extjs.gxt.ui.client.data.PagingLoadConfig; +import com.extjs.gxt.ui.client.data.PagingLoadResult; +import com.google.common.base.Strings; public class GwtTriggerServiceImpl extends KapuaRemoteServiceServlet implements GwtTriggerService { @@ -59,7 +59,6 @@ public class GwtTriggerServiceImpl extends KapuaRemoteServiceServlet implements private static final TriggerFactory TRIGGER_FACTORY = LOCATOR.getFactory(TriggerFactory.class); private static final TriggerDefinitionService TRIGGER_DEFINITION_SERVICE = LOCATOR.getService(TriggerDefinitionService.class); - private static final TriggerDefinitionFactory TRIGGER_DEFINITION_FACTORY = LOCATOR.getFactory(TriggerDefinitionFactory.class); private static final String TRIGGER_DEFINITION_INTERVAL_NAME = "Interval Job"; private static final TriggerDefinition TRIGGER_DEFINITION_INTERVAL; @@ -80,7 +79,7 @@ public class GwtTriggerServiceImpl extends KapuaRemoteServiceServlet implements @Override public TriggerDefinitionListResult call() throws Exception { - TriggerDefinitionQuery query = TRIGGER_DEFINITION_FACTORY.newQuery(null); + TriggerDefinitionQuery query = new TriggerDefinitionQuery((KapuaId) null); return TRIGGER_DEFINITION_SERVICE.query(query); } }); @@ -115,7 +114,7 @@ public PagingLoadResult findByJobId(PagingLoadConfig loadConfig, Str gwtTriggerQuery.setScopeId(gwtScopeId); gwtTriggerQuery.setJobId(gwtJobId); - TriggerQuery triggerQuery = GwtKapuaJobModelConverter.convertTriggerQuery(gwtTriggerQuery, loadConfig); + KapuaQuery triggerQuery = GwtKapuaJobModelConverter.convertTriggerQuery(gwtTriggerQuery, loadConfig); // query TriggerListResult triggerListResult = TRIGGER_SERVICE.query(triggerQuery); @@ -151,7 +150,7 @@ public GwtTrigger create(GwtXSRFToken xsrfToken, GwtTriggerCreator gwtTriggerCre try { KapuaId scopeId = KapuaEid.parseCompactId(gwtTriggerCreator.getScopeId()); - TriggerCreator triggerCreator = TRIGGER_FACTORY.newCreator(scopeId); + TriggerCreator triggerCreator = new TriggerCreator(scopeId); triggerCreator.setName(gwtTriggerCreator.getTriggerName()); triggerCreator.setStartsOn(gwtTriggerCreator.getStartsOn()); triggerCreator.setEndsOn(gwtTriggerCreator.getEndsOn()); diff --git a/console/module/job/src/main/java/org/eclipse/kapua/app/console/module/job/servlet/JobTargetExporterCsv.java b/console/module/job/src/main/java/org/eclipse/kapua/app/console/module/job/servlet/JobTargetExporterCsv.java index 6e85f445454..1ca9c68a594 100644 --- a/console/module/job/src/main/java/org/eclipse/kapua/app/console/module/job/servlet/JobTargetExporterCsv.java +++ b/console/module/job/src/main/java/org/eclipse/kapua/app/console/module/job/servlet/JobTargetExporterCsv.java @@ -12,8 +12,6 @@ *******************************************************************************/ package org.eclipse.kapua.app.console.module.job.servlet; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.OutputStreamWriter; import java.net.URLEncoder; @@ -26,6 +24,10 @@ import java.util.List; import java.util.Map; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.lang3.CharEncoding; import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.locator.KapuaLocator; import org.eclipse.kapua.model.id.KapuaId; @@ -33,14 +35,12 @@ import org.eclipse.kapua.model.query.KapuaListResult; import org.eclipse.kapua.service.device.registry.Device; import org.eclipse.kapua.service.device.registry.DeviceAttributes; -import org.eclipse.kapua.service.device.registry.DeviceFactory; import org.eclipse.kapua.service.device.registry.DeviceListResult; import org.eclipse.kapua.service.device.registry.DeviceQuery; import org.eclipse.kapua.service.device.registry.DeviceRegistryService; import org.eclipse.kapua.service.job.targets.JobTarget; import com.opencsv.CSVWriter; -import org.apache.commons.lang3.CharEncoding; public class JobTargetExporterCsv extends JobTargetExporter { @@ -70,7 +70,7 @@ public void init(final String scopeId, String jobId) writer = new CSVWriter(outputWriter); List cols = new ArrayList(Arrays.asList(JOB_TARGET_PROPERTIES)); - writer.writeNext(cols.toArray(new String[]{ })); + writer.writeNext(cols.toArray(new String[] {})); } @Override @@ -80,8 +80,7 @@ public void append(KapuaListResult jobTargets) KapuaLocator locator = KapuaLocator.getInstance(); final KapuaIdFactory kapuaIdFactory = locator.getFactory(KapuaIdFactory.class); final DeviceRegistryService deviceRegistryService = locator.getService(DeviceRegistryService.class); - final DeviceFactory deviceFactory = locator.getFactory(DeviceFactory.class); - final DeviceQuery deviceQuery = deviceFactory.newQuery(kapuaIdFactory.newKapuaId(scopeId)); + final DeviceQuery deviceQuery = new DeviceQuery(kapuaIdFactory.newKapuaId(scopeId)); KapuaId[] targetIds = new KapuaId[jobTargets.getSize()]; int i = 0; diff --git a/console/module/job/src/main/java/org/eclipse/kapua/app/console/module/job/servlet/JobTargetExporterServlet.java b/console/module/job/src/main/java/org/eclipse/kapua/app/console/module/job/servlet/JobTargetExporterServlet.java index 3826c67c117..4663bd7f52d 100644 --- a/console/module/job/src/main/java/org/eclipse/kapua/app/console/module/job/servlet/JobTargetExporterServlet.java +++ b/console/module/job/src/main/java/org/eclipse/kapua/app/console/module/job/servlet/JobTargetExporterServlet.java @@ -12,26 +12,27 @@ *******************************************************************************/ package org.eclipse.kapua.app.console.module.job.servlet; +import java.io.IOException; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + import org.eclipse.kapua.KapuaEntityNotFoundException; import org.eclipse.kapua.KapuaIllegalAccessException; import org.eclipse.kapua.KapuaUnauthenticatedException; import org.eclipse.kapua.locator.KapuaLocator; import org.eclipse.kapua.model.id.KapuaIdFactory; import org.eclipse.kapua.model.query.KapuaListResult; +import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.service.job.targets.JobTarget; import org.eclipse.kapua.service.job.targets.JobTargetAttributes; -import org.eclipse.kapua.service.job.targets.JobTargetFactory; -import org.eclipse.kapua.service.job.targets.JobTargetQuery; +import org.eclipse.kapua.service.job.targets.JobTargetListResult; import org.eclipse.kapua.service.job.targets.JobTargetService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; - public class JobTargetExporterServlet extends HttpServlet { private static final long serialVersionUID = -2533869595709953567L; @@ -76,18 +77,17 @@ private void internalDoGet(HttpServletRequest request, HttpServletResponse respo KapuaLocator locator = KapuaLocator.getInstance(); KapuaIdFactory kapuaIdFactory = locator.getFactory(KapuaIdFactory.class); JobTargetService jobTargetService = locator.getService(JobTargetService.class); - JobTargetFactory jobTargetFactory = locator.getFactory(JobTargetFactory.class); jobTargetExporter.init(scopeId, jobId); int offset = 0; - JobTargetQuery jobTargetQuery = jobTargetFactory.newQuery(kapuaIdFactory.newKapuaId(scopeId)); + KapuaQuery jobTargetQuery = new KapuaQuery(kapuaIdFactory.newKapuaId(scopeId)); jobTargetQuery.setPredicate(jobTargetQuery.attributePredicate(JobTargetAttributes.JOB_ID, kapuaIdFactory.newKapuaId(jobId))); // paginate through the matching message jobTargetQuery.setLimit(250); - KapuaListResult totalJobTargets = jobTargetFactory.newListResult(); + KapuaListResult totalJobTargets = new JobTargetListResult(); KapuaListResult results; do { jobTargetQuery.setOffset(offset); diff --git a/console/module/job/src/main/java/org/eclipse/kapua/app/console/module/job/shared/util/GwtKapuaJobModelConverter.java b/console/module/job/src/main/java/org/eclipse/kapua/app/console/module/job/shared/util/GwtKapuaJobModelConverter.java index 70099ff1b88..0213c8d9707 100644 --- a/console/module/job/src/main/java/org/eclipse/kapua/app/console/module/job/shared/util/GwtKapuaJobModelConverter.java +++ b/console/module/job/src/main/java/org/eclipse/kapua/app/console/module/job/shared/util/GwtKapuaJobModelConverter.java @@ -12,8 +12,11 @@ *******************************************************************************/ package org.eclipse.kapua.app.console.module.job.shared.util; -import com.extjs.gxt.ui.client.Style.SortDir; -import com.extjs.gxt.ui.client.data.PagingLoadConfig; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + import org.apache.commons.lang3.StringUtils; import org.eclipse.kapua.app.console.module.api.shared.util.GwtKapuaCommonsModelConverter; import org.eclipse.kapua.app.console.module.job.shared.model.GwtJob; @@ -28,12 +31,11 @@ import org.eclipse.kapua.app.console.module.job.shared.model.GwtJobTargetQuery; import org.eclipse.kapua.app.console.module.job.shared.model.scheduler.GwtTriggerProperty; import org.eclipse.kapua.app.console.module.job.shared.model.scheduler.GwtTriggerQuery; -import org.eclipse.kapua.commons.model.query.FieldSortCriteriaImpl; -import org.eclipse.kapua.job.engine.JobEngineFactory; import org.eclipse.kapua.job.engine.JobStartOptions; import org.eclipse.kapua.locator.KapuaLocator; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.model.query.FieldSortCriteria; +import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.model.query.SortOrder; import org.eclipse.kapua.model.query.predicate.AndPredicate; import org.eclipse.kapua.model.query.predicate.AttributePredicate; @@ -43,40 +45,27 @@ import org.eclipse.kapua.service.job.JobFactory; import org.eclipse.kapua.service.job.JobQuery; import org.eclipse.kapua.service.job.execution.JobExecutionAttributes; -import org.eclipse.kapua.service.job.execution.JobExecutionFactory; import org.eclipse.kapua.service.job.execution.JobExecutionQuery; import org.eclipse.kapua.service.job.step.JobStep; import org.eclipse.kapua.service.job.step.JobStepAttributes; import org.eclipse.kapua.service.job.step.JobStepCreator; import org.eclipse.kapua.service.job.step.JobStepFactory; -import org.eclipse.kapua.service.job.step.JobStepQuery; -import org.eclipse.kapua.service.job.step.definition.JobStepDefinitionFactory; import org.eclipse.kapua.service.job.step.definition.JobStepDefinitionQuery; import org.eclipse.kapua.service.job.step.definition.JobStepProperty; import org.eclipse.kapua.service.job.targets.JobTargetAttributes; -import org.eclipse.kapua.service.job.targets.JobTargetFactory; -import org.eclipse.kapua.service.job.targets.JobTargetQuery; import org.eclipse.kapua.service.scheduler.trigger.TriggerAttributes; import org.eclipse.kapua.service.scheduler.trigger.TriggerFactory; -import org.eclipse.kapua.service.scheduler.trigger.TriggerQuery; import org.eclipse.kapua.service.scheduler.trigger.definition.TriggerProperty; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; +import com.extjs.gxt.ui.client.Style.SortDir; +import com.extjs.gxt.ui.client.data.PagingLoadConfig; public class GwtKapuaJobModelConverter { private static final KapuaLocator LOCATOR = KapuaLocator.getInstance(); - private static final JobExecutionFactory JOB_EXECUTION_FACTORY = LOCATOR.getFactory(JobExecutionFactory.class); private static final JobFactory JOB_FACTORY = LOCATOR.getFactory(JobFactory.class); private static final JobStepFactory JOB_STEP_FACTORY = LOCATOR.getFactory(JobStepFactory.class); - private static final JobStepDefinitionFactory JOB_STEP_DEFINITION_FACTORY = LOCATOR.getFactory(JobStepDefinitionFactory.class); - private static final JobTargetFactory JOB_TARGET_FACTORY = LOCATOR.getFactory(JobTargetFactory.class); - private static final JobEngineFactory JOB_ENGINE_FACTORY = LOCATOR.getFactory(JobEngineFactory.class); - private static final TriggerFactory TRIGGER_FACTORY = LOCATOR.getFactory(TriggerFactory.class); private GwtKapuaJobModelConverter() { @@ -128,7 +117,7 @@ public static List convertJobStepProperties(List kapuaPropertyNameAttributePredicate = query.attributePredicate(TriggerAttributes.TRIGGER_PROPERTIES_NAME, "jobId"); AttributePredicate kapuaPropertyValueAttributePredicate = query.attributePredicate(TriggerAttributes.TRIGGER_PROPERTIES_VALUE, gwtTriggerQuery.getJobId()); @@ -297,7 +286,7 @@ public static List convertTriggerProperties(List kapua-console org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-console-module diff --git a/console/module/tag/pom.xml b/console/module/tag/pom.xml index 9ae04b86e5f..c7d2b67d302 100644 --- a/console/module/tag/pom.xml +++ b/console/module/tag/pom.xml @@ -19,7 +19,7 @@ kapua-console-module org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-console-module-tag diff --git a/console/module/tag/src/main/java/org/eclipse/kapua/app/console/module/tag/server/GwtTagServiceImpl.java b/console/module/tag/src/main/java/org/eclipse/kapua/app/console/module/tag/server/GwtTagServiceImpl.java index ee8575c56a3..43c336b5517 100644 --- a/console/module/tag/src/main/java/org/eclipse/kapua/app/console/module/tag/server/GwtTagServiceImpl.java +++ b/console/module/tag/src/main/java/org/eclipse/kapua/app/console/module/tag/server/GwtTagServiceImpl.java @@ -12,11 +12,12 @@ *******************************************************************************/ package org.eclipse.kapua.app.console.module.tag.server; -import com.extjs.gxt.ui.client.data.BaseListLoadResult; -import com.extjs.gxt.ui.client.data.BasePagingLoadResult; -import com.extjs.gxt.ui.client.data.ListLoadResult; -import com.extjs.gxt.ui.client.data.PagingLoadConfig; -import com.extjs.gxt.ui.client.data.PagingLoadResult; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.Callable; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.app.console.module.api.client.GwtKapuaException; import org.eclipse.kapua.app.console.module.api.server.KapuaRemoteServiceServlet; @@ -38,20 +39,19 @@ import org.eclipse.kapua.service.device.registry.DeviceRegistryService; import org.eclipse.kapua.service.tag.Tag; import org.eclipse.kapua.service.tag.TagCreator; -import org.eclipse.kapua.service.tag.TagFactory; import org.eclipse.kapua.service.tag.TagListResult; import org.eclipse.kapua.service.tag.TagQuery; import org.eclipse.kapua.service.tag.TagService; import org.eclipse.kapua.service.user.User; -import org.eclipse.kapua.service.user.UserFactory; import org.eclipse.kapua.service.user.UserListResult; +import org.eclipse.kapua.service.user.UserQuery; import org.eclipse.kapua.service.user.UserService; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.Callable; +import com.extjs.gxt.ui.client.data.BaseListLoadResult; +import com.extjs.gxt.ui.client.data.BasePagingLoadResult; +import com.extjs.gxt.ui.client.data.ListLoadResult; +import com.extjs.gxt.ui.client.data.PagingLoadConfig; +import com.extjs.gxt.ui.client.data.PagingLoadResult; public class GwtTagServiceImpl extends KapuaRemoteServiceServlet implements GwtTagService { @@ -62,10 +62,8 @@ public class GwtTagServiceImpl extends KapuaRemoteServiceServlet implements GwtT DeviceRegistryService deviceRegistryService = locator.getService(DeviceRegistryService.class); TagService tagService = locator.getService(TagService.class); - TagFactory tagFactory = locator.getFactory(TagFactory.class); final UserService userService = locator.getService(UserService.class); - final UserFactory userFactory = locator.getFactory(UserFactory.class); private static final String ENTITY_INFO = "entityInfo"; @@ -74,7 +72,7 @@ public GwtTag create(GwtTagCreator gwtTagCreator) throws GwtKapuaException { GwtTag gwtTag = null; try { KapuaId scopeId = KapuaEid.parseCompactId(gwtTagCreator.getScopeId()); - TagCreator tagCreator = tagFactory.newCreator(scopeId, gwtTagCreator.getName()); + TagCreator tagCreator = new TagCreator(scopeId, gwtTagCreator.getName()); tagCreator.setDescription(gwtTagCreator.getDescription()); Tag tag = tagService.create(tagCreator); @@ -141,7 +139,7 @@ public PagingLoadResult query(PagingLoadConfig loadConfig, final GwtTagQ @Override public UserListResult call() throws Exception { - return userService.query(userFactory.newQuery(null)); + return userService.query(new UserQuery(null)); } }); @@ -186,12 +184,12 @@ public ListLoadResult getTagDescription(String scopeShortId, S final Tag tag = tagService.find(scopeId, tagId); if (tag != null) { -//TODO: #LAYER_VIOLATION - user lookup logic should not be done here (fetching all users is incredibly inefficient anyway) + //TODO: #LAYER_VIOLATION - user lookup logic should not be done here (fetching all users is incredibly inefficient anyway) UserListResult userListResult = KapuaSecurityUtils.doPrivileged(new Callable() { @Override public UserListResult call() throws Exception { - return userService.query(userFactory.newQuery(null)); + return userService.query(new UserQuery(null)); } }); @@ -220,7 +218,7 @@ public UserListResult call() throws Exception { public List findAll(String scopeId) throws GwtKapuaException { List tagList = new ArrayList(); try { - TagQuery query = tagFactory.newQuery(GwtKapuaCommonsModelConverter.convertKapuaId(scopeId)); + TagQuery query = new TagQuery(GwtKapuaCommonsModelConverter.convertKapuaId(scopeId)); TagListResult result = tagService.query(query); diff --git a/console/module/tag/src/main/java/org/eclipse/kapua/app/console/module/tag/shared/util/GwtKapuaTagModelConverter.java b/console/module/tag/src/main/java/org/eclipse/kapua/app/console/module/tag/shared/util/GwtKapuaTagModelConverter.java index c59cf43ed15..53e6e317c51 100644 --- a/console/module/tag/src/main/java/org/eclipse/kapua/app/console/module/tag/shared/util/GwtKapuaTagModelConverter.java +++ b/console/module/tag/src/main/java/org/eclipse/kapua/app/console/module/tag/shared/util/GwtKapuaTagModelConverter.java @@ -12,25 +12,21 @@ *******************************************************************************/ package org.eclipse.kapua.app.console.module.tag.shared.util; -import com.extjs.gxt.ui.client.Style.SortDir; -import com.extjs.gxt.ui.client.data.PagingLoadConfig; import org.apache.commons.lang3.StringUtils; import org.eclipse.kapua.app.console.module.api.shared.util.GwtKapuaCommonsModelConverter; import org.eclipse.kapua.app.console.module.tag.shared.model.GwtTagQuery; +import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.model.query.FieldSortCriteria; import org.eclipse.kapua.model.query.SortOrder; -import org.eclipse.kapua.locator.KapuaLocator; -import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.model.query.predicate.AndPredicate; import org.eclipse.kapua.model.query.predicate.AttributePredicate.Operator; import org.eclipse.kapua.service.tag.TagAttributes; -import org.eclipse.kapua.service.tag.TagFactory; import org.eclipse.kapua.service.tag.TagQuery; -public class GwtKapuaTagModelConverter { +import com.extjs.gxt.ui.client.Style.SortDir; +import com.extjs.gxt.ui.client.data.PagingLoadConfig; - private static final KapuaLocator LOCATOR = KapuaLocator.getInstance(); - private static final TagFactory TAG_FACTORY = LOCATOR.getFactory(TagFactory.class); +public class GwtKapuaTagModelConverter { private GwtKapuaTagModelConverter() { } @@ -38,13 +34,15 @@ private GwtKapuaTagModelConverter() { /** * Converts a {@link GwtTagQuery} into a {@link TagQuery} object for backend usage * - * @param loadConfig the load configuration - * @param gwtTagQuery the {@link GwtTagQuery} to convertKapuaId + * @param loadConfig + * the load configuration + * @param gwtTagQuery + * the {@link GwtTagQuery} to convertKapuaId * @return the converted {@link TagQuery} */ public static TagQuery convertTagQuery(PagingLoadConfig loadConfig, GwtTagQuery gwtTagQuery) { - TagQuery query = TAG_FACTORY.newQuery(GwtKapuaCommonsModelConverter.convertKapuaId(gwtTagQuery.getScopeId())); + TagQuery query = new TagQuery(GwtKapuaCommonsModelConverter.convertKapuaId(gwtTagQuery.getScopeId())); // Predicates conversion AndPredicate andPredicate = query.andPredicate(); diff --git a/console/module/user/pom.xml b/console/module/user/pom.xml index 376b13040f7..ce826542da0 100644 --- a/console/module/user/pom.xml +++ b/console/module/user/pom.xml @@ -19,7 +19,7 @@ kapua-console-module org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-console-module-user diff --git a/console/module/user/src/main/java/org/eclipse/kapua/app/console/module/user/client/dialog/UserDeleteDialog.java b/console/module/user/src/main/java/org/eclipse/kapua/app/console/module/user/client/dialog/UserDeleteDialog.java index baa7910a2af..28232300e2e 100644 --- a/console/module/user/src/main/java/org/eclipse/kapua/app/console/module/user/client/dialog/UserDeleteDialog.java +++ b/console/module/user/src/main/java/org/eclipse/kapua/app/console/module/user/client/dialog/UserDeleteDialog.java @@ -16,18 +16,17 @@ import org.eclipse.kapua.app.console.module.api.client.util.DialogUtils; import org.eclipse.kapua.app.console.module.user.client.messages.ConsoleUserMessages; import org.eclipse.kapua.app.console.module.user.shared.model.GwtUser; +import org.eclipse.kapua.app.console.module.user.shared.service.GwtUserService; +import org.eclipse.kapua.app.console.module.user.shared.service.GwtUserServiceAsync; import com.google.gwt.core.client.GWT; import com.google.gwt.user.client.rpc.AsyncCallback; -import org.eclipse.kapua.app.console.module.user.shared.service.GwtUserService; -import org.eclipse.kapua.app.console.module.user.shared.service.GwtUserServiceAsync; public class UserDeleteDialog extends EntityDeleteDialog { private static final ConsoleUserMessages MSGS = GWT.create(ConsoleUserMessages.class); private static final GwtUserServiceAsync GWT_USER_SERVICE = GWT.create(GwtUserService.class); - private GwtUser gwtUser; public UserDeleteDialog(GwtUser gwtUser) { diff --git a/console/module/user/src/main/java/org/eclipse/kapua/app/console/module/user/server/GwtUserServiceImpl.java b/console/module/user/src/main/java/org/eclipse/kapua/app/console/module/user/server/GwtUserServiceImpl.java index 382c328ec8f..48c17d9725d 100644 --- a/console/module/user/src/main/java/org/eclipse/kapua/app/console/module/user/server/GwtUserServiceImpl.java +++ b/console/module/user/src/main/java/org/eclipse/kapua/app/console/module/user/server/GwtUserServiceImpl.java @@ -12,11 +12,12 @@ *******************************************************************************/ package org.eclipse.kapua.app.console.module.user.server; -import com.extjs.gxt.ui.client.data.BaseListLoadResult; -import com.extjs.gxt.ui.client.data.BasePagingLoadResult; -import com.extjs.gxt.ui.client.data.ListLoadResult; -import com.extjs.gxt.ui.client.data.PagingLoadConfig; -import com.extjs.gxt.ui.client.data.PagingLoadResult; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.Callable; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.app.console.module.api.client.GwtKapuaException; import org.eclipse.kapua.app.console.module.api.server.KapuaRemoteServiceServlet; @@ -38,14 +39,12 @@ import org.eclipse.kapua.model.domain.Actions; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.authentication.credential.CredentialCreator; -import org.eclipse.kapua.service.authentication.credential.CredentialFactory; import org.eclipse.kapua.service.authentication.credential.CredentialService; import org.eclipse.kapua.service.authentication.credential.CredentialStatus; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; +import org.eclipse.kapua.service.authorization.permission.Permission; import org.eclipse.kapua.service.authorization.role.RoleService; import org.eclipse.kapua.service.device.registry.Device; -import org.eclipse.kapua.service.device.registry.DeviceFactory; import org.eclipse.kapua.service.device.registry.DeviceListResult; import org.eclipse.kapua.service.device.registry.DeviceQuery; import org.eclipse.kapua.service.device.registry.DeviceRegistryService; @@ -53,17 +52,16 @@ import org.eclipse.kapua.service.device.registry.connection.DeviceConnectionService; import org.eclipse.kapua.service.user.User; import org.eclipse.kapua.service.user.UserCreator; -import org.eclipse.kapua.service.user.UserFactory; import org.eclipse.kapua.service.user.UserListResult; import org.eclipse.kapua.service.user.UserQuery; import org.eclipse.kapua.service.user.UserService; import org.eclipse.kapua.service.user.UserType; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.Callable; +import com.extjs.gxt.ui.client.data.BaseListLoadResult; +import com.extjs.gxt.ui.client.data.BasePagingLoadResult; +import com.extjs.gxt.ui.client.data.ListLoadResult; +import com.extjs.gxt.ui.client.data.PagingLoadConfig; +import com.extjs.gxt.ui.client.data.PagingLoadResult; /** * The server side implementation of the RPC service. @@ -76,18 +74,13 @@ public class GwtUserServiceImpl extends KapuaRemoteServiceServlet implements Gwt private static final RoleService ROLE_SERVICE = LOCATOR.getService(RoleService.class); private static final CredentialService CREDENTIAL_SERVICE = LOCATOR.getService(CredentialService.class); - private static final CredentialFactory CREDENTIAL_FACTORY = LOCATOR.getFactory(CredentialFactory.class); private static final UserService USER_SERVICE = LOCATOR.getService(UserService.class); - private static final UserFactory USER_FACTORY = LOCATOR.getFactory(UserFactory.class); - private static final DeviceConnectionService DEVICE_CONNECTION_SERVICE = LOCATOR.getService(DeviceConnectionService.class); private static final AuthorizationService AUTHORIZATION_SERVICE = LOCATOR.getService(AuthorizationService.class); - private static final PermissionFactory PERMISSION_FACTORY = LOCATOR.getFactory(PermissionFactory.class); private static final DeviceRegistryService DEVICE_SERVICE = LOCATOR.getService(DeviceRegistryService.class); - private static final DeviceFactory DEVICE_FACTORY = LOCATOR.getFactory(DeviceFactory.class); private static final String USER_INFO = "userInfo"; private static final String ENTITY_INFO = "entityInfo"; @@ -100,7 +93,7 @@ public GwtUser create(GwtXSRFToken xsrfToken, GwtUserCreator gwtUserCreator) thr try { KapuaId scopeId = KapuaEid.parseCompactId(gwtUserCreator.getScopeId()); - UserCreator userCreator = USER_FACTORY.newCreator(scopeId, gwtUserCreator.getUsername()); + UserCreator userCreator = new UserCreator(scopeId, gwtUserCreator.getUsername()); userCreator.setUserType(GwtKapuaUserModelConverter.convertUserType(gwtUserCreator.getUserType())); userCreator.setDisplayName(gwtUserCreator.getDisplayName()); userCreator.setEmail(gwtUserCreator.getEmail()); @@ -115,7 +108,7 @@ public GwtUser create(GwtXSRFToken xsrfToken, GwtUserCreator gwtUserCreator) thr if (UserType.INTERNAL.equals(user.getUserType()) && gwtUserCreator.getPassword() != null) { - CredentialCreator credentialCreator = CREDENTIAL_FACTORY.newCreator(scopeId, + CredentialCreator credentialCreator = new CredentialCreator(scopeId, user.getId(), "PASSWORD", gwtUserCreator.getPassword(), @@ -210,7 +203,7 @@ public ListLoadResult findAll(String scopeIdString) KapuaId scopeId = KapuaEid.parseCompactId(scopeIdString); List gwtUserList = new ArrayList(); try { - UserQuery query = USER_FACTORY.newQuery(scopeId); + UserQuery query = new UserQuery(scopeId); UserListResult list = USER_SERVICE.query(query); for (User user : list.getItems()) { @@ -244,7 +237,7 @@ public PagingLoadResult query(PagingLoadConfig loadConfig, GwtUserQuery @Override public UserListResult call() throws Exception { - return USER_SERVICE.query(USER_FACTORY.newQuery(null)); + return USER_SERVICE.query(new UserQuery(null)); } }); @@ -271,7 +264,7 @@ public UserListResult call() throws Exception { @Override public ListLoadResult getUserDescription(boolean isSsoEnabled, String shortScopeId, - String shortUserId) throws GwtKapuaException { + String shortUserId) throws GwtKapuaException { List gwtUserDescription = new ArrayList(); try { final KapuaId scopeId = KapuaEid.parseCompactId(shortScopeId); @@ -286,7 +279,7 @@ public ListLoadResult getUserDescription(boolean isSsoEnabled, @Override public UserListResult call() throws Exception { - return USER_SERVICE.query(USER_FACTORY.newQuery(null)); + return USER_SERVICE.query(new UserQuery(null)); } }); @@ -296,7 +289,7 @@ public UserListResult call() throws Exception { } DeviceConnection deviceConnection = null; - if (deviceListQuery(scopeId) != null && AUTHORIZATION_SERVICE.isPermitted(PERMISSION_FACTORY.newPermission(Domains.DEVICE_CONNECTION, Actions.read, scopeId))) { + if (deviceListQuery(scopeId) != null && AUTHORIZATION_SERVICE.isPermitted(new Permission(Domains.DEVICE_CONNECTION, Actions.read, scopeId))) { for (Device device : deviceListQuery(scopeId).getItems()) { if (device.getConnectionId() != null) { deviceConnection = DEVICE_CONNECTION_SERVICE.find(scopeId, device.getConnectionId()); @@ -337,7 +330,7 @@ public UserListResult call() throws Exception { @Override public PagingLoadResult getUsersForRole(PagingLoadConfig pagingLoadConfig, - GwtAccessRoleQuery query) throws GwtKapuaException { + GwtAccessRoleQuery query) throws GwtKapuaException { int totalLength = 0; List list = new ArrayList(); try { @@ -361,7 +354,7 @@ public PagingLoadResult getUsersForRole(PagingLoadConfig pagingLoadConf @Override public PagingLoadResult getUsersForAccount(PagingLoadConfig loadConfig, GwtUserQuery gwtUserQuery, - String accountId) throws GwtKapuaException { + String accountId) throws GwtKapuaException { int totalLength = 0; List gwtUsers = new ArrayList(); @@ -373,7 +366,7 @@ public PagingLoadResult getUsersForAccount(PagingLoadConfig loadConfig, if (!users.isEmpty()) { //TODO: #LAYER_VIOLATION - user lookup should not be done here (horribly inefficient) - final UserQuery allUsersQuery = USER_FACTORY.newQuery(GwtKapuaCommonsModelConverter.convertKapuaId(accountId)); + final UserQuery allUsersQuery = new UserQuery(GwtKapuaCommonsModelConverter.convertKapuaId(accountId)); UserListResult allUsers = KapuaSecurityUtils.doPrivileged(new Callable() { @Override @@ -406,8 +399,8 @@ public UserListResult call() throws Exception { */ private DeviceListResult deviceListQuery(KapuaId scopeId) throws KapuaException { DeviceListResult devicesList = null; - if (AUTHORIZATION_SERVICE.isPermitted(PERMISSION_FACTORY.newPermission(Domains.DEVICE, Actions.read, scopeId))) { - DeviceQuery deviceQuery = DEVICE_FACTORY.newQuery(scopeId); + if (AUTHORIZATION_SERVICE.isPermitted(new Permission(Domains.DEVICE, Actions.read, scopeId))) { + DeviceQuery deviceQuery = new DeviceQuery(scopeId); devicesList = DEVICE_SERVICE.query(deviceQuery); } return devicesList; diff --git a/console/module/user/src/main/java/org/eclipse/kapua/app/console/module/user/shared/util/GwtKapuaUserModelConverter.java b/console/module/user/src/main/java/org/eclipse/kapua/app/console/module/user/shared/util/GwtKapuaUserModelConverter.java index bc3f91dd60a..944ab1cdccc 100644 --- a/console/module/user/src/main/java/org/eclipse/kapua/app/console/module/user/shared/util/GwtKapuaUserModelConverter.java +++ b/console/module/user/src/main/java/org/eclipse/kapua/app/console/module/user/shared/util/GwtKapuaUserModelConverter.java @@ -12,26 +12,25 @@ *******************************************************************************/ package org.eclipse.kapua.app.console.module.user.shared.util; -import com.extjs.gxt.ui.client.Style.SortDir; -import com.extjs.gxt.ui.client.data.BaseModel; -import com.extjs.gxt.ui.client.data.PagingLoadConfig; import org.apache.commons.lang3.StringUtils; import org.eclipse.kapua.app.console.module.api.shared.util.GwtKapuaCommonsModelConverter; import org.eclipse.kapua.app.console.module.user.shared.model.GwtUser.GwtUserStatus; import org.eclipse.kapua.app.console.module.user.shared.model.GwtUser.GwtUserType; import org.eclipse.kapua.app.console.module.user.shared.model.GwtUserQuery; -import org.eclipse.kapua.locator.KapuaLocator; import org.eclipse.kapua.model.KapuaEntity; import org.eclipse.kapua.model.query.FieldSortCriteria; import org.eclipse.kapua.model.query.SortOrder; import org.eclipse.kapua.model.query.predicate.AndPredicate; import org.eclipse.kapua.model.query.predicate.AttributePredicate.Operator; import org.eclipse.kapua.service.user.UserAttributes; -import org.eclipse.kapua.service.user.UserFactory; import org.eclipse.kapua.service.user.UserQuery; import org.eclipse.kapua.service.user.UserStatus; import org.eclipse.kapua.service.user.UserType; +import com.extjs.gxt.ui.client.Style.SortDir; +import com.extjs.gxt.ui.client.data.BaseModel; +import com.extjs.gxt.ui.client.data.PagingLoadConfig; + /** * Utility class for convertKapuaId {@link BaseModel}s to {@link KapuaEntity}ies and other Kapua models */ @@ -43,17 +42,15 @@ private GwtKapuaUserModelConverter() { /** * Converts a {@link GwtUserQuery} into a {@link UserQuery} object for backend usage * - * @param loadConfig the load configuration - * @param gwtUserQuery the {@link GwtUserQuery} to convertKapuaId + * @param loadConfig + * the load configuration + * @param gwtUserQuery + * the {@link GwtUserQuery} to convertKapuaId * @return the converted {@link UserQuery} */ public static UserQuery convertUserQuery(PagingLoadConfig loadConfig, GwtUserQuery gwtUserQuery) { - // Get Services - KapuaLocator locator = KapuaLocator.getInstance(); - UserFactory userFactory = locator.getFactory(UserFactory.class); - - UserQuery query = userFactory.newQuery(GwtKapuaCommonsModelConverter.convertKapuaId(gwtUserQuery.getScopeId())); + UserQuery query = new UserQuery(GwtKapuaCommonsModelConverter.convertKapuaId(gwtUserQuery.getScopeId())); AndPredicate predicate = query.andPredicate(); if (gwtUserQuery.getName() != null && !gwtUserQuery.getName().isEmpty()) { diff --git a/console/module/welcome/pom.xml b/console/module/welcome/pom.xml index a00362d7cee..2783230fdc3 100644 --- a/console/module/welcome/pom.xml +++ b/console/module/welcome/pom.xml @@ -19,7 +19,7 @@ kapua-console-module org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-console-module-welcome diff --git a/console/pom.xml b/console/pom.xml index 725ef14caa4..0ab244b6a79 100644 --- a/console/pom.xml +++ b/console/pom.xml @@ -19,7 +19,7 @@ org.eclipse.kapua kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-console diff --git a/console/web/pom.xml b/console/web/pom.xml index 20bf64faf85..086c20431d4 100644 --- a/console/web/pom.xml +++ b/console/web/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-console - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-console-web diff --git a/console/web/src/main/java/org/eclipse/kapua/app/console/ConsoleJAXBContextProvider.java b/console/web/src/main/java/org/eclipse/kapua/app/console/ConsoleJAXBContextProvider.java index 507ec9735e3..5c2b1d48027 100644 --- a/console/web/src/main/java/org/eclipse/kapua/app/console/ConsoleJAXBContextProvider.java +++ b/console/web/src/main/java/org/eclipse/kapua/app/console/ConsoleJAXBContextProvider.java @@ -39,7 +39,6 @@ import org.eclipse.kapua.commons.service.event.store.api.EventStoreXmlRegistry; import org.eclipse.kapua.commons.util.xml.JAXBContextProvider; import org.eclipse.kapua.event.ServiceEvent; -import org.eclipse.kapua.job.engine.JobEngineXmlRegistry; import org.eclipse.kapua.job.engine.JobStartOptions; import org.eclipse.kapua.job.engine.commons.model.JobTargetSublist; import org.eclipse.kapua.model.config.metatype.KapuaTad; @@ -47,6 +46,7 @@ import org.eclipse.kapua.model.config.metatype.KapuaTmetadata; import org.eclipse.kapua.model.config.metatype.KapuaTocd; import org.eclipse.kapua.model.config.metatype.KapuaToption; +import org.eclipse.kapua.model.config.metatype.KapuaTscalar; import org.eclipse.kapua.service.device.call.kura.model.bundle.KuraBundle; import org.eclipse.kapua.service.device.call.kura.model.bundle.KuraBundles; import org.eclipse.kapua.service.device.call.kura.model.configuration.KuraDeviceComponentConfiguration; @@ -65,7 +65,6 @@ import org.eclipse.kapua.service.device.call.kura.model.inventory.system.KuraInventorySystemPackage; import org.eclipse.kapua.service.device.call.kura.model.inventory.system.KuraInventorySystemPackages; import org.eclipse.kapua.service.device.call.kura.model.snapshot.KuraSnapshotIds; -import org.eclipse.kapua.service.device.management.asset.DeviceAssetXmlRegistry; import org.eclipse.kapua.service.device.management.asset.DeviceAssets; import org.eclipse.kapua.service.device.management.bundle.DeviceBundle; import org.eclipse.kapua.service.device.management.bundle.DeviceBundles; @@ -79,7 +78,6 @@ import org.eclipse.kapua.service.device.management.inventory.model.container.DeviceInventoryContainers; import org.eclipse.kapua.service.device.management.inventory.model.inventory.DeviceInventory; import org.eclipse.kapua.service.device.management.inventory.model.inventory.DeviceInventoryItem; -import org.eclipse.kapua.service.device.management.inventory.model.inventory.DeviceInventoryXmlRegistry; import org.eclipse.kapua.service.device.management.inventory.model.packages.DeviceInventoryPackage; import org.eclipse.kapua.service.device.management.inventory.model.packages.DeviceInventoryPackages; import org.eclipse.kapua.service.device.management.inventory.model.system.DeviceInventorySystemPackage; @@ -92,7 +90,6 @@ import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystoreItemQuery; import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystoreItems; import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystoreKeypair; -import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystoreXmlRegistry; import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystores; import org.eclipse.kapua.service.device.management.packages.model.DevicePackages; import org.eclipse.kapua.service.device.management.packages.model.download.DevicePackageDownloadRequest; @@ -175,7 +172,6 @@ public JAXBContext getJAXBContext() throws KapuaException { DeviceInventorySystemPackage.class, KuraInventorySystemPackages.class, KuraInventorySystemPackage.class, - DeviceInventoryXmlRegistry.class, // Device Management Keystore DeviceKeystores.class, @@ -188,7 +184,6 @@ public JAXBContext getJAXBContext() throws KapuaException { DeviceKeystoreKeypair.class, DeviceKeystoreCSRInfo.class, DeviceKeystoreCSR.class, - DeviceKeystoreXmlRegistry.class, // Device Management Packages DevicePackageDownloadRequest.class, @@ -203,10 +198,10 @@ public JAXBContext getJAXBContext() throws KapuaException { KapuaTicon.class, KapuaToption.class, KapuaTmetadata.class, + KapuaTscalar.class, // Device Management Assets DeviceAssets.class, - DeviceAssetXmlRegistry.class, // Job JobTargetSublist.class, @@ -215,7 +210,6 @@ public JAXBContext getJAXBContext() throws KapuaException { JobListResult.class, JobQuery.class, JobXmlRegistry.class, - JobEngineXmlRegistry.class, // KapuaEvent ServiceEvent.class, diff --git a/consumer/lifecycle-app/pom.xml b/consumer/lifecycle-app/pom.xml index 017a07fbc0f..2a077a77c3b 100644 --- a/consumer/lifecycle-app/pom.xml +++ b/consumer/lifecycle-app/pom.xml @@ -19,7 +19,7 @@ kapua-consumer org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-consumer-lifecycle-app diff --git a/consumer/lifecycle/pom.xml b/consumer/lifecycle/pom.xml index 2696f202246..c03a5dbe5ec 100644 --- a/consumer/lifecycle/pom.xml +++ b/consumer/lifecycle/pom.xml @@ -17,7 +17,7 @@ org.eclipse.kapua kapua-consumer - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-consumer-lifecycle diff --git a/consumer/pom.xml b/consumer/pom.xml index c5b17142e42..c17ee8c9f98 100644 --- a/consumer/pom.xml +++ b/consumer/pom.xml @@ -19,7 +19,7 @@ org.eclipse.kapua kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT pom diff --git a/consumer/telemetry-app/pom.xml b/consumer/telemetry-app/pom.xml index c2c247e8dce..136d809960d 100644 --- a/consumer/telemetry-app/pom.xml +++ b/consumer/telemetry-app/pom.xml @@ -18,7 +18,7 @@ kapua-consumer org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT 4.0.0 diff --git a/consumer/telemetry/pom.xml b/consumer/telemetry/pom.xml index 657ff990e5f..791831f3d38 100644 --- a/consumer/telemetry/pom.xml +++ b/consumer/telemetry/pom.xml @@ -17,7 +17,7 @@ org.eclipse.kapua kapua-consumer - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-consumer-telemetry diff --git a/deployment/commons/pom.xml b/deployment/commons/pom.xml index 67625aa915c..f92d24ef75c 100644 --- a/deployment/commons/pom.xml +++ b/deployment/commons/pom.xml @@ -19,7 +19,7 @@ kapua-deployment org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-deployment-commons diff --git a/deployment/commons/sso/keycloak/build b/deployment/commons/sso/keycloak/build index f15941a1afa..a446049e80f 100755 --- a/deployment/commons/sso/keycloak/build +++ b/deployment/commons/sso/keycloak/build @@ -14,7 +14,7 @@ echo "Building Kapua Keycloak Docker image..." -docker build -f ./docker/Dockerfile -t kapua/kapua-keycloak:"${IMAGE_VERSION:=2.1.0-SNAPSHOT}" . || +docker build -f ./docker/Dockerfile -t kapua/kapua-keycloak:"${IMAGE_VERSION:=2.1.0-FALSE_EXTENSIONS-SNAPSHOT}" . || { echo "Building Kapua Keycloak docker image... ERROR!" exit 1 diff --git a/deployment/docker/pom.xml b/deployment/docker/pom.xml index 727f45592ec..ef41cb98c01 100644 --- a/deployment/docker/pom.xml +++ b/deployment/docker/pom.xml @@ -19,7 +19,7 @@ kapua-deployment org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-docker diff --git a/deployment/docker/unix/docker-common.sh b/deployment/docker/unix/docker-common.sh index 0b1adbbdc18..9c0309bdf99 100755 --- a/deployment/docker/unix/docker-common.sh +++ b/deployment/docker/unix/docker-common.sh @@ -15,7 +15,7 @@ SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" -export IMAGE_VERSION=${IMAGE_VERSION:=2.1.0-SNAPSHOT} +export IMAGE_VERSION=${IMAGE_VERSION:=2.1.0-FALSE_EXTENSIONS-SNAPSHOT} export CRYPTO_SECRET_KEY="${CRYPTO_SECRET_KEY:=dockerSecretKey!}" # Certificates diff --git a/deployment/minishift/minishift-importer.sh b/deployment/minishift/minishift-importer.sh index e2c1efce932..caaaab012fb 100755 --- a/deployment/minishift/minishift-importer.sh +++ b/deployment/minishift/minishift-importer.sh @@ -29,7 +29,7 @@ ERROR=0 DOCKER_ACCOUNT=${DOCKER_ACCOUNT:=kapua} -IMAGE_VERSION=${IMAGE_VERSION:=2.1.0-SNAPSHOT} +IMAGE_VERSION=${IMAGE_VERSION:=2.1.0-FALSE_EXTENSIONS-SNAPSHOT} SERVICES=("console" "api" "sql" "broker" "events-broker") TMP_DIR="/tmp/kapua-containers-$(date +%s)" diff --git a/deployment/minishift/minishift-pull-images.sh b/deployment/minishift/minishift-pull-images.sh index 0ec90b04794..dbf8400b1a8 100755 --- a/deployment/minishift/minishift-pull-images.sh +++ b/deployment/minishift/minishift-pull-images.sh @@ -17,7 +17,7 @@ # DOCKER_ACCOUNT=${DOCKER_ACCOUNT:=kapua} -IMAGE_VERSION=${IMAGE_VERSION:=2.1.0-SNAPSHOT} +IMAGE_VERSION=${IMAGE_VERSION:=2.1.0-FALSE_EXTENSIONS-SNAPSHOT} SERVICES=("console" "api" "sql" "broker" "events-broker") echo "Pulling Kapua images..." diff --git a/deployment/minishift/pom.xml b/deployment/minishift/pom.xml index ab0504435ba..2ff960a7d16 100644 --- a/deployment/minishift/pom.xml +++ b/deployment/minishift/pom.xml @@ -19,7 +19,7 @@ kapua-deployment org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-minishift diff --git a/deployment/minishift/sso/keycloak-importer b/deployment/minishift/sso/keycloak-importer index 463ed399591..a1bb1b941ec 100755 --- a/deployment/minishift/sso/keycloak-importer +++ b/deployment/minishift/sso/keycloak-importer @@ -14,7 +14,7 @@ ERROR=0 DOCKER_ACCOUNT=${DOCKER_ACCOUNT:=kapua} -IMAGE_VERSION=${IMAGE_VERSION:=2.1.0-SNAPSHOT} +IMAGE_VERSION=${IMAGE_VERSION:=2.1.0-FALSE_EXTENSIONS-SNAPSHOT} KEYCLOAK="keycloak" TMP_DIR="/tmp/keycloak-container-$(date +%s)" diff --git a/deployment/openshift/openshift-deploy.sh b/deployment/openshift/openshift-deploy.sh index 6ae5f7c2f66..5ab5ad698fe 100755 --- a/deployment/openshift/openshift-deploy.sh +++ b/deployment/openshift/openshift-deploy.sh @@ -19,7 +19,7 @@ SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" . ${SCRIPT_DIR}/openshift-common.sh : DOCKER_ACCOUNT=${DOCKER_ACCOUNT:=kapua} -: IMAGE_VERSION=${IMAGE_VERSION:=2.1.0-SNAPSHOT} +: IMAGE_VERSION=${IMAGE_VERSION:=2.1.0-FALSE_EXTENSIONS-SNAPSHOT} : JAVA_OPTS_EXTRA=${JAVA_OPTS_EXTRA:=''} ### Test if the project is already created ... fail otherwise diff --git a/deployment/openshift/pom.xml b/deployment/openshift/pom.xml index 2e9d18339e6..ba03fc61bd9 100644 --- a/deployment/openshift/pom.xml +++ b/deployment/openshift/pom.xml @@ -19,7 +19,7 @@ kapua-deployment org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT pom diff --git a/deployment/pom.xml b/deployment/pom.xml index 9c3a34f127a..dd7ffbb82f7 100644 --- a/deployment/pom.xml +++ b/deployment/pom.xml @@ -19,7 +19,7 @@ kapua org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-deployment diff --git a/dev-tools/cucumber-reports/pom.xml b/dev-tools/cucumber-reports/pom.xml index 02b70853212..87d6cd9627b 100644 --- a/dev-tools/cucumber-reports/pom.xml +++ b/dev-tools/cucumber-reports/pom.xml @@ -19,7 +19,7 @@ kapua-dev-tools org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-cucumber-reports diff --git a/dev-tools/pom.xml b/dev-tools/pom.xml index 2f6dd730dcb..17b5bc4c002 100644 --- a/dev-tools/pom.xml +++ b/dev-tools/pom.xml @@ -20,7 +20,7 @@ org.eclipse.kapua kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-dev-tools diff --git a/docs/developer-guide/en/running.md b/docs/developer-guide/en/running.md index 5b63055e2eb..bdd62384fb5 100644 --- a/docs/developer-guide/en/running.md +++ b/docs/developer-guide/en/running.md @@ -1,34 +1,44 @@ # Running -Kapua can be run in a few different ways. See the following chapters for more information about how to start and run -Kapua. Keep in mind that if you want to deploy a released version, not building anything, you can follow the [Kapua quick start guide](https://github.com/eclipse/kapua/blob/develop/README.md). +Kapua can be run in a few different ways. See the following chapters for more information +about how to start and run +Kapua. Keep in mind that if you want to deploy a released version, not building anything, +you can follow +the [Kapua quick start guide](https://github.com/eclipse/kapua/blob/develop/README.md). This section is focused on running your custom build. -{% hint style='info' %} Most of the following descriptions focus on a developer centric setup and not on a full blown +{% hint style='info' %} Most of the following descriptions focus on a developer centric +setup and not on a full blown production setup. {% endhint %} ## Docker containers -Before running Kapua on Docker, Make sure that you have built Kapua docker images locally, following the provided [building section](building.md). +Before running Kapua on Docker, Make sure that you have built Kapua docker images locally, +following the provided [building section](building.md). ### Requirements + Same as the ones showed in the [building section](building.md) plus -* Docker compose V2, starting from Kapua releases >= 1.6.12 (present in latest docker desktop versions) +* Docker compose V2, starting from Kapua releases >= 1.6.12 (present in latest docker + desktop versions) -If you previously set the IMAGE_VERSION environment variable to a released version, please now unset it. In this way, latest built Kapua docker images will be deployed. +If you previously set the IMAGE_VERSION environment variable to a released version, please +now unset it. In this way, latest built Kapua docker images will be deployed. Now, you can start Kapua by using Docker Compose. To do so, run kapua/deployment/docker/docker-deploy.sh -After Kapua has been started, you can navigate your browser to http://localhost:8080 and log in using the following +After Kapua has been started, you can navigate your browser to http://localhost:8080 and +log in using the following credentials: `kapua-sys` : `kapua-password` You can access the API using: http://localhost:8081 -**Note**: If you are using Docker on Windows the hostname will most likely not be `localhost` but the IP address of your +**Note**: If you are using Docker on Windows the hostname will most likely not be +`localhost` but the IP address of your docker instance. To stop Kapua, run @@ -37,53 +47,67 @@ To stop Kapua, run #### Advanced options -It's possible to deploy kapua with some advanced options that are exposed [in this document](deployment/docker/README.md) +It's possible to deploy kapua with some advanced options that are +exposed [in this document](deployment/docker/README.md) -If you are interested in having debugging/logging capabilities we recommend you to consult it. +If you are interested in having debugging/logging capabilities we recommend you to consult +it. ## OpenShift -OpenShift is a PaaS (Platform As A Service) platform based on Kubernetes. Kapua supports deployments -into [OpenShift Origin](https://www.openshift.org), which is an open source community project. Origin sources, can be +OpenShift is a PaaS (Platform As A Service) platform based on Kubernetes. Kapua supports +deployments +into [OpenShift Origin](https://www.openshift.org), which is an open source community +project. Origin sources, can be found [here](https://www.openshift.org/). We support Kapua on OpenShift Origin **1.4.1**. -Currently we support running OpenShift only on Linux OS. If you would like to run Kapua on Mac OS or on Windows for +Currently we support running OpenShift only on Linux OS. If you would like to run Kapua on +Mac OS or on Windows for development purposes, please install Linux -(for example Fedora 25) into a virtual machine (for example VirtualBox) and install OpenShift there. +(for example Fedora 25) into a virtual machine (for example VirtualBox) and install +OpenShift there. ### Starting OpenShift cluster -For running Kapua on an OpenShift you need to have OpenShift cluster installed and started in the first place. You can +For running Kapua on an OpenShift you need to have OpenShift cluster installed and started +in the first place. You can install it by yourself or rely on the script we provide: sudo kapua/deployment/openshift/openshift-start.sh -If you are running your OpenShift cluster for the first time, execute the following initialized script as well: +If you are running your OpenShift cluster for the first time, execute the following +initialized script as well: kapua/deployment/openshift/openshift-initialize.sh -Initialization script is responsible for logging you into a cluster and creating new OpenShift project for Kapua. +Initialization script is responsible for logging you into a cluster and creating new +OpenShift project for Kapua. -If your Openshift cluster is not on the localhost, set the `OPENSHIFT_HOST` environment variable. For example, something +If your Openshift cluster is not on the localhost, set the `OPENSHIFT_HOST` environment +variable. For example, something like export OPENSHIFT_HOST=192.168.64.2:8443 -If for some reasons, you cannot start your cluster, try to execute the startup script with option `DOCKERIZED=FALSE`: +If for some reasons, you cannot start your cluster, try to execute the startup script with +option `DOCKERIZED=FALSE`: sudo DOCKERIZED=FALSE kapua/deployment/openshift/openshift-start.sh -Option `DOCKERIZED=FALSE` tells startup script to use standard binary installation of OpenShift Origin instead of +Option `DOCKERIZED=FALSE` tells startup script to use standard binary installation of +OpenShift Origin instead of Docker-based `oc cluster up` command. ### Deploying Kapua into OpenShift cluster -Now when you have OpenShift cluster up, running and initialized, execute the following script: +Now when you have OpenShift cluster up, running and initialized, execute the following +script: cd kapua/deployment/openshift ./openshift-deploy.sh -Now open the following URL in your web browser - `http://localhost:8080`. And log-in into Kapua UI using default +Now open the following URL in your web browser - `http://localhost:8080`. And log-in into +Kapua UI using default credentials:
    @@ -93,8 +117,10 @@ credentials: ## Using Minishift -Minishift is a tool that helps you run OpenShift locally by running a single-node OpenShift cluster inside a VM. -Follow [this guide](https://docs.openshift.org/latest/minishift/getting-started/index.html) for installing and having +Minishift is a tool that helps you run OpenShift locally by running a single-node +OpenShift cluster inside a VM. +Follow [this guide](https://docs.openshift.org/latest/minishift/getting-started/index.html) +for installing and having Minishift up and running. Steps to run Kapua on Minishift are the following @@ -141,13 +167,17 @@ Steps to run Kapua on Minishift are the following ### External Node port for MQTT -The default setup uses port 31883 to export the MQTT over TCP port of the broker. This means that you can connect from +The default setup uses port 31883 to export the MQTT over TCP port of the broker. This +means that you can connect from outside of the OpenShift cluster to Kapua over port 31883 (instead of port 1883) to Kapua. -However it is only possible for one service to make use of this port. If you are planning to add a second Kapua -installation and still want to use the external node port, then you will need to choose a different, yet unsed, port. +However it is only possible for one service to make use of this port. If you are planning +to add a second Kapua +installation and still want to use the external node port, then you will need to choose a +different, yet unsed, port. -Also see: https://docs.openshift.com/container-platform/latest/dev_guide/getting_traffic_into_cluster.html +Also +see: https://docs.openshift.com/container-platform/latest/dev_guide/getting_traffic_into_cluster.html ### Adding metrics @@ -158,40 +188,53 @@ then you can also install Grafana for Hawkular to visualize your data: ### External access -In order to enable devices to access Kapua we need to allow external access to the broker's MQTT connector. In the +In order to enable devices to access Kapua we need to allow external access to the +broker's MQTT connector. In the default deployment there are two ways to achieve this. -First, the broker exposes MQTT over WebSocket transport. As WebSocket is based on HTTP we can define a router inside the -Openshift to get those device connections to the broker. For example, if your Openshift deployment is running at the -address `192.168.64.2`, you can connect the [Kura Simulator](../user-manual/simulator.md) like this +First, the broker exposes MQTT over WebSocket transport. As WebSocket is based on HTTP we +can define a router inside the +Openshift to get those device connections to the broker. For example, if your Openshift +deployment is running at the +address `192.168.64.2`, you can connect the [Kura Simulator](../user-manual/simulator.md) +like this java -jar target/kapua-simulator-kura-*-SNAPSHOT-app.jar --broker ws://kapua-broker:kapua-password@broker-eclipse-kapua.192.168.64.2.nip.io:80 -Not all MQTT clients have WebSocket support, so we need to enable direct MQTT over TCP access to the broker as well. By -default, Kapua comes with the NodePort service that routes all traffic from port `31883` to the broker. So you can -connect your MQTT clients directly to this service. For the simulator example similar to the above, that would look +Not all MQTT clients have WebSocket support, so we need to enable direct MQTT over TCP +access to the broker as well. By +default, Kapua comes with the NodePort service that routes all traffic from port `31883` +to the broker. So you can +connect your MQTT clients directly to this service. For the simulator example similar to +the above, that would look something like - java -jar target/kapua-simulator-kura-2.1.0-SNAPSHOT-app.jar --broker tcp://kapua-broker:kapua-password@192.168.64.2:31883 + java -jar target/kapua-simulator-kura-2.1.0-FALSE_EXTENSIONS-SNAPSHOT-app.jar --broker tcp://kapua-broker:kapua-password@192.168.64.2:31883 -This is suitable only for the local deployments. In the cloud or production environments, you should deploy a proper +This is suitable only for the local deployments. In the cloud or production environments, +you should deploy a proper LoadBalancer Openshift service to enable external traffic flow to the broker. ### Ensuring enough entropy -It may happen that firing up docker containers and starting up application which use Java's `SecureRandom` (which -happens in the next step a few times) run dry the Linux Kernel's entropy pool. The result is that some application will +It may happen that firing up docker containers and starting up application which use +Java's `SecureRandom` (which +happens in the next step a few times) run dry the Linux Kernel's entropy pool. The result +is that some application will block during startup -(even longer than 30 seconds) which will trigger OpenShift to kill the pods since they are considered unresponsive ( +(even longer than 30 seconds) which will trigger OpenShift to kill the pods since they are +considered unresponsive ( which they actually are). You can check the amount of entropy the kernel has available with the following command: cat /proc/sys/kernel/random/entropy_avail -If this number drops to zero, then the kernel has run out of entropy and application will block. +If this number drops to zero, then the kernel has run out of entropy and application will +block. -One solution (there are a few others) is to install `haveged` a user-space daemon which provides entropy to the kernel. +One solution (there are a few others) is to install `haveged` a user-space daemon which +provides entropy to the kernel. On CentOS 7 it can be installed with the following commands (all as `root`): @@ -199,8 +242,11 @@ On CentOS 7 it can be installed with the following commands (all as `root`): yum install haveged systemctl enable --now haveged -As the package comes from the [EPEL repositories](https://fedoraproject.org/wiki/EPEL "Information about EPEL"). If you -haven't yet enabled those repositories, then you need to do this before trying to install `haveged`: +As the package comes from +the [EPEL repositories](https://fedoraproject.org/wiki/EPEL "Information about EPEL"). If +you +haven't yet enabled those repositories, then you need to do this before trying to install +`haveged`: yum install epel-release diff --git a/extras/encryption-migrator/README.md b/extras/encryption-migrator/README.md index 3813973cc0a..a68344e1291 100644 --- a/extras/encryption-migrator/README.md +++ b/extras/encryption-migrator/README.md @@ -3,20 +3,28 @@ Kapua Encryption Migrator ## Introduction -This module contains a Java Application that leverages the Kapua APIs to update the encryption key used to perform symmetric encryption of entity attributes on DB persistence and any other usage of +This module contains a Java Application that leverages the Kapua APIs to update the +encryption key used to perform symmetric encryption of entity attributes on DB persistence +and any other usage of CryptoUtil class. ## Background -To improve security against unauthorized access to DB some fields that contain sensible data needs to be encrypted. This encryption makes difficult for an attacker to easily read data from the +To improve security against unauthorized access to DB some fields that contain sensible +data needs to be encrypted. This encryption makes difficult for an attacker to easily read +data from the database that may contain sensible data. -Kapua had already in place one-way encryption for Credentials and other resources while fields that required symmetric encryption didn't have a uniform and simple way to manage the encryption of the +Kapua had already in place one-way encryption for Credentials and other resources while +fields that required symmetric encryption didn't have a uniform and simple way to manage +the encryption of the fields. ## Changes in Kapua 2.0 -With Kapua 2.0.0 entity attributes can be symmetric encrypted by simply adding an annotation to the rest of the JPA mappings for an entity attribute which instructs JPA to crypt and decrypt fields +With Kapua 2.0.0 entity attributes can be symmetric encrypted by simply adding an +annotation to the rest of the JPA mappings for an entity attribute which instructs JPA to +crypt and decrypt fields values. Before Kapua 2.0.0 fields that were symmetric-encrypted are: @@ -28,16 +36,21 @@ After Kapua 2.0.0 fields that are symmetric-encrypted are: - MfaOption.mfaSecretKey - JobStepProperty.propertyValue -Every field share the same key and lets the developer abstract from the specific task of encrypting fields which gets delegated to JPA. While this can affect performances (we lose the on-demand +Every field share the same key and lets the developer abstract from the specific task of +encrypting fields which gets delegated to JPA. While this can affect performances (we lose +the on-demand encryption/decryption), we gain the ease of using this security feature. ## The ES indices Migration tool The encryption migration tool has been implemented with two goals: -- Do the first migration: to allow every field listed before to be unified under a single encryption key and mechanism. -- Update the encryption secret key: it might happen that a secret key needs to be replaced (e.g.: the secret key disclosure) - and this tools migrate every attribute from a given old encryption secret key to the newly given. +- Do the first migration: to allow every field listed before to be unified under a single + encryption key and mechanism. +- Update the encryption secret key: it might happen that a secret key needs to be + replaced (e.g.: the secret key disclosure) + and this tools migrate every attribute from a given old encryption secret key to the + newly given. ### Settings @@ -63,5 +76,5 @@ Other useful properties from Kapua #### Example usage ```bash -java -Dcommons.db.connection.host=somehost -Dmigrator.encryption.key.old=changeMePlease\!\! -Dmigrator.encryption.key.new=changedMeThanks\! -jar kapua-encryption-migrator-2.1.0-SNAPSHOT-app.jar +java -Dcommons.db.connection.host=somehost -Dmigrator.encryption.key.old=changeMePlease\!\! -Dmigrator.encryption.key.new=changedMeThanks\! -jar kapua-encryption-migrator-2.1.0-FALSE_EXTENSIONS-SNAPSHOT-app.jar ``` diff --git a/extras/encryption-migrator/pom.xml b/extras/encryption-migrator/pom.xml index b552cc5b6db..392d265cb7e 100644 --- a/extras/encryption-migrator/pom.xml +++ b/extras/encryption-migrator/pom.xml @@ -18,7 +18,7 @@ kapua-extras org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-encryption-migrator diff --git a/extras/encryption-migrator/src/main/java/org/eclipse/kapua/extras/migrator/encryption/api/AbstractEntityAttributeMigrator.java b/extras/encryption-migrator/src/main/java/org/eclipse/kapua/extras/migrator/encryption/api/AbstractEntityAttributeMigrator.java index a59da006688..48266a89e06 100644 --- a/extras/encryption-migrator/src/main/java/org/eclipse/kapua/extras/migrator/encryption/api/AbstractEntityAttributeMigrator.java +++ b/extras/encryption-migrator/src/main/java/org/eclipse/kapua/extras/migrator/encryption/api/AbstractEntityAttributeMigrator.java @@ -54,7 +54,7 @@ public void migrate(List entitiesToMigrate) throws KapuaException { @Override public List getChunk(int offset, int limit) throws KapuaException { - KapuaQuery query = newEntityQuery(); + KapuaQuery query = new KapuaQuery(); // This is the most stable sorting even if it is not always indexed query.setSortCriteria(query.fieldSortCriteria(KapuaEntityAttributes.CREATED_ON, SortOrder.ASCENDING)); @@ -67,9 +67,8 @@ public List getChunk(int offset, int limit) throws KapuaException { @Override public long getTotalCount() throws KapuaException { - KapuaQuery query = newEntityQuery(); + KapuaQuery query = new KapuaQuery(); return entityService.count(query); } - protected abstract KapuaQuery newEntityQuery(); } diff --git a/extras/encryption-migrator/src/main/java/org/eclipse/kapua/extras/migrator/encryption/authentication/MfaOptionAttributeMigrator.java b/extras/encryption-migrator/src/main/java/org/eclipse/kapua/extras/migrator/encryption/authentication/MfaOptionAttributeMigrator.java index 1b8ce0616c7..fdb81658f0e 100644 --- a/extras/encryption-migrator/src/main/java/org/eclipse/kapua/extras/migrator/encryption/authentication/MfaOptionAttributeMigrator.java +++ b/extras/encryption-migrator/src/main/java/org/eclipse/kapua/extras/migrator/encryption/authentication/MfaOptionAttributeMigrator.java @@ -16,10 +16,10 @@ import org.eclipse.kapua.commons.jpa.KapuaJpaTxManagerFactory; import org.eclipse.kapua.extras.migrator.encryption.api.AbstractEntityAttributeMigrator; import org.eclipse.kapua.extras.migrator.encryption.api.EntitySecretAttributeMigrator; -import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.service.authentication.credential.mfa.MfaOption; public class MfaOptionAttributeMigrator extends AbstractEntityAttributeMigrator implements EntitySecretAttributeMigrator { + public MfaOptionAttributeMigrator(String persistenceUnitName, KapuaJpaTxManagerFactory jpaTxManagerFactory) { super(new MfaOptionMigratorServiceImpl( jpaTxManagerFactory.create(persistenceUnitName), @@ -31,9 +31,4 @@ public MfaOptionAttributeMigrator(String persistenceUnitName, KapuaJpaTxManagerF public String getEntityName() { return MfaOption.TYPE; } - - @Override - protected KapuaQuery newEntityQuery() { - return new MfaOptionMigratorQueryImpl(); - } } diff --git a/extras/encryption-migrator/src/main/java/org/eclipse/kapua/extras/migrator/encryption/authentication/MfaOptionMigratorJpaRepository.java b/extras/encryption-migrator/src/main/java/org/eclipse/kapua/extras/migrator/encryption/authentication/MfaOptionMigratorJpaRepository.java index aebb923387d..d97364cfe39 100644 --- a/extras/encryption-migrator/src/main/java/org/eclipse/kapua/extras/migrator/encryption/authentication/MfaOptionMigratorJpaRepository.java +++ b/extras/encryption-migrator/src/main/java/org/eclipse/kapua/extras/migrator/encryption/authentication/MfaOptionMigratorJpaRepository.java @@ -12,6 +12,8 @@ *******************************************************************************/ package org.eclipse.kapua.extras.migrator.encryption.authentication; +import java.util.Optional; + import org.eclipse.kapua.commons.jpa.KapuaJpaRepositoryConfiguration; import org.eclipse.kapua.commons.jpa.KapuaUpdatableEntityJpaRepository; import org.eclipse.kapua.model.id.KapuaId; @@ -20,13 +22,12 @@ import org.eclipse.kapua.service.authentication.credential.mfa.MfaOptionRepository; import org.eclipse.kapua.storage.TxContext; -import java.util.Optional; - public class MfaOptionMigratorJpaRepository extends KapuaUpdatableEntityJpaRepository implements MfaOptionRepository { + public MfaOptionMigratorJpaRepository(KapuaJpaRepositoryConfiguration jpaRepoConfig) { - super(MfaOptionMigrator.class, MfaOption.TYPE, () -> new MfaOptionMigratorListResultImpl(), jpaRepoConfig); + super(MfaOptionMigrator.class, MfaOption.TYPE, () -> new MfaOptionListResult(), jpaRepoConfig); } @Override diff --git a/extras/encryption-migrator/src/main/java/org/eclipse/kapua/extras/migrator/encryption/authentication/MfaOptionMigratorListResultImpl.java b/extras/encryption-migrator/src/main/java/org/eclipse/kapua/extras/migrator/encryption/authentication/MfaOptionMigratorListResultImpl.java deleted file mode 100644 index fcade9feb5e..00000000000 --- a/extras/encryption-migrator/src/main/java/org/eclipse/kapua/extras/migrator/encryption/authentication/MfaOptionMigratorListResultImpl.java +++ /dev/null @@ -1,25 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.extras.migrator.encryption.authentication; - -import org.eclipse.kapua.commons.model.query.KapuaListResultImpl; -import org.eclipse.kapua.service.authentication.credential.mfa.MfaOption; -import org.eclipse.kapua.service.authentication.credential.mfa.MfaOptionListResult; - -/** - * {@link MfaOptionListResult} implementation. - * - * @since 1.0.0 - */ -public class MfaOptionMigratorListResultImpl extends KapuaListResultImpl implements MfaOptionListResult { -} diff --git a/extras/encryption-migrator/src/main/java/org/eclipse/kapua/extras/migrator/encryption/authentication/MfaOptionMigratorQueryImpl.java b/extras/encryption-migrator/src/main/java/org/eclipse/kapua/extras/migrator/encryption/authentication/MfaOptionMigratorQueryImpl.java deleted file mode 100644 index 65d19e55d7d..00000000000 --- a/extras/encryption-migrator/src/main/java/org/eclipse/kapua/extras/migrator/encryption/authentication/MfaOptionMigratorQueryImpl.java +++ /dev/null @@ -1,33 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.extras.migrator.encryption.authentication; - -import org.eclipse.kapua.commons.model.query.AbstractKapuaNamedQuery; -import org.eclipse.kapua.service.authentication.credential.mfa.MfaOptionQuery; - -/** - * {@link MfaOptionQuery} definition. - * - * @since 1.0.0 - */ -public class MfaOptionMigratorQueryImpl extends AbstractKapuaNamedQuery implements MfaOptionQuery { - - /** - * Constructor. - * - * @since 1.0.0 - */ - public MfaOptionMigratorQueryImpl() { - super(); - } -} diff --git a/extras/encryption-migrator/src/main/java/org/eclipse/kapua/extras/migrator/encryption/job/JobStepAttributeMigrator.java b/extras/encryption-migrator/src/main/java/org/eclipse/kapua/extras/migrator/encryption/job/JobStepAttributeMigrator.java index 6b84f533c8e..e821bd2d6fe 100644 --- a/extras/encryption-migrator/src/main/java/org/eclipse/kapua/extras/migrator/encryption/job/JobStepAttributeMigrator.java +++ b/extras/encryption-migrator/src/main/java/org/eclipse/kapua/extras/migrator/encryption/job/JobStepAttributeMigrator.java @@ -16,7 +16,6 @@ import org.eclipse.kapua.commons.jpa.KapuaJpaTxManagerFactory; import org.eclipse.kapua.extras.migrator.encryption.api.AbstractEntityAttributeMigrator; import org.eclipse.kapua.extras.migrator.encryption.api.EntitySecretAttributeMigrator; -import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.service.job.step.JobStep; public class JobStepAttributeMigrator extends AbstractEntityAttributeMigrator implements EntitySecretAttributeMigrator { @@ -33,8 +32,4 @@ public String getEntityName() { return JobStep.TYPE; } - @Override - protected KapuaQuery newEntityQuery() { - return new JobStepMigratorQueryImpl(); - } } diff --git a/extras/encryption-migrator/src/main/java/org/eclipse/kapua/extras/migrator/encryption/job/JobStepMigratorJpaRepository.java b/extras/encryption-migrator/src/main/java/org/eclipse/kapua/extras/migrator/encryption/job/JobStepMigratorJpaRepository.java index 252b5bcf617..62e73c3956f 100644 --- a/extras/encryption-migrator/src/main/java/org/eclipse/kapua/extras/migrator/encryption/job/JobStepMigratorJpaRepository.java +++ b/extras/encryption-migrator/src/main/java/org/eclipse/kapua/extras/migrator/encryption/job/JobStepMigratorJpaRepository.java @@ -12,6 +12,8 @@ *******************************************************************************/ package org.eclipse.kapua.extras.migrator.encryption.job; +import java.util.Optional; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.commons.jpa.KapuaJpaRepositoryConfiguration; import org.eclipse.kapua.commons.jpa.KapuaNamedEntityJpaRepository; @@ -22,14 +24,12 @@ import org.eclipse.kapua.service.job.step.definition.JobStepProperty; import org.eclipse.kapua.storage.TxContext; -import java.util.Optional; - public class JobStepMigratorJpaRepository extends KapuaNamedEntityJpaRepository implements JobStepRepository { public JobStepMigratorJpaRepository(KapuaJpaRepositoryConfiguration jpaRepoConfig) { - super(JobStepMigrator.class, JobStep.TYPE, () -> new JobStepMigratorListResultImpl(), jpaRepoConfig); + super(JobStepMigrator.class, JobStep.TYPE, () -> new JobStepListResult(), jpaRepoConfig); } @Override diff --git a/extras/encryption-migrator/src/main/java/org/eclipse/kapua/extras/migrator/encryption/job/JobStepMigratorListResultImpl.java b/extras/encryption-migrator/src/main/java/org/eclipse/kapua/extras/migrator/encryption/job/JobStepMigratorListResultImpl.java deleted file mode 100644 index 7662b098c99..00000000000 --- a/extras/encryption-migrator/src/main/java/org/eclipse/kapua/extras/migrator/encryption/job/JobStepMigratorListResultImpl.java +++ /dev/null @@ -1,25 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.extras.migrator.encryption.job; - -import org.eclipse.kapua.commons.model.query.KapuaListResultImpl; -import org.eclipse.kapua.service.job.step.JobStep; -import org.eclipse.kapua.service.job.step.JobStepListResult; - -/** - * {@link JobStepListResult} implementation. - * - * @since 1.0.0 - */ -public class JobStepMigratorListResultImpl extends KapuaListResultImpl implements JobStepListResult { -} diff --git a/extras/encryption-migrator/src/main/java/org/eclipse/kapua/extras/migrator/encryption/job/JobStepMigratorQueryImpl.java b/extras/encryption-migrator/src/main/java/org/eclipse/kapua/extras/migrator/encryption/job/JobStepMigratorQueryImpl.java deleted file mode 100644 index e9a1241dc28..00000000000 --- a/extras/encryption-migrator/src/main/java/org/eclipse/kapua/extras/migrator/encryption/job/JobStepMigratorQueryImpl.java +++ /dev/null @@ -1,33 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.extras.migrator.encryption.job; - -import org.eclipse.kapua.commons.model.query.AbstractKapuaNamedQuery; -import org.eclipse.kapua.service.job.step.JobStepQuery; - -/** - * {@link JobStepQuery} definition. - * - * @since 1.0.0 - */ -public class JobStepMigratorQueryImpl extends AbstractKapuaNamedQuery implements JobStepQuery { - - /** - * Constructor. - * - * @since 1.0.0 - */ - public JobStepMigratorQueryImpl() { - super(); - } -} diff --git a/extras/es-migrator/pom.xml b/extras/es-migrator/pom.xml index 00487f4704f..4d413f5a51b 100644 --- a/extras/es-migrator/pom.xml +++ b/extras/es-migrator/pom.xml @@ -17,7 +17,7 @@ kapua-extras org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT 4.0.0 kapua-es-migrator diff --git a/extras/foreignkeys/pom.xml b/extras/foreignkeys/pom.xml index 0b98fea8029..79d43c7ae94 100644 --- a/extras/foreignkeys/pom.xml +++ b/extras/foreignkeys/pom.xml @@ -17,7 +17,7 @@ org.eclipse.kapua kapua-extras - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-foreignkeys diff --git a/extras/liquibase-unlocker/README.md b/extras/liquibase-unlocker/README.md index 14dc4f4ef66..000b5bdfc66 100644 --- a/extras/liquibase-unlocker/README.md +++ b/extras/liquibase-unlocker/README.md @@ -3,27 +3,44 @@ Liquibase "changeLogLock" table unlocker tool ## Introduction -This module contains a Java Application that unlocks a stucked deployment caused by a wrong execution of liquibase updates +This module contains a Java Application that unlocks a stucked deployment caused by a +wrong execution of liquibase updates ## Background -The liquibase updates, run on changelog files, are performed concurrently by some Kapua containers. To ensure that a single container is running an update on the DB, aka to ensure the right concurrent -access to this shared resource, liquibase uses a table called DATABASECHANGELOGLOCK to track which entity is performing the update. A row in this table testifies the presence of an entity making an -update, therefore consulting it before performing an update allows you to understand if it is possible to acquire the lock on the resource. -After the update, the container that locked the recourse releases the lock by deleting the row in this table. - -It may happen that, while inside the critical section, the container running the update is stopped for some reason, for example for a crash. After this event, the DATABASECHANGELOGLOCK is left with a -row therefore the lock will never be released. If subsequent containers tries to perform other liquibase updates (for example, the mentioned container that has been restarted) they will be blocked +The liquibase updates, run on changelog files, are performed concurrently by some Kapua +containers. To ensure that a single container is running an update on the DB, aka to +ensure the right concurrent +access to this shared resource, liquibase uses a table called DATABASECHANGELOGLOCK to +track which entity is performing the update. A row in this table testifies the presence of +an entity making an +update, therefore consulting it before performing an update allows you to understand if it +is possible to acquire the lock on the resource. +After the update, the container that locked the recourse releases the lock by deleting the +row in this table. + +It may happen that, while inside the critical section, the container running the update is +stopped for some reason, for example for a crash. After this event, the +DATABASECHANGELOGLOCK is left with a +row therefore the lock will never be released. If subsequent containers tries to perform +other liquibase updates (for example, the mentioned container that has been restarted) +they will be blocked endlessly trying to enter the critical section. -Tu unlock this situation, a manual operation on such table (for example, the deletion of the row or the deletion of the entire table) sometime works. The fact is that the liquibase api provides an -explicit command to troubleshoot this situation, in a more safe way, so it is encouraged to use it. Furthermore, the mentioned manual operation requires access to the DB retrieving credentials and so -on. The proposed script doesn't require this and get the job done with a single invocation. +Tu unlock this situation, a manual operation on such table (for example, the deletion of +the row or the deletion of the entire table) sometime works. The fact is that the +liquibase api provides an +explicit command to troubleshoot this situation, in a more safe way, so it is encouraged +to use it. Furthermore, the mentioned manual operation requires access to the DB +retrieving credentials and so +on. The proposed script doesn't require this and get the job done with a single +invocation. #### Usage ```bash -java -jar kapua-liquibase-unlocker-2.1.0-SNAPSHOT-app.jar +java -jar kapua-liquibase-unlocker-2.1.0-FALSE_EXTENSIONS-SNAPSHOT-app.jar ``` -To be used when the deployment is stucked for the afore mentioned reasons, the lock will be released and the deployment will continue. \ No newline at end of file +To be used when the deployment is stucked for the afore mentioned reasons, the lock will +be released and the deployment will continue. \ No newline at end of file diff --git a/extras/liquibase-unlocker/pom.xml b/extras/liquibase-unlocker/pom.xml index 2372ac19716..a89e7a59c0e 100644 --- a/extras/liquibase-unlocker/pom.xml +++ b/extras/liquibase-unlocker/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-extras - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-liquibase-unlocker diff --git a/extras/pom.xml b/extras/pom.xml index 15051dabf3a..03c13cf1827 100644 --- a/extras/pom.xml +++ b/extras/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-extras diff --git a/job-engine/api/pom.xml b/job-engine/api/pom.xml index f568abf6915..8eea3632b7e 100644 --- a/job-engine/api/pom.xml +++ b/job-engine/api/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-job-engine - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-job-engine-api diff --git a/job-engine/api/src/main/java/org/eclipse/kapua/job/engine/JobEngineFactory.java b/job-engine/api/src/main/java/org/eclipse/kapua/job/engine/JobEngineFactory.java deleted file mode 100644 index 5aa1f706f92..00000000000 --- a/job-engine/api/src/main/java/org/eclipse/kapua/job/engine/JobEngineFactory.java +++ /dev/null @@ -1,20 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2018, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.job.engine; - -import org.eclipse.kapua.model.KapuaObjectFactory; - -public interface JobEngineFactory extends KapuaObjectFactory { - - JobStartOptions newJobStartOptions(); -} diff --git a/job-engine/api/src/main/java/org/eclipse/kapua/job/engine/JobEngineXmlRegistry.java b/job-engine/api/src/main/java/org/eclipse/kapua/job/engine/JobEngineXmlRegistry.java deleted file mode 100644 index 0f7e7f96ac9..00000000000 --- a/job-engine/api/src/main/java/org/eclipse/kapua/job/engine/JobEngineXmlRegistry.java +++ /dev/null @@ -1,24 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2018, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.job.engine; - -import org.eclipse.kapua.locator.KapuaLocator; - -public class JobEngineXmlRegistry { - - private JobEngineFactory jobEngineFactory = KapuaLocator.getInstance().getFactory(JobEngineFactory.class); - - public JobStartOptions newJobStartOptions() { - return jobEngineFactory.newJobStartOptions(); - } -} diff --git a/job-engine/api/src/main/java/org/eclipse/kapua/job/engine/JobStartOptions.java b/job-engine/api/src/main/java/org/eclipse/kapua/job/engine/JobStartOptions.java index 1b5f9846a89..499c45ddd21 100644 --- a/job-engine/api/src/main/java/org/eclipse/kapua/job/engine/JobStartOptions.java +++ b/job-engine/api/src/main/java/org/eclipse/kapua/job/engine/JobStartOptions.java @@ -12,11 +12,10 @@ *******************************************************************************/ package org.eclipse.kapua.job.engine; -import org.eclipse.kapua.KapuaSerializable; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.model.id.KapuaIdAdapter; -import org.eclipse.kapua.service.job.step.definition.JobStepProperty; -import org.eclipse.kapua.service.job.targets.JobTarget; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; @@ -26,8 +25,12 @@ import javax.xml.bind.annotation.XmlTransient; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; -import java.util.List; -import java.util.Set; + +import org.eclipse.kapua.KapuaSerializable; +import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.id.KapuaIdAdapter; +import org.eclipse.kapua.service.job.step.definition.JobStepProperty; +import org.eclipse.kapua.service.job.targets.JobTarget; /** * {@link JobStartOptions} definition. @@ -36,8 +39,16 @@ */ @XmlRootElement(name = "jobStartOptions") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = JobEngineXmlRegistry.class, factoryMethod = "newJobStartOptions") -public interface JobStartOptions extends KapuaSerializable { +@XmlType +public class JobStartOptions implements KapuaSerializable { + + private static final long serialVersionUID = 5339966879340542119L; + + private Set targetIdSublist; + private List stepPropertiesOverrides; + private boolean resetStepIndex; + private Integer fromStepIndex; + private boolean enqueue; /** * Gets the sub{@link java.util.List} of {@link org.eclipse.kapua.service.job.targets.JobTarget} {@link KapuaId}s. @@ -48,39 +59,64 @@ public interface JobStartOptions extends KapuaSerializable { @XmlElementWrapper(name = "targetIdSublist") @XmlElement(name = "targetId") @XmlJavaTypeAdapter(KapuaIdAdapter.class) - Set getTargetIdSublist(); + public Set getTargetIdSublist() { + if (targetIdSublist == null) { + targetIdSublist = new HashSet<>(); + } + + return targetIdSublist; + } /** * Sets the sub{@link java.util.List} of {@link org.eclipse.kapua.service.job.targets.JobTarget} {@link KapuaId}s. * - * @param targetIdSublist The sub{@link java.util.List} of {@link org.eclipse.kapua.service.job.targets.JobTarget} {@link KapuaId}s. + * @param targetIdSublist + * The sub{@link java.util.List} of {@link org.eclipse.kapua.service.job.targets.JobTarget} {@link KapuaId}s. * @since 1.0.0 */ - void setTargetIdSublist(Set targetIdSublist); + public void setTargetIdSublist(Set targetIdSublist) { + this.targetIdSublist = targetIdSublist; + } /** * Removes a {@link org.eclipse.kapua.service.job.targets.JobTarget} {@link KapuaId} from sub{@link java.util.List} of {@link org.eclipse.kapua.service.job.targets.JobTarget} {@link KapuaId}s. * - * @param targetId The {@link org.eclipse.kapua.service.job.targets.JobTarget} {@link KapuaId} to remove. + * @param targetId + * The {@link org.eclipse.kapua.service.job.targets.JobTarget} {@link KapuaId} to remove. * @since 1.0.0 */ @XmlTransient - void removeTargetIdToSublist(KapuaId targetId); + public void removeTargetIdToSublist(KapuaId targetId) { + getTargetIdSublist().remove(targetId); + } /** * Adds a {@link org.eclipse.kapua.service.job.targets.JobTarget} {@link KapuaId} from sub{@link java.util.List} of {@link org.eclipse.kapua.service.job.targets.JobTarget} {@link KapuaId}s. * - * @param targetId The {@link org.eclipse.kapua.service.job.targets.JobTarget} {@link KapuaId} to add. + * @param targetId + * The {@link org.eclipse.kapua.service.job.targets.JobTarget} {@link KapuaId} to add. * @since 1.0.0 */ @XmlTransient - void addTargetIdToSublist(KapuaId targetId); + public void addTargetIdToSublist(KapuaId targetId) { + getTargetIdSublist().add(targetId); + } + + public List getStepPropertiesOverrides() { + if (stepPropertiesOverrides == null) { + stepPropertiesOverrides = new ArrayList<>(); + } - List getStepPropertiesOverrides(); + return stepPropertiesOverrides; + } - void addStepPropertyOverride(JobStepProperty jobStepPropertyOverride); + public void addStepPropertyOverride(JobStepProperty stepPropertyOverride) { + getStepPropertiesOverrides().add(stepPropertyOverride); + } - void setStepPropertiesOverrides(List jobStepPropertiesOverrides); + public void setStepPropertiesOverrides(List stepPropertiesOverrides) { + this.stepPropertiesOverrides = new ArrayList<>(stepPropertiesOverrides); + } /** * Gets whether or not the {@link JobTarget#getStepIndex()} needs to be reset to the given {@link #getFromStepIndex()}. @@ -88,15 +124,20 @@ public interface JobStartOptions extends KapuaSerializable { * @return {@code true} if the {@link JobTarget#getStepIndex()} needs to be reset to the given {@link #getFromStepIndex()}, {@code false} otherwise. * @since 1.1.0 */ - boolean getResetStepIndex(); + public boolean getResetStepIndex() { + return resetStepIndex; + } /** * Sets whether or not the {@link JobTarget#getStepIndex()} needs to be reset to the given {@link #getFromStepIndex()}. * - * @param resetStepIndex {@code true} if the {@link JobTarget#getStepIndex()} needs to be reset to the given {@link #getFromStepIndex()}, {@code false} otherwise. + * @param resetStepIndex + * {@code true} if the {@link JobTarget#getStepIndex()} needs to be reset to the given {@link #getFromStepIndex()}, {@code false} otherwise. * @since 1.1.0 */ - void setResetStepIndex(boolean resetStepIndex); + public void setResetStepIndex(boolean resetStepIndex) { + this.resetStepIndex = resetStepIndex; + } /** * Gets the starting {@link org.eclipse.kapua.service.job.step.JobStep} index. @@ -104,15 +145,20 @@ public interface JobStartOptions extends KapuaSerializable { * @return The starting {@link org.eclipse.kapua.service.job.step.JobStep} index. * @since 1.0.0 */ - Integer getFromStepIndex(); + public Integer getFromStepIndex() { + return fromStepIndex; + } /** * Sets the starting {@link org.eclipse.kapua.service.job.step.JobStep} index. * - * @param fromStepIndex The starting {@link org.eclipse.kapua.service.job.step.JobStep} index. + * @param fromStepIndex + * The starting {@link org.eclipse.kapua.service.job.step.JobStep} index. * @since 1.0.0 */ - void setFromStepIndex(Integer fromStepIndex); + public void setFromStepIndex(Integer fromStepIndex) { + this.fromStepIndex = fromStepIndex; + } /** * Gets whether or not enqueue the {@link org.eclipse.kapua.service.job.execution.JobExecution}. @@ -120,14 +166,19 @@ public interface JobStartOptions extends KapuaSerializable { * @return {@code true} if the {@link org.eclipse.kapua.service.job.execution.JobExecution} needs to be enqueued, {@code false} otherwise. * @since 1.1.0 */ - boolean getEnqueue(); + public boolean getEnqueue() { + return enqueue; + } /** * Sets whether or not enqueue the {@link org.eclipse.kapua.service.job.execution.JobExecution}. * - * @param enqueue {@code true} if the {@link org.eclipse.kapua.service.job.execution.JobExecution} needs to be enqueued, {@code false} otherwise. + * @param enqueue + * {@code true} if the {@link org.eclipse.kapua.service.job.execution.JobExecution} needs to be enqueued, {@code false} otherwise. * @since 1.1.0 */ - void setEnqueue(boolean enqueue); + public void setEnqueue(boolean enqueue) { + this.enqueue = enqueue; + } } diff --git a/job-engine/api/src/main/java/org/eclipse/kapua/job/engine/queue/QueuedJobExecutionCreator.java b/job-engine/api/src/main/java/org/eclipse/kapua/job/engine/queue/QueuedJobExecutionCreator.java index e1d21ba99f4..19aa9e2472c 100644 --- a/job-engine/api/src/main/java/org/eclipse/kapua/job/engine/queue/QueuedJobExecutionCreator.java +++ b/job-engine/api/src/main/java/org/eclipse/kapua/job/engine/queue/QueuedJobExecutionCreator.java @@ -12,14 +12,15 @@ *******************************************************************************/ package org.eclipse.kapua.job.engine.queue; -import org.eclipse.kapua.model.KapuaUpdatableEntityCreator; -import org.eclipse.kapua.model.id.KapuaId; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; +import org.eclipse.kapua.model.KapuaEntityCreator; +import org.eclipse.kapua.model.KapuaUpdatableEntityCreator; +import org.eclipse.kapua.model.id.KapuaId; + /** * {@link QueuedJobExecutionCreator} definition. * @@ -27,8 +28,26 @@ */ @XmlRootElement(name = "queuedJobExecutionCreator") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = QueuedJobExecutionXmlRegistry.class, factoryMethod = "newQueuedJobExecutionCreator") -public interface QueuedJobExecutionCreator extends KapuaUpdatableEntityCreator { +@XmlType +public class QueuedJobExecutionCreator extends KapuaUpdatableEntityCreator { + + private static final long serialVersionUID = 3119071638220738358L; + + private KapuaId jobId; + private KapuaId jobExecutionId; + private KapuaId waitForJobExecutionId; + private QueuedJobExecutionStatus status; + + public QueuedJobExecutionCreator() { + } + + public QueuedJobExecutionCreator(KapuaId scopeId) { + super(scopeId); + } + + public QueuedJobExecutionCreator(KapuaEntityCreator entityCreator) { + super(entityCreator); + } /** * Gets the {@link org.eclipse.kapua.service.job.Job} {@link KapuaId}. @@ -36,15 +55,20 @@ public interface QueuedJobExecutionCreator extends KapuaUpdatableEntityCreator { +public interface QueuedJobExecutionFactory extends KapuaEntityFactory { } diff --git a/job-engine/api/src/main/java/org/eclipse/kapua/job/engine/queue/QueuedJobExecutionListResult.java b/job-engine/api/src/main/java/org/eclipse/kapua/job/engine/queue/QueuedJobExecutionListResult.java index d3c35da8534..906559a3a38 100644 --- a/job-engine/api/src/main/java/org/eclipse/kapua/job/engine/queue/QueuedJobExecutionListResult.java +++ b/job-engine/api/src/main/java/org/eclipse/kapua/job/engine/queue/QueuedJobExecutionListResult.java @@ -26,7 +26,7 @@ */ @XmlRootElement(name = "queuedJobListResult") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = QueuedJobExecutionXmlRegistry.class, factoryMethod = "newQueuedJobExecutionListResult") -public interface QueuedJobExecutionListResult extends KapuaListResult { +@XmlType +public class QueuedJobExecutionListResult extends KapuaListResult { } diff --git a/job-engine/api/src/main/java/org/eclipse/kapua/job/engine/queue/QueuedJobExecutionQuery.java b/job-engine/api/src/main/java/org/eclipse/kapua/job/engine/queue/QueuedJobExecutionQuery.java deleted file mode 100644 index 2aaef2a32f8..00000000000 --- a/job-engine/api/src/main/java/org/eclipse/kapua/job/engine/queue/QueuedJobExecutionQuery.java +++ /dev/null @@ -1,32 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2019, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.job.engine.queue; - -import org.eclipse.kapua.model.query.KapuaQuery; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlType; - -/** - * {@link QueuedJobExecution} {@link KapuaQuery} definition. - * - * @see KapuaQuery - * @since 1.1.0 - */ -@XmlRootElement(name = "query") -@XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = QueuedJobExecutionXmlRegistry.class, factoryMethod = "newQuery") -public interface QueuedJobExecutionQuery extends KapuaQuery { -} diff --git a/job-engine/api/src/main/java/org/eclipse/kapua/job/engine/queue/QueuedJobExecutionService.java b/job-engine/api/src/main/java/org/eclipse/kapua/job/engine/queue/QueuedJobExecutionService.java index 997d4baa5ff..51e21cd5a03 100644 --- a/job-engine/api/src/main/java/org/eclipse/kapua/job/engine/queue/QueuedJobExecutionService.java +++ b/job-engine/api/src/main/java/org/eclipse/kapua/job/engine/queue/QueuedJobExecutionService.java @@ -18,9 +18,8 @@ import org.eclipse.kapua.service.KapuaUpdatableEntityService; /** - * {@link QueuedJobExecutionService} exposes APIs to manage {@link QueuedJobExecution} objects.
    - * It includes APIs to create, update, find, list and delete {@link QueuedJobExecution}s.
    - * Instances of the {@link QueuedJobExecutionService} can be acquired through the {@link org.eclipse.kapua.locator.KapuaLocator} object. + * {@link QueuedJobExecutionService} exposes APIs to manage {@link QueuedJobExecution} objects.
    It includes APIs to create, update, find, list and delete {@link QueuedJobExecution}s.
    Instances + * of the {@link QueuedJobExecutionService} can be acquired through the {@link org.eclipse.kapua.locator.KapuaLocator} object. * * @since 1.1.0 */ @@ -30,7 +29,8 @@ public interface QueuedJobExecutionService extends KapuaEntityService kapua-job-engine-app org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-job-engine-app-core diff --git a/job-engine/app/core/src/main/java/org/eclipse/kapua/job/engine/app/core/jackson/ObjectMapperProvider.java b/job-engine/app/core/src/main/java/org/eclipse/kapua/job/engine/app/core/jackson/ObjectMapperProvider.java index ff768bc14a4..a7f53d11ba0 100644 --- a/job-engine/app/core/src/main/java/org/eclipse/kapua/job/engine/app/core/jackson/ObjectMapperProvider.java +++ b/job-engine/app/core/src/main/java/org/eclipse/kapua/job/engine/app/core/jackson/ObjectMapperProvider.java @@ -12,18 +12,17 @@ *******************************************************************************/ package org.eclipse.kapua.job.engine.app.core.jackson; -import com.fasterxml.jackson.databind.ObjectMapper; +import javax.ws.rs.ext.ContextResolver; +import javax.ws.rs.ext.Provider; + import org.eclipse.kapua.commons.rest.model.IsJobRunningResponse; -import org.eclipse.kapua.job.engine.JobStartOptions; import org.eclipse.kapua.job.engine.app.core.jackson.mixin.IsJobRunningResponseMixin; -import org.eclipse.kapua.job.engine.app.core.jackson.mixin.JobStartOptionsMixin; import org.eclipse.kapua.job.engine.app.core.jackson.mixin.JobStepPropertyMixin; import org.eclipse.kapua.job.engine.app.core.jackson.mixin.KapuaIdMixin; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.job.step.definition.JobStepProperty; -import javax.ws.rs.ext.ContextResolver; -import javax.ws.rs.ext.Provider; +import com.fasterxml.jackson.databind.ObjectMapper; @Provider public class ObjectMapperProvider implements ContextResolver { @@ -33,7 +32,6 @@ public class ObjectMapperProvider implements ContextResolver { public ObjectMapperProvider() { objectMapper = new ObjectMapper(); objectMapper.addMixIn(KapuaId.class, KapuaIdMixin.class); - objectMapper.addMixIn(JobStartOptions.class, JobStartOptionsMixin.class); objectMapper.addMixIn(JobStepProperty.class, JobStepPropertyMixin.class); objectMapper.addMixIn(IsJobRunningResponse.class, IsJobRunningResponseMixin.class); } diff --git a/job-engine/app/core/src/main/java/org/eclipse/kapua/job/engine/app/core/jackson/mixin/JobStartOptionsMixin.java b/job-engine/app/core/src/main/java/org/eclipse/kapua/job/engine/app/core/jackson/mixin/JobStartOptionsMixin.java deleted file mode 100644 index a5a7ac3e95f..00000000000 --- a/job-engine/app/core/src/main/java/org/eclipse/kapua/job/engine/app/core/jackson/mixin/JobStartOptionsMixin.java +++ /dev/null @@ -1,22 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.job.engine.app.core.jackson.mixin; - -import org.eclipse.kapua.job.engine.jbatch.JobStartOptionsImpl; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.databind.annotation.JsonDeserialize; - -@JsonDeserialize(as = JobStartOptionsImpl.class) -@JsonIgnoreProperties("type") -public interface JobStartOptionsMixin { } diff --git a/job-engine/app/pom.xml b/job-engine/app/pom.xml index d07e6b2083d..084760a91eb 100644 --- a/job-engine/app/pom.xml +++ b/job-engine/app/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-job-engine - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-job-engine-app diff --git a/job-engine/app/resources/pom.xml b/job-engine/app/resources/pom.xml index e53d16012a5..443e14a141d 100644 --- a/job-engine/app/resources/pom.xml +++ b/job-engine/app/resources/pom.xml @@ -18,7 +18,7 @@ kapua-job-engine-app org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-job-engine-app-resources diff --git a/job-engine/app/web/pom.xml b/job-engine/app/web/pom.xml index 927ba567304..96a76e37c34 100644 --- a/job-engine/app/web/pom.xml +++ b/job-engine/app/web/pom.xml @@ -18,7 +18,7 @@ kapua-job-engine-app org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-job-engine-app-web diff --git a/job-engine/app/web/src/main/java/org/eclipse/kapua/job/engine/app/web/jaxb/JobEngineJAXBContextProvider.java b/job-engine/app/web/src/main/java/org/eclipse/kapua/job/engine/app/web/jaxb/JobEngineJAXBContextProvider.java index fe837571f4f..7db3668b3fe 100644 --- a/job-engine/app/web/src/main/java/org/eclipse/kapua/job/engine/app/web/jaxb/JobEngineJAXBContextProvider.java +++ b/job-engine/app/web/src/main/java/org/eclipse/kapua/job/engine/app/web/jaxb/JobEngineJAXBContextProvider.java @@ -40,7 +40,6 @@ import org.eclipse.kapua.job.engine.JobStartOptions; import org.eclipse.kapua.job.engine.commons.model.JobStepPropertiesOverrides; import org.eclipse.kapua.job.engine.commons.model.JobTargetSublist; -import org.eclipse.kapua.service.authentication.AuthenticationXmlRegistry; import org.eclipse.kapua.service.authentication.token.AccessToken; import org.eclipse.kapua.service.device.call.kura.model.configuration.KuraDeviceConfiguration; import org.eclipse.kapua.service.device.management.asset.DeviceAssets; @@ -54,7 +53,6 @@ import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystoreItemQuery; import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystoreItems; import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystoreKeypair; -import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystoreXmlRegistry; import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystores; import org.eclipse.kapua.service.device.management.packages.model.download.DevicePackageDownloadOptions; import org.eclipse.kapua.service.device.management.packages.model.download.DevicePackageDownloadRequest; @@ -71,15 +69,12 @@ import org.eclipse.kapua.service.job.execution.JobExecutionXmlRegistry; import org.eclipse.kapua.service.job.step.JobStep; import org.eclipse.kapua.service.job.step.JobStepListResult; -import org.eclipse.kapua.service.job.step.JobStepQuery; import org.eclipse.kapua.service.job.step.JobStepXmlRegistry; import org.eclipse.kapua.service.job.step.definition.JobStepProperty; import org.eclipse.kapua.service.job.targets.JobTarget; import org.eclipse.kapua.service.job.targets.JobTargetListResult; -import org.eclipse.kapua.service.job.targets.JobTargetQuery; import org.eclipse.kapua.service.scheduler.trigger.Trigger; import org.eclipse.kapua.service.scheduler.trigger.TriggerListResult; -import org.eclipse.kapua.service.scheduler.trigger.TriggerQuery; import org.eclipse.kapua.service.scheduler.trigger.TriggerXmlRegistry; import org.eclipse.persistence.jaxb.JAXBContextFactory; import org.eclipse.persistence.jaxb.MarshallerProperties; @@ -132,7 +127,6 @@ public JAXBContext getJAXBContext() throws KapuaException { JobStoppingExceptionInfo.class, // Authentication - AuthenticationXmlRegistry.class, AccessToken.class, // Device Management Keystore @@ -145,7 +139,6 @@ public JAXBContext getJAXBContext() throws KapuaException { DeviceKeystoreKeypair.class, DeviceKeystoreCSRInfo.class, DeviceKeystoreCSR.class, - DeviceKeystoreXmlRegistry.class, // Jobs Job.class, @@ -154,7 +147,6 @@ public JAXBContext getJAXBContext() throws KapuaException { JobStep.class, JobStepListResult.class, - JobStepQuery.class, JobStepXmlRegistry.class, JobStepProperty.class, @@ -165,7 +157,6 @@ public JAXBContext getJAXBContext() throws KapuaException { JobTarget.class, JobTargetListResult.class, - JobTargetQuery.class, JobExecutionXmlRegistry.class, JobTargetSublist.class, @@ -182,7 +173,6 @@ public JAXBContext getJAXBContext() throws KapuaException { Trigger.class, TriggerListResult.class, - TriggerQuery.class, TriggerXmlRegistry.class, KuraDeviceConfiguration.class diff --git a/job-engine/client/pom.xml b/job-engine/client/pom.xml index 94eeb99cf6f..f4d7630b8f7 100644 --- a/job-engine/client/pom.xml +++ b/job-engine/client/pom.xml @@ -20,7 +20,7 @@ kapua-job-engine org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-job-engine-client diff --git a/job-engine/client/src/main/java/org/eclipse/kapua/job/engine/client/JobEngineClientModule.java b/job-engine/client/src/main/java/org/eclipse/kapua/job/engine/client/JobEngineClientModule.java index fa5be800928..a258ddce90d 100644 --- a/job-engine/client/src/main/java/org/eclipse/kapua/job/engine/client/JobEngineClientModule.java +++ b/job-engine/client/src/main/java/org/eclipse/kapua/job/engine/client/JobEngineClientModule.java @@ -12,17 +12,16 @@ *******************************************************************************/ package org.eclipse.kapua.job.engine.client; +import javax.inject.Singleton; + import org.eclipse.kapua.commons.core.AbstractKapuaModule; -import org.eclipse.kapua.job.engine.JobEngineFactory; import org.eclipse.kapua.job.engine.JobEngineService; import org.eclipse.kapua.job.engine.client.settings.JobEngineClientSetting; -import javax.inject.Singleton; - public class JobEngineClientModule extends AbstractKapuaModule { + @Override protected void configureModule() { - bind(JobEngineFactory.class).to(JobEngineFactoryClient.class).in(Singleton.class); bind(JobEngineService.class).to(JobEngineServiceClient.class).in(Singleton.class); bind(JobEngineClientSetting.class).in(Singleton.class); } diff --git a/job-engine/client/src/main/java/org/eclipse/kapua/job/engine/client/JobEngineFactoryClient.java b/job-engine/client/src/main/java/org/eclipse/kapua/job/engine/client/JobEngineFactoryClient.java deleted file mode 100644 index de1da49395b..00000000000 --- a/job-engine/client/src/main/java/org/eclipse/kapua/job/engine/client/JobEngineFactoryClient.java +++ /dev/null @@ -1,33 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.job.engine.client; - -import org.eclipse.kapua.job.engine.JobEngineFactory; -import org.eclipse.kapua.job.engine.JobStartOptions; - -import javax.inject.Singleton; - -/** - * {@link JobEngineFactory} remote client implementation - * - * @since 1.5.0 - */ -@Singleton -public class JobEngineFactoryClient implements JobEngineFactory { - - @Override - public JobStartOptions newJobStartOptions() { - return new JobStartOptionsClient(); - } - -} diff --git a/job-engine/client/src/main/java/org/eclipse/kapua/job/engine/client/JobStartOptionsClient.java b/job-engine/client/src/main/java/org/eclipse/kapua/job/engine/client/JobStartOptionsClient.java deleted file mode 100644 index f437c3bcdbe..00000000000 --- a/job-engine/client/src/main/java/org/eclipse/kapua/job/engine/client/JobStartOptionsClient.java +++ /dev/null @@ -1,112 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.job.engine.client; - -import org.eclipse.kapua.job.engine.JobStartOptions; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.job.step.definition.JobStepProperty; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -/** - * {@link JobStartOptions} remote client implementation. - * - * @since 1.5.0 - */ -public class JobStartOptionsClient implements JobStartOptions { - - private static final long serialVersionUID = 7890046123237425642L; - - private Set targetIdSublist; - private List stepPropertiesOverrides; - private boolean resetStepIndex; - private Integer fromStepIndex; - private boolean enqueue; - - @Override - public Set getTargetIdSublist() { - if (targetIdSublist == null) { - this.targetIdSublist = new HashSet<>(); - } - - return targetIdSublist; - } - - @Override - public void setTargetIdSublist(Set targetIdSublist) { - this.targetIdSublist = targetIdSublist; - } - - @Override - public void addTargetIdToSublist(KapuaId targetId) { - getTargetIdSublist().add(targetId); - } - - @Override - public void removeTargetIdToSublist(KapuaId targetId) { - getTargetIdSublist().remove(targetId); - } - - @Override - public List getStepPropertiesOverrides() { - if (stepPropertiesOverrides == null) { - stepPropertiesOverrides = new ArrayList<>(); - } - - return stepPropertiesOverrides; - } - - @Override - public void addStepPropertyOverride(JobStepProperty jobStepPropertyOverride) { - getStepPropertiesOverrides().add(jobStepPropertyOverride); - } - - @Override - public void setStepPropertiesOverrides(List stepPropertiesOverrides) { - this.stepPropertiesOverrides = new ArrayList<>(stepPropertiesOverrides); - } - - @Override - public boolean getResetStepIndex() { - return resetStepIndex; - } - - @Override - public void setResetStepIndex(boolean resetStepIndex) { - this.resetStepIndex = resetStepIndex; - } - - @Override - public Integer getFromStepIndex() { - return fromStepIndex; - } - - @Override - public void setFromStepIndex(Integer fromStepIndex) { - this.fromStepIndex = fromStepIndex; - } - - @Override - public boolean getEnqueue() { - return enqueue; - } - - @Override - public void setEnqueue(boolean enqueue) { - this.enqueue = enqueue; - } - -} diff --git a/job-engine/commons/pom.xml b/job-engine/commons/pom.xml index c7d193790e4..14d59b966a0 100644 --- a/job-engine/commons/pom.xml +++ b/job-engine/commons/pom.xml @@ -19,7 +19,7 @@ org.eclipse.kapua kapua-job-engine - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-job-engine-commons diff --git a/job-engine/commons/src/main/java/org/eclipse/kapua/job/engine/commons/operation/DefaultTargetReader.java b/job-engine/commons/src/main/java/org/eclipse/kapua/job/engine/commons/operation/DefaultTargetReader.java index 02d34c4f333..a1c6930ee97 100644 --- a/job-engine/commons/src/main/java/org/eclipse/kapua/job/engine/commons/operation/DefaultTargetReader.java +++ b/job-engine/commons/src/main/java/org/eclipse/kapua/job/engine/commons/operation/DefaultTargetReader.java @@ -40,7 +40,6 @@ import org.eclipse.kapua.service.job.targets.JobTargetAttributes; import org.eclipse.kapua.service.job.targets.JobTargetFactory; import org.eclipse.kapua.service.job.targets.JobTargetListResult; -import org.eclipse.kapua.service.job.targets.JobTargetQuery; import org.eclipse.kapua.service.job.targets.JobTargetService; import org.eclipse.kapua.service.job.targets.JobTargetStatus; import org.slf4j.Logger; @@ -88,7 +87,7 @@ public void open(Serializable arg0) throws Exception { jobLogger.info("Reading target chunk. Step:{} (index:{})...", stepName, stepIndex); // Job Id and JobTarget status filtering - JobTargetQuery query = jobTargetFactory.newQuery(jobContextWrapper.getScopeId()); + KapuaQuery query = new KapuaQuery(jobContextWrapper.getScopeId()); AndPredicate andPredicate = query.andPredicate( query.attributePredicate(JobTargetAttributes.JOB_ID, jobContextWrapper.getJobId()) diff --git a/job-engine/jbatch/pom.xml b/job-engine/jbatch/pom.xml index 66487f05c56..7eff6a04893 100644 --- a/job-engine/jbatch/pom.xml +++ b/job-engine/jbatch/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-job-engine - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-job-engine-jbatch diff --git a/job-engine/jbatch/src/main/java/org/eclipse/kapua/job/engine/jbatch/JobEngineFactoryJbatch.java b/job-engine/jbatch/src/main/java/org/eclipse/kapua/job/engine/jbatch/JobEngineFactoryJbatch.java deleted file mode 100644 index 74a7aa65988..00000000000 --- a/job-engine/jbatch/src/main/java/org/eclipse/kapua/job/engine/jbatch/JobEngineFactoryJbatch.java +++ /dev/null @@ -1,27 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2018, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.job.engine.jbatch; - -import org.eclipse.kapua.job.engine.JobEngineFactory; -import org.eclipse.kapua.job.engine.JobStartOptions; - -import javax.inject.Singleton; - -@Singleton -public class JobEngineFactoryJbatch implements JobEngineFactory { - - @Override - public JobStartOptions newJobStartOptions() { - return new JobStartOptionsImpl(); - } -} diff --git a/job-engine/jbatch/src/main/java/org/eclipse/kapua/job/engine/jbatch/JobEngineServiceJbatch.java b/job-engine/jbatch/src/main/java/org/eclipse/kapua/job/engine/jbatch/JobEngineServiceJbatch.java index 80f18a685b9..2133aa4ee91 100644 --- a/job-engine/jbatch/src/main/java/org/eclipse/kapua/job/engine/jbatch/JobEngineServiceJbatch.java +++ b/job-engine/jbatch/src/main/java/org/eclipse/kapua/job/engine/jbatch/JobEngineServiceJbatch.java @@ -12,6 +12,13 @@ *******************************************************************************/ package org.eclipse.kapua.job.engine.jbatch; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import javax.inject.Inject; +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaEntityNotFoundException; import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.KapuaIllegalArgumentException; @@ -33,53 +40,38 @@ import org.eclipse.kapua.model.KapuaEntityAttributes; import org.eclipse.kapua.model.domain.Actions; import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; +import org.eclipse.kapua.service.authorization.permission.Permission; import org.eclipse.kapua.service.job.Job; import org.eclipse.kapua.service.job.JobService; import org.eclipse.kapua.service.job.execution.JobExecution; import org.eclipse.kapua.service.job.execution.JobExecutionService; import org.eclipse.kapua.service.job.step.JobStepAttributes; -import org.eclipse.kapua.service.job.step.JobStepFactory; -import org.eclipse.kapua.service.job.step.JobStepQuery; import org.eclipse.kapua.service.job.step.JobStepService; import org.eclipse.kapua.service.job.targets.JobTargetAttributes; -import org.eclipse.kapua.service.job.targets.JobTargetFactory; -import org.eclipse.kapua.service.job.targets.JobTargetQuery; import org.eclipse.kapua.service.job.targets.JobTargetService; -import javax.inject.Inject; -import javax.inject.Singleton; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - @Singleton public class JobEngineServiceJbatch implements JobEngineService { @Inject private AuthorizationService authorizationService; @Inject - private PermissionFactory permissionFactory; - @Inject private JobService jobService; @Inject private JobExecutionService jobExecutionService; @Inject private JobStepService jobStepService; @Inject - private JobStepFactory jobStepFactory; - @Inject private JobTargetService jobTargetService; @Inject - private JobTargetFactory jobTargetFactory; - @Inject private JbatchDriver jbatchDriver; private static final String JOB_EXECUTION_ID = "jobExecutionId"; @Override public void startJob(KapuaId scopeId, KapuaId jobId) throws KapuaException { - startJob(scopeId, jobId, new JobStartOptionsImpl()); + startJob(scopeId, jobId, new JobStartOptions()); } @Override @@ -89,14 +81,14 @@ public void startJob(KapuaId scopeId, KapuaId jobId, JobStartOptions jobStartOpt ArgumentValidator.notNull(jobId, KapuaEntityAttributes.ENTITY_ID); ArgumentValidator.notNull(jobStartOptions, "jobStartOptions"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.execute, scopeId)); + authorizationService.checkPermission(new Permission(Domains.JOB, Actions.execute, scopeId)); // Check Job Existence Job job = jobService.find(scopeId, jobId); if (job == null) { throw new KapuaEntityNotFoundException(Job.TYPE, jobId); } // Check job targets - JobTargetQuery jobTargetQuery = jobTargetFactory.newQuery(scopeId); + KapuaQuery jobTargetQuery = new KapuaQuery(scopeId); jobTargetQuery.setPredicate(jobTargetQuery.attributePredicate(JobTargetAttributes.JOB_ID, jobId)); if (jobTargetService.count(jobTargetQuery) <= 0) { throw new JobMissingTargetException(scopeId, jobId); @@ -115,7 +107,7 @@ public void startJob(KapuaId scopeId, KapuaId jobId, JobStartOptions jobStartOpt } } // Check job steps - JobStepQuery jobStepQuery = jobStepFactory.newQuery(scopeId); + KapuaQuery jobStepQuery = new KapuaQuery(scopeId); jobStepQuery.setPredicate(jobStepQuery.attributePredicate(JobStepAttributes.JOB_ID, jobId)); if (jobStepService.count(jobStepQuery) <= 0) { throw new JobMissingStepException(scopeId, jobId); @@ -134,7 +126,7 @@ public boolean isRunning(KapuaId scopeId, KapuaId jobId) throws KapuaException { ArgumentValidator.notNull(scopeId, KapuaEntityAttributes.SCOPE_ID); ArgumentValidator.notNull(jobId, KapuaEntityAttributes.ENTITY_ID); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.read, scopeId)); + authorizationService.checkPermission(new Permission(Domains.JOB, Actions.read, scopeId)); return internalIsRunning(scopeId, jobId); } @@ -144,7 +136,7 @@ public Map isRunning(KapuaId scopeId, Set jobIds) thr // Argument Validation ArgumentValidator.notNull(scopeId, KapuaEntityAttributes.SCOPE_ID); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.read, scopeId)); + authorizationService.checkPermission(new Permission(Domains.JOB, Actions.read, scopeId)); Map isRunningMap = new HashMap<>(); jobIds.forEach(jobId -> { @@ -165,7 +157,7 @@ public void stopJob(KapuaId scopeId, KapuaId jobId) throws KapuaException { ArgumentValidator.notNull(scopeId, KapuaEntityAttributes.SCOPE_ID); ArgumentValidator.notNull(jobId, KapuaEntityAttributes.ENTITY_ID); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.execute, scopeId)); + authorizationService.checkPermission(new Permission(Domains.JOB, Actions.execute, scopeId)); // Check existence Job job = jobService.find(scopeId, jobId); if (job == null) { @@ -190,7 +182,7 @@ public void stopJobExecution(KapuaId scopeId, KapuaId jobId, KapuaId jobExecutio ArgumentValidator.notNull(jobId, KapuaEntityAttributes.ENTITY_ID); ArgumentValidator.notNull(jobExecutionId, JOB_EXECUTION_ID); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.execute, scopeId)); + authorizationService.checkPermission(new Permission(Domains.JOB, Actions.execute, scopeId)); // Check existence Job job = jobService.find(scopeId, jobId); if (job == null) { @@ -221,7 +213,7 @@ public void resumeJobExecution(KapuaId scopeId, KapuaId jobId, KapuaId jobExecut ArgumentValidator.notNull(jobId, KapuaEntityAttributes.ENTITY_ID); ArgumentValidator.notNull(jobExecutionId, JOB_EXECUTION_ID); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.execute, scopeId)); + authorizationService.checkPermission(new Permission(Domains.JOB, Actions.execute, scopeId)); // Check existence Job job = jobService.find(scopeId, jobId); if (job == null) { @@ -251,7 +243,7 @@ public void cleanJobData(KapuaId scopeId, KapuaId jobId) throws KapuaException { ArgumentValidator.notNull(scopeId, KapuaEntityAttributes.SCOPE_ID); ArgumentValidator.notNull(jobId, KapuaEntityAttributes.ENTITY_ID); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.delete, null)); + authorizationService.checkPermission(new Permission(Domains.JOB, Actions.delete, null)); // Check existence Job job = jobService.find(scopeId, jobId); if (job == null) { @@ -273,12 +265,17 @@ public void cleanJobData(KapuaId scopeId, KapuaId jobId) throws KapuaException { /** * Using the {@link JbatchDriver} checks whether the {@link Job} is running. * - * @param scopeId The {@link Job#getScopeId()}. - * @param jobId The {@link Job#getId()}. + * @param scopeId + * The {@link Job#getScopeId()}. + * @param jobId + * The {@link Job#getId()}. * @return {@code true} if {@link JbatchDriver} reports that is running, {@code false} otherwise. - * @throws JobCheckRunningException if {@link Job} running status cannot be checked. - * @throws KapuaEntityNotFoundException if {@link Job} does not exists. - * @throws KapuaException if any other error occurs. + * @throws JobCheckRunningException + * if {@link Job} running status cannot be checked. + * @throws KapuaEntityNotFoundException + * if {@link Job} does not exists. + * @throws KapuaException + * if any other error occurs. * @since 1.5.0 */ private boolean internalIsRunning(KapuaId scopeId, KapuaId jobId) throws KapuaException { diff --git a/job-engine/jbatch/src/main/java/org/eclipse/kapua/job/engine/jbatch/JobStartOptionsImpl.java b/job-engine/jbatch/src/main/java/org/eclipse/kapua/job/engine/jbatch/JobStartOptionsImpl.java deleted file mode 100644 index 20a7e805ef1..00000000000 --- a/job-engine/jbatch/src/main/java/org/eclipse/kapua/job/engine/jbatch/JobStartOptionsImpl.java +++ /dev/null @@ -1,138 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2018, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.job.engine.jbatch; - -import org.eclipse.kapua.job.engine.JobStartOptions; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.job.step.definition.JobStepProperty; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -/** - * {@link JobStartOptions} implementation. - * - * @since 1.0.0 - */ -public class JobStartOptionsImpl implements JobStartOptions { - - private static final long serialVersionUID = 5339966879340542119L; - - private Set targetIdSublist; - private List stepPropertiesOverrides; - private boolean resetStepIndex; - private Integer fromStepIndex; - private boolean enqueue; - - /** - * Constructor. - * - * @since 1.0.0 - */ - public JobStartOptionsImpl() { - } - - /** - * Clone constructor. - * - * @param jobStartOptions The {@link JobStartOptions} to clone. - * @since 1.1.0 - */ - public JobStartOptionsImpl(JobStartOptions jobStartOptions) { - this(); - - setTargetIdSublist(jobStartOptions.getTargetIdSublist()); - setResetStepIndex(jobStartOptions.getResetStepIndex()); - setFromStepIndex(jobStartOptions.getFromStepIndex()); - setEnqueue(jobStartOptions.getEnqueue()); - } - - @Override - public Set getTargetIdSublist() { - if (targetIdSublist == null) { - targetIdSublist = new HashSet<>(); - } - - return targetIdSublist; - } - - @Override - public void setTargetIdSublist(Set targetIdSublist) { - this.targetIdSublist = targetIdSublist; - } - - @Override - public void addTargetIdToSublist(KapuaId targetId) { - getTargetIdSublist().add(targetId); - } - - @Override - public void removeTargetIdToSublist(KapuaId targetId) { - getTargetIdSublist().remove(targetId); - } - - @Override - public List getStepPropertiesOverrides() { - if (stepPropertiesOverrides == null) { - stepPropertiesOverrides = new ArrayList<>(); - } - - return stepPropertiesOverrides; - } - - @Override - public void addStepPropertyOverride(JobStepProperty stepPropertyOverride) { - getStepPropertiesOverrides().add(stepPropertyOverride); - } - - @Override - public void setStepPropertiesOverrides(List stepPropertiesOverrides) { - this.stepPropertiesOverrides = new ArrayList<>(stepPropertiesOverrides); - } - - @Override - public boolean getResetStepIndex() { - return resetStepIndex; - } - - @Override - public void setResetStepIndex(boolean resetStepIndex) { - this.resetStepIndex = resetStepIndex; - } - - @Override - public Integer getFromStepIndex() { - return fromStepIndex; - } - - @Override - public void setFromStepIndex(Integer fromStepIndex) { - this.fromStepIndex = fromStepIndex; - } - - @Override - public boolean getEnqueue() { - return enqueue; - } - - @Override - public void setEnqueue(boolean enqueue) { - this.enqueue = enqueue; - } - - public static JobStartOptionsImpl parse(JobStartOptions jobStartOptions) { - return jobStartOptions != null ? (jobStartOptions instanceof JobStartOptionsImpl ? (JobStartOptionsImpl) jobStartOptions : new JobStartOptionsImpl(jobStartOptions)) : null; - } -} diff --git a/job-engine/jbatch/src/main/java/org/eclipse/kapua/job/engine/jbatch/JobengineJbatchModule.java b/job-engine/jbatch/src/main/java/org/eclipse/kapua/job/engine/jbatch/JobengineJbatchModule.java index 9404ae82a49..730de52c2a4 100644 --- a/job-engine/jbatch/src/main/java/org/eclipse/kapua/job/engine/jbatch/JobengineJbatchModule.java +++ b/job-engine/jbatch/src/main/java/org/eclipse/kapua/job/engine/jbatch/JobengineJbatchModule.java @@ -16,7 +16,6 @@ import javax.inject.Singleton; import org.eclipse.kapua.commons.core.AbstractKapuaModule; -import org.eclipse.kapua.job.engine.JobEngineFactory; import org.eclipse.kapua.job.engine.JobEngineService; import org.eclipse.kapua.job.engine.jbatch.driver.JbatchDriver; import org.eclipse.kapua.job.engine.jbatch.driver.utils.JobDefinitionBuildUtils; @@ -32,7 +31,6 @@ public class JobengineJbatchModule extends AbstractKapuaModule { @Override protected void configureModule() { - bind(JobEngineFactory.class).to(JobEngineFactoryJbatch.class).in(Singleton.class); bind(JobEngineService.class).to(JobEngineServiceJbatch.class).in(Singleton.class); bind(JobEngineSetting.class).in(Singleton.class); } diff --git a/job-engine/jbatch/src/main/java/org/eclipse/kapua/job/engine/jbatch/driver/JbatchDriver.java b/job-engine/jbatch/src/main/java/org/eclipse/kapua/job/engine/jbatch/driver/JbatchDriver.java index 832e94e5242..19eec12787e 100644 --- a/job-engine/jbatch/src/main/java/org/eclipse/kapua/job/engine/jbatch/driver/JbatchDriver.java +++ b/job-engine/jbatch/src/main/java/org/eclipse/kapua/job/engine/jbatch/driver/JbatchDriver.java @@ -54,13 +54,13 @@ import org.eclipse.kapua.job.engine.jbatch.persistence.JPAPersistenceManagerImpl; import org.eclipse.kapua.job.engine.jbatch.setting.JobEngineSettingKeys; import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.service.job.Job; import org.eclipse.kapua.service.job.execution.JobExecutionService; import org.eclipse.kapua.service.job.step.JobStep; import org.eclipse.kapua.service.job.step.JobStepAttributes; import org.eclipse.kapua.service.job.step.JobStepFactory; import org.eclipse.kapua.service.job.step.JobStepListResult; -import org.eclipse.kapua.service.job.step.JobStepQuery; import org.eclipse.kapua.service.job.step.JobStepService; import org.eclipse.kapua.service.job.step.definition.JobStepDefinition; import org.eclipse.kapua.service.job.step.definition.JobStepDefinitionService; @@ -153,7 +153,7 @@ public void startJob(@NotNull KapuaId scopeId, @NotNull KapuaId jobId, @NotNull String jobXmlDefinition; String jobName = JbatchDriver.getJbatchJobName(scopeId, jobId); try { - JobStepQuery query = jobStepFactory.newQuery(scopeId); + KapuaQuery query = new KapuaQuery(scopeId); query.setPredicate(query.attributePredicate(JobStepAttributes.JOB_ID, jobId)); JobStepListResult jobSteps = jobStepService.query(query); diff --git a/job-engine/jbatch/src/main/java/org/eclipse/kapua/job/engine/jbatch/listener/KapuaJobListener.java b/job-engine/jbatch/src/main/java/org/eclipse/kapua/job/engine/jbatch/listener/KapuaJobListener.java index 5a347e7630f..364c1c7c548 100644 --- a/job-engine/jbatch/src/main/java/org/eclipse/kapua/job/engine/jbatch/listener/KapuaJobListener.java +++ b/job-engine/jbatch/src/main/java/org/eclipse/kapua/job/engine/jbatch/listener/KapuaJobListener.java @@ -42,6 +42,7 @@ import org.eclipse.kapua.job.engine.queue.QueuedJobExecutionService; import org.eclipse.kapua.job.engine.queue.QueuedJobExecutionStatus; import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.model.query.SortOrder; import org.eclipse.kapua.model.query.predicate.AttributePredicate; import org.eclipse.kapua.service.job.Job; @@ -56,7 +57,6 @@ import org.eclipse.kapua.service.job.targets.JobTargetAttributes; import org.eclipse.kapua.service.job.targets.JobTargetFactory; import org.eclipse.kapua.service.job.targets.JobTargetListResult; -import org.eclipse.kapua.service.job.targets.JobTargetQuery; import org.eclipse.kapua.service.job.targets.JobTargetService; import org.eclipse.kapua.service.job.targets.JobTargetStatus; import org.slf4j.Logger; @@ -278,14 +278,14 @@ private JobExecution createJobExecution(KapuaId scopeId, KapuaId jobId, JobTarge Properties jobExecutionProperties = new Properties(); jobExecutionProperties.put(JBATCH_EXECUTION_ID, Long.toString(jBatchExecutionId)); - JobExecutionCreator jobExecutionCreator = jobExecutionFactory.newCreator(scopeId); + JobExecutionCreator jobExecutionCreator = new JobExecutionCreator(scopeId); jobExecutionCreator.setJobId(jobId); jobExecutionCreator.setStartedOn(new Date()); jobExecutionCreator.setEntityAttributes(jobExecutionProperties); if (jobTargetSublist.isEmpty()) { - JobTargetQuery jobTargetQuery = jobTargetFactory.newQuery(scopeId); + KapuaQuery jobTargetQuery = new KapuaQuery(scopeId); jobTargetQuery.setPredicate( jobTargetQuery.andPredicate( @@ -338,7 +338,7 @@ private JobExecution getAnotherJobExecutionRunning(KapuaId scopeId, KapuaId jobI List runningExecutionsIds = BatchRuntime.getJobOperator().getRunningExecutions(jobName); if (runningExecutionsIds.size() > 1) { - JobExecutionQuery jobExecutionQuery = jobExecutionFactory.newQuery(scopeId); + JobExecutionQuery jobExecutionQuery = new JobExecutionQuery(scopeId); jobExecutionQuery.setPredicate( jobExecutionQuery.andPredicate( @@ -377,7 +377,7 @@ private JobExecution getAnotherJobExecutionRunning(KapuaId scopeId, KapuaId jobI */ private QueuedJobExecution enqueueJobExecution(KapuaId scopeId, KapuaId jobId, KapuaId jobExecutionId, KapuaId runningJobExecutionId) throws KapuaException { - QueuedJobExecutionCreator queuedJobExecutionCreator = queuedJobExecutionFactory.newCreator(scopeId); + QueuedJobExecutionCreator queuedJobExecutionCreator = new QueuedJobExecutionCreator(scopeId); queuedJobExecutionCreator.setJobId(jobId); queuedJobExecutionCreator.setJobExecutionId(jobExecutionId); queuedJobExecutionCreator.setWaitForJobExecutionId(runningJobExecutionId); diff --git a/job-engine/jbatch/src/main/java/org/eclipse/kapua/job/engine/jbatch/listener/QueuedJobExecutionCheckTask.java b/job-engine/jbatch/src/main/java/org/eclipse/kapua/job/engine/jbatch/listener/QueuedJobExecutionCheckTask.java index 9968e4dac2c..13be4ff8532 100644 --- a/job-engine/jbatch/src/main/java/org/eclipse/kapua/job/engine/jbatch/listener/QueuedJobExecutionCheckTask.java +++ b/job-engine/jbatch/src/main/java/org/eclipse/kapua/job/engine/jbatch/listener/QueuedJobExecutionCheckTask.java @@ -12,8 +12,8 @@ *******************************************************************************/ package org.eclipse.kapua.job.engine.jbatch.listener; -import org.eclipse.kapua.commons.model.query.predicate.AndPredicateImpl; -import org.eclipse.kapua.commons.model.query.predicate.AttributePredicateImpl; +import java.util.TimerTask; + import org.eclipse.kapua.commons.security.KapuaSecurityUtils; import org.eclipse.kapua.job.engine.JobEngineService; import org.eclipse.kapua.job.engine.jbatch.setting.JobEngineSetting; @@ -22,15 +22,15 @@ import org.eclipse.kapua.job.engine.queue.QueuedJobExecutionAttributes; import org.eclipse.kapua.job.engine.queue.QueuedJobExecutionFactory; import org.eclipse.kapua.job.engine.queue.QueuedJobExecutionListResult; -import org.eclipse.kapua.job.engine.queue.QueuedJobExecutionQuery; import org.eclipse.kapua.job.engine.queue.QueuedJobExecutionService; import org.eclipse.kapua.job.engine.queue.QueuedJobExecutionStatus; import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.query.KapuaQuery; +import org.eclipse.kapua.model.query.predicate.AndPredicate; +import org.eclipse.kapua.model.query.predicate.AttributePredicate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.TimerTask; - public class QueuedJobExecutionCheckTask extends TimerTask { private static final Logger LOG = LoggerFactory.getLogger(QueuedJobExecutionCheckTask.class); @@ -64,12 +64,12 @@ public void run() { LOG.info("Checking Job Execution queue for: {}...", jobExecutionId); try { - QueuedJobExecutionQuery query = queuedJobExecutionFactory.newQuery(scopeId); + KapuaQuery query = new KapuaQuery(scopeId); query.setPredicate( - new AndPredicateImpl( - new AttributePredicateImpl<>(QueuedJobExecutionAttributes.JOB_ID, jobId), - new AttributePredicateImpl<>(QueuedJobExecutionAttributes.WAIT_FOR_JOB_EXECUTION_ID, jobExecutionId) + new AndPredicate( + new AttributePredicate<>(QueuedJobExecutionAttributes.JOB_ID, jobId), + new AttributePredicate<>(QueuedJobExecutionAttributes.WAIT_FOR_JOB_EXECUTION_ID, jobExecutionId) ) ); diff --git a/job-engine/jbatch/src/main/java/org/eclipse/kapua/job/engine/queue/jbatch/JobEngineQueueJbatchModule.java b/job-engine/jbatch/src/main/java/org/eclipse/kapua/job/engine/queue/jbatch/JobEngineQueueJbatchModule.java index b66193d480d..eb1bdfdb9d7 100644 --- a/job-engine/jbatch/src/main/java/org/eclipse/kapua/job/engine/queue/jbatch/JobEngineQueueJbatchModule.java +++ b/job-engine/jbatch/src/main/java/org/eclipse/kapua/job/engine/queue/jbatch/JobEngineQueueJbatchModule.java @@ -12,7 +12,8 @@ *******************************************************************************/ package org.eclipse.kapua.job.engine.queue.jbatch; -import com.google.inject.Provides; +import javax.inject.Singleton; + import org.eclipse.kapua.commons.core.AbstractKapuaModule; import org.eclipse.kapua.commons.jpa.KapuaJpaRepositoryConfiguration; import org.eclipse.kapua.commons.jpa.KapuaJpaTxManagerFactory; @@ -22,11 +23,11 @@ import org.eclipse.kapua.job.engine.queue.QueuedJobExecutionRepository; import org.eclipse.kapua.job.engine.queue.QueuedJobExecutionService; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; -import javax.inject.Singleton; +import com.google.inject.Provides; public class JobEngineQueueJbatchModule extends AbstractKapuaModule { + @Override protected void configureModule() { bind(QueuedJobExecutionFactory.class).to(QueuedJobExecutionFactoryImpl.class); @@ -37,12 +38,10 @@ protected void configureModule() { @Singleton QueuedJobExecutionService queuedJobExecutionService( AuthorizationService authorizationService, - PermissionFactory permissionFactory, QueuedJobExecutionRepository repository, KapuaJpaTxManagerFactory jpaTxManagerFactory) { return new QueuedJobExecutionServiceImpl( authorizationService, - permissionFactory, jpaTxManagerFactory.create("kapua-job-engine"), repository); } diff --git a/job-engine/jbatch/src/main/java/org/eclipse/kapua/job/engine/queue/jbatch/QueuedJobExecutionCreatorImpl.java b/job-engine/jbatch/src/main/java/org/eclipse/kapua/job/engine/queue/jbatch/QueuedJobExecutionCreatorImpl.java deleted file mode 100644 index 4962add3d41..00000000000 --- a/job-engine/jbatch/src/main/java/org/eclipse/kapua/job/engine/queue/jbatch/QueuedJobExecutionCreatorImpl.java +++ /dev/null @@ -1,84 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2019, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.job.engine.queue.jbatch; - -import org.eclipse.kapua.commons.model.AbstractKapuaUpdatableEntityCreator; -import org.eclipse.kapua.job.engine.queue.QueuedJobExecution; -import org.eclipse.kapua.job.engine.queue.QueuedJobExecutionCreator; -import org.eclipse.kapua.job.engine.queue.QueuedJobExecutionStatus; -import org.eclipse.kapua.model.id.KapuaId; - -/** - * {@link QueuedJobExecutionCreator} implementation - * - * @since 1.0.0 - */ -public class QueuedJobExecutionCreatorImpl extends AbstractKapuaUpdatableEntityCreator implements QueuedJobExecutionCreator { - - private static final long serialVersionUID = 3119071638220738358L; - - private KapuaId jobId; - private KapuaId jobExecutionId; - private KapuaId waitForJobExecutionId; - private QueuedJobExecutionStatus status; - - /** - * Constructor. - * - * @param scopeId The scope {@link KapuaId} to set into the {@link QueuedJobExecutionCreator}. - * @since 1.1.0 - */ - protected QueuedJobExecutionCreatorImpl(KapuaId scopeId) { - super(scopeId); - } - - @Override - public KapuaId getJobId() { - return jobId; - } - - @Override - public void setJobId(KapuaId jobId) { - this.jobId = jobId; - } - - @Override - public KapuaId getJobExecutionId() { - return jobExecutionId; - } - - @Override - public void setJobExecutionId(KapuaId jobExecutionId) { - this.jobExecutionId = jobExecutionId; - } - - @Override - public KapuaId getWaitForJobExecutionId() { - return waitForJobExecutionId; - } - - @Override - public void setWaitForJobExecutionId(KapuaId waitForJobExecutionId) { - this.waitForJobExecutionId = waitForJobExecutionId; - } - - @Override - public QueuedJobExecutionStatus getStatus() { - return status; - } - - @Override - public void setStatus(QueuedJobExecutionStatus status) { - this.status = status; - } -} diff --git a/job-engine/jbatch/src/main/java/org/eclipse/kapua/job/engine/queue/jbatch/QueuedJobExecutionFactoryImpl.java b/job-engine/jbatch/src/main/java/org/eclipse/kapua/job/engine/queue/jbatch/QueuedJobExecutionFactoryImpl.java index fd5c6642390..9e0db656e1a 100644 --- a/job-engine/jbatch/src/main/java/org/eclipse/kapua/job/engine/queue/jbatch/QueuedJobExecutionFactoryImpl.java +++ b/job-engine/jbatch/src/main/java/org/eclipse/kapua/job/engine/queue/jbatch/QueuedJobExecutionFactoryImpl.java @@ -12,16 +12,13 @@ *******************************************************************************/ package org.eclipse.kapua.job.engine.queue.jbatch; +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaEntityCloneException; import org.eclipse.kapua.job.engine.queue.QueuedJobExecution; -import org.eclipse.kapua.job.engine.queue.QueuedJobExecutionCreator; import org.eclipse.kapua.job.engine.queue.QueuedJobExecutionFactory; -import org.eclipse.kapua.job.engine.queue.QueuedJobExecutionListResult; -import org.eclipse.kapua.job.engine.queue.QueuedJobExecutionQuery; import org.eclipse.kapua.model.id.KapuaId; -import javax.inject.Singleton; - /** * {@link QueuedJobExecutionFactory} implementation. * @@ -35,21 +32,6 @@ public QueuedJobExecution newEntity(KapuaId scopeId) { return new QueuedJobExecutionImpl(scopeId); } - @Override - public QueuedJobExecutionCreator newCreator(KapuaId scopeId) { - return new QueuedJobExecutionCreatorImpl(scopeId); - } - - @Override - public QueuedJobExecutionQuery newQuery(KapuaId scopeId) { - return new QueuedJobExecutionQueryImpl(scopeId); - } - - @Override - public QueuedJobExecutionListResult newListResult() { - return new QueuedJobExecutionListResultImpl(); - } - @Override public QueuedJobExecution clone(QueuedJobExecution queuedJobExecution) { try { diff --git a/job-engine/jbatch/src/main/java/org/eclipse/kapua/job/engine/queue/jbatch/QueuedJobExecutionImplJpaRepository.java b/job-engine/jbatch/src/main/java/org/eclipse/kapua/job/engine/queue/jbatch/QueuedJobExecutionImplJpaRepository.java index a5956470dbf..d4b98e6d520 100644 --- a/job-engine/jbatch/src/main/java/org/eclipse/kapua/job/engine/queue/jbatch/QueuedJobExecutionImplJpaRepository.java +++ b/job-engine/jbatch/src/main/java/org/eclipse/kapua/job/engine/queue/jbatch/QueuedJobExecutionImplJpaRepository.java @@ -22,7 +22,8 @@ public class QueuedJobExecutionImplJpaRepository extends KapuaUpdatableEntityJpaRepository implements QueuedJobExecutionRepository { + public QueuedJobExecutionImplJpaRepository(KapuaJpaRepositoryConfiguration jpaRepoConfig) { - super(QueuedJobExecutionImpl.class, JobExecution.TYPE, () -> new QueuedJobExecutionListResultImpl(), jpaRepoConfig); + super(QueuedJobExecutionImpl.class, JobExecution.TYPE, () -> new QueuedJobExecutionListResult(), jpaRepoConfig); } } diff --git a/job-engine/jbatch/src/main/java/org/eclipse/kapua/job/engine/queue/jbatch/QueuedJobExecutionListResultImpl.java b/job-engine/jbatch/src/main/java/org/eclipse/kapua/job/engine/queue/jbatch/QueuedJobExecutionListResultImpl.java deleted file mode 100644 index d7a642d35d0..00000000000 --- a/job-engine/jbatch/src/main/java/org/eclipse/kapua/job/engine/queue/jbatch/QueuedJobExecutionListResultImpl.java +++ /dev/null @@ -1,26 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2019, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.job.engine.queue.jbatch; - -import org.eclipse.kapua.commons.model.query.KapuaListResultImpl; -import org.eclipse.kapua.job.engine.queue.QueuedJobExecution; -import org.eclipse.kapua.job.engine.queue.QueuedJobExecutionListResult; - -/** - * {@link QueuedJobExecutionListResult} implementation. - * - * @since 1.1.0 - */ -public class QueuedJobExecutionListResultImpl extends KapuaListResultImpl implements QueuedJobExecutionListResult { - -} diff --git a/job-engine/jbatch/src/main/java/org/eclipse/kapua/job/engine/queue/jbatch/QueuedJobExecutionQueryImpl.java b/job-engine/jbatch/src/main/java/org/eclipse/kapua/job/engine/queue/jbatch/QueuedJobExecutionQueryImpl.java deleted file mode 100644 index e58f97796e2..00000000000 --- a/job-engine/jbatch/src/main/java/org/eclipse/kapua/job/engine/queue/jbatch/QueuedJobExecutionQueryImpl.java +++ /dev/null @@ -1,35 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2019, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.job.engine.queue.jbatch; - -import org.eclipse.kapua.commons.model.query.AbstractKapuaQuery; -import org.eclipse.kapua.job.engine.queue.QueuedJobExecutionQuery; -import org.eclipse.kapua.model.id.KapuaId; - -/** - * {@link QueuedJobExecutionQuery} implementation. - * - * @since 1.1.0 - */ -public class QueuedJobExecutionQueryImpl extends AbstractKapuaQuery implements QueuedJobExecutionQuery { - - /** - * Constructor. - * - * @param scopeId The {@link #getScopeId()}. - * @since 1.1.0 - */ - public QueuedJobExecutionQueryImpl(KapuaId scopeId) { - super(scopeId); - } -} diff --git a/job-engine/jbatch/src/main/java/org/eclipse/kapua/job/engine/queue/jbatch/QueuedJobExecutionServiceImpl.java b/job-engine/jbatch/src/main/java/org/eclipse/kapua/job/engine/queue/jbatch/QueuedJobExecutionServiceImpl.java index dd90911d46d..2721de8a9be 100644 --- a/job-engine/jbatch/src/main/java/org/eclipse/kapua/job/engine/queue/jbatch/QueuedJobExecutionServiceImpl.java +++ b/job-engine/jbatch/src/main/java/org/eclipse/kapua/job/engine/queue/jbatch/QueuedJobExecutionServiceImpl.java @@ -12,6 +12,8 @@ *******************************************************************************/ package org.eclipse.kapua.job.engine.queue.jbatch; +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.commons.model.domains.Domains; import org.eclipse.kapua.commons.util.ArgumentValidator; @@ -24,11 +26,9 @@ import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; +import org.eclipse.kapua.service.authorization.permission.Permission; import org.eclipse.kapua.storage.TxManager; -import javax.inject.Singleton; - /** * {@link QueuedJobExecutionService} implementation */ @@ -36,17 +36,14 @@ public class QueuedJobExecutionServiceImpl implements QueuedJobExecutionService { private final AuthorizationService authorizationService; - private final PermissionFactory permissionFactory; private final TxManager txManager; private final QueuedJobExecutionRepository repository; public QueuedJobExecutionServiceImpl( AuthorizationService authorizationService, - PermissionFactory permissionFactory, TxManager txManager, QueuedJobExecutionRepository repository) { this.authorizationService = authorizationService; - this.permissionFactory = permissionFactory; this.txManager = txManager; this.repository = repository; } @@ -57,7 +54,7 @@ public QueuedJobExecution create(QueuedJobExecutionCreator creator) throws Kapua ArgumentValidator.notNull(creator, "queuedJobExecutionCreator"); ArgumentValidator.notNull(creator.getScopeId(), "queuedJobExecutionCreator.scopeId"); // Check access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.write, null)); + authorizationService.checkPermission(new Permission(Domains.JOB, Actions.write, null)); QueuedJobExecution queuedJobExecutionImpl = new QueuedJobExecutionImpl(creator.getScopeId()); queuedJobExecutionImpl.setJobId(creator.getJobId()); @@ -74,7 +71,7 @@ public QueuedJobExecution update(QueuedJobExecution queuedJobExecution) throws K ArgumentValidator.notNull(queuedJobExecution, "queuedJobExecution"); ArgumentValidator.notNull(queuedJobExecution.getScopeId(), "queuedJobExecution.scopeId"); // Check access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.write, null)); + authorizationService.checkPermission(new Permission(Domains.JOB, Actions.write, null)); return txManager.execute(tx -> repository.update(tx, queuedJobExecution)); } @@ -85,7 +82,7 @@ public QueuedJobExecution find(KapuaId scopeId, KapuaId queuedJobExecutionId) th ArgumentValidator.notNull(scopeId, "scopeId"); ArgumentValidator.notNull(queuedJobExecutionId, "queuedJobExecutionId"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.read, scopeId)); + authorizationService.checkPermission(new Permission(Domains.JOB, Actions.read, scopeId)); // Do find return txManager.execute(tx -> repository.find(tx, scopeId, queuedJobExecutionId)) .orElse(null); @@ -96,7 +93,7 @@ public QueuedJobExecutionListResult query(KapuaQuery query) throws KapuaExceptio // Argument Validation ArgumentValidator.notNull(query, "query"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.read, query.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.JOB, Actions.read, query.getScopeId())); // Do query return txManager.execute(tx -> repository.query(tx, query)); } @@ -106,7 +103,7 @@ public long count(KapuaQuery query) throws KapuaException { // Argument Validation ArgumentValidator.notNull(query, "query"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.read, query.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.JOB, Actions.read, query.getScopeId())); // Do query return txManager.execute(tx -> repository.count(tx, query)); } @@ -117,7 +114,7 @@ public void delete(KapuaId scopeId, KapuaId queuedJobExecutionId) throws KapuaEx ArgumentValidator.notNull(scopeId, "scopeId"); ArgumentValidator.notNull(queuedJobExecutionId, "queuedJobExecutionId"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.delete, scopeId)); + authorizationService.checkPermission(new Permission(Domains.JOB, Actions.delete, scopeId)); // Do delete txManager.execute(tx -> repository.delete(tx, scopeId, queuedJobExecutionId)); } diff --git a/job-engine/pom.xml b/job-engine/pom.xml index 8492a9ff8e0..69f6b85131d 100644 --- a/job-engine/pom.xml +++ b/job-engine/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-job-engine diff --git a/locator/guice/pom.xml b/locator/guice/pom.xml index baab0c418bc..bff3fd4af7f 100644 --- a/locator/guice/pom.xml +++ b/locator/guice/pom.xml @@ -19,7 +19,7 @@ org.eclipse.kapua kapua-locator - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-locator-guice diff --git a/locator/guice/src/main/java/org/eclipse/kapua/locator/guice/FactoryResolver.java b/locator/guice/src/main/java/org/eclipse/kapua/locator/guice/FactoryResolver.java deleted file mode 100644 index 6a58d76c786..00000000000 --- a/locator/guice/src/main/java/org/eclipse/kapua/locator/guice/FactoryResolver.java +++ /dev/null @@ -1,48 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - * Red Hat Inc - *******************************************************************************/ -package org.eclipse.kapua.locator.guice; - -import org.eclipse.kapua.locator.KapuaLocatorErrorCodes; -import org.eclipse.kapua.locator.KapuaLocatorException; -import org.eclipse.kapua.model.KapuaObjectFactory; - -public class FactoryResolver { - - private final Class factoryClass; - private final Class implementationClass; - - private FactoryResolver(Class factory, Class implementation) { - this.factoryClass = factory; - this.implementationClass = implementation; - } - - @SuppressWarnings("unchecked") - public static FactoryResolver newInstance(Class factory, Class implementation) - throws KapuaLocatorException { - if (!factory.isAssignableFrom(implementation)) { - throw new KapuaLocatorException(KapuaLocatorErrorCodes.FACTORY_PROVIDER_INVALID, implementation, factory); - } - - return new FactoryResolver((Class)factory, (Class)implementation); - } - - public Class getFactoryClass() { - return factoryClass; - } - - public Class getImplementationClass() { - return implementationClass; - } - -} diff --git a/locator/pom.xml b/locator/pom.xml index 7862d0572b9..7743eb1e026 100644 --- a/locator/pom.xml +++ b/locator/pom.xml @@ -19,7 +19,7 @@ org.eclipse.kapua kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-locator diff --git a/message/api/pom.xml b/message/api/pom.xml index 81501ecf2d9..5abe58a65b6 100644 --- a/message/api/pom.xml +++ b/message/api/pom.xml @@ -19,7 +19,7 @@ org.eclipse.kapua kapua-message - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-message-api diff --git a/message/internal/pom.xml b/message/internal/pom.xml index fd46f4e7672..56e64736a67 100644 --- a/message/internal/pom.xml +++ b/message/internal/pom.xml @@ -19,7 +19,7 @@ org.eclipse.kapua kapua-message - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-message-internal diff --git a/message/pom.xml b/message/pom.xml index d205e851a95..6a8da023be7 100644 --- a/message/pom.xml +++ b/message/pom.xml @@ -19,7 +19,7 @@ org.eclipse.kapua kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT pom diff --git a/plug-ins/pom.xml b/plug-ins/pom.xml index c06224fcb5f..e7584889099 100644 --- a/plug-ins/pom.xml +++ b/plug-ins/pom.xml @@ -21,7 +21,7 @@ org.eclipse.kapua kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT pom diff --git a/plug-ins/sso/openid-connect/api/pom.xml b/plug-ins/sso/openid-connect/api/pom.xml index 792bf68b14e..b0fab85f5bc 100644 --- a/plug-ins/sso/openid-connect/api/pom.xml +++ b/plug-ins/sso/openid-connect/api/pom.xml @@ -20,7 +20,7 @@ org.eclipse.kapua kapua-openid-connect - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-openid-api diff --git a/plug-ins/sso/openid-connect/pom.xml b/plug-ins/sso/openid-connect/pom.xml index 44d0dddeb72..80a8a71c3e9 100644 --- a/plug-ins/sso/openid-connect/pom.xml +++ b/plug-ins/sso/openid-connect/pom.xml @@ -21,7 +21,7 @@ org.eclipse.kapua kapua-sso - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT pom diff --git a/plug-ins/sso/openid-connect/provider-generic/pom.xml b/plug-ins/sso/openid-connect/provider-generic/pom.xml index f10b49f8c42..e5ba59fd808 100644 --- a/plug-ins/sso/openid-connect/provider-generic/pom.xml +++ b/plug-ins/sso/openid-connect/provider-generic/pom.xml @@ -21,7 +21,7 @@ org.eclipse.kapua kapua-openid-connect - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-openid-provider-generic diff --git a/plug-ins/sso/openid-connect/provider-keycloak/pom.xml b/plug-ins/sso/openid-connect/provider-keycloak/pom.xml index 6b6c3149857..55e0cad140f 100644 --- a/plug-ins/sso/openid-connect/provider-keycloak/pom.xml +++ b/plug-ins/sso/openid-connect/provider-keycloak/pom.xml @@ -21,7 +21,7 @@ org.eclipse.kapua kapua-openid-connect - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-openid-provider-keycloak diff --git a/plug-ins/sso/openid-connect/provider/pom.xml b/plug-ins/sso/openid-connect/provider/pom.xml index 4bae8fdb2e0..075dc9db901 100644 --- a/plug-ins/sso/openid-connect/provider/pom.xml +++ b/plug-ins/sso/openid-connect/provider/pom.xml @@ -20,7 +20,7 @@ org.eclipse.kapua kapua-openid-connect - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-openid-provider diff --git a/plug-ins/sso/pom.xml b/plug-ins/sso/pom.xml index dc4f6e12d07..f0a709d7278 100644 --- a/plug-ins/sso/pom.xml +++ b/plug-ins/sso/pom.xml @@ -21,7 +21,7 @@ org.eclipse.kapua kapua-plug-ins - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT pom diff --git a/pom.xml b/pom.xml index 34565661301..29453bc72c1 100644 --- a/pom.xml +++ b/pom.xml @@ -17,7 +17,7 @@ org.eclipse.kapua kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua pom diff --git a/qa/common/pom.xml b/qa/common/pom.xml index 931fb57cf78..4cfb028397d 100644 --- a/qa/common/pom.xml +++ b/qa/common/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-qa - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-qa-common @@ -172,8 +172,8 @@ camel-jms-starter - org.apache.geronimo.specs - geronimo-jms_1.1_spec + org.apache.geronimo.specs + geronimo-jms_1.1_spec diff --git a/qa/common/src/main/java/org/eclipse/kapua/qa/common/SimulatedDeviceSteps.java b/qa/common/src/main/java/org/eclipse/kapua/qa/common/SimulatedDeviceSteps.java index 1adb387029e..be030528a98 100644 --- a/qa/common/src/main/java/org/eclipse/kapua/qa/common/SimulatedDeviceSteps.java +++ b/qa/common/src/main/java/org/eclipse/kapua/qa/common/SimulatedDeviceSteps.java @@ -27,6 +27,8 @@ import java.util.concurrent.ScheduledExecutorService; import java.util.stream.Collectors; +import javax.inject.Inject; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.kura.simulator.GatewayConfiguration; import org.eclipse.kapua.kura.simulator.MqttAsyncTransport; @@ -36,11 +38,10 @@ import org.eclipse.kapua.kura.simulator.app.command.SimpleCommandApplication; import org.eclipse.kapua.kura.simulator.app.deploy.SimpleDeployApplication; import org.eclipse.kapua.locator.KapuaLocator; -import org.eclipse.kapua.service.authentication.CredentialsFactory; +import org.eclipse.kapua.service.authentication.UsernamePasswordCredentials; import org.eclipse.kapua.service.device.management.bundle.DeviceBundle; import org.eclipse.kapua.service.device.management.bundle.DeviceBundleManagementService; import org.eclipse.kapua.service.device.management.bundle.DeviceBundles; -import org.eclipse.kapua.service.device.management.packages.DevicePackageFactory; import org.eclipse.kapua.service.device.management.packages.DevicePackageManagementService; import org.eclipse.kapua.service.device.management.packages.model.DevicePackage; import org.eclipse.kapua.service.device.management.packages.model.DevicePackageBundleInfo; @@ -61,8 +62,6 @@ import com.google.inject.Singleton; -import javax.inject.Inject; - import io.cucumber.java.After; import io.cucumber.java.Before; import io.cucumber.java.Scenario; @@ -122,7 +121,7 @@ public void setNodeUri(String nodeUri) { @Given("My credentials are username {string} and password {string}") public void setUsernamePasswordCredentials(String username, String password) { - session.setCredentials(KapuaLocator.getInstance().getFactory(CredentialsFactory.class).newUsernamePasswordCredentials(username, password)); + session.setCredentials(new UsernamePasswordCredentials(username, password)); } @When("I start the simulator") @@ -334,7 +333,7 @@ public void downloadPackage(final String packageName, final String version, fina With.withDevice(account, currentDevice.getClientId(), device -> { final DevicePackageManagementService service = KapuaLocator.getInstance().getService(DevicePackageManagementService.class); - final DevicePackageDownloadRequest request = KapuaLocator.getInstance().getFactory(DevicePackageFactory.class).newPackageDownloadRequest(); + final DevicePackageDownloadRequest request = new DevicePackageDownloadRequest(); request.setInstall(true); request.setName(packageName); request.setVersion(version); diff --git a/qa/common/src/main/java/org/eclipse/kapua/qa/common/TestJAXBContextProvider.java b/qa/common/src/main/java/org/eclipse/kapua/qa/common/TestJAXBContextProvider.java index 7ba9f1673e5..2ef06aefb96 100644 --- a/qa/common/src/main/java/org/eclipse/kapua/qa/common/TestJAXBContextProvider.java +++ b/qa/common/src/main/java/org/eclipse/kapua/qa/common/TestJAXBContextProvider.java @@ -36,7 +36,6 @@ import org.eclipse.kapua.commons.util.xml.JAXBContextProvider; import org.eclipse.kapua.event.ServiceEvent; import org.eclipse.kapua.job.engine.JobStartOptions; -import org.eclipse.kapua.job.engine.client.JobStartOptionsClient; import org.eclipse.kapua.job.engine.commons.model.JobStepPropertiesOverrides; import org.eclipse.kapua.job.engine.commons.model.JobTargetSublist; import org.eclipse.kapua.model.config.metatype.KapuaTad; @@ -46,6 +45,7 @@ import org.eclipse.kapua.model.config.metatype.KapuaTobject; import org.eclipse.kapua.model.config.metatype.KapuaTocd; import org.eclipse.kapua.model.config.metatype.KapuaToption; +import org.eclipse.kapua.model.config.metatype.KapuaTscalar; import org.eclipse.kapua.service.authentication.token.AccessToken; import org.eclipse.kapua.service.device.call.kura.model.bundle.KuraBundle; import org.eclipse.kapua.service.device.call.kura.model.bundle.KuraBundles; @@ -78,7 +78,6 @@ import org.eclipse.kapua.service.device.management.inventory.model.container.DeviceInventoryContainers; import org.eclipse.kapua.service.device.management.inventory.model.inventory.DeviceInventory; import org.eclipse.kapua.service.device.management.inventory.model.inventory.DeviceInventoryItem; -import org.eclipse.kapua.service.device.management.inventory.model.inventory.DeviceInventoryXmlRegistry; import org.eclipse.kapua.service.device.management.inventory.model.packages.DeviceInventoryPackage; import org.eclipse.kapua.service.device.management.inventory.model.packages.DeviceInventoryPackages; import org.eclipse.kapua.service.device.management.inventory.model.system.DeviceInventorySystemPackage; @@ -91,7 +90,6 @@ import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystoreItemQuery; import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystoreItems; import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystoreKeypair; -import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystoreXmlRegistry; import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystores; import org.eclipse.kapua.service.device.management.packages.model.DevicePackages; import org.eclipse.kapua.service.device.management.packages.model.download.DevicePackageDownloadRequest; @@ -107,8 +105,7 @@ import org.slf4j.LoggerFactory; /** - * JAXB context provided for proper (un)marshalling of interface annotated classes. - * This particular implementation is used only in unit and integration tests. + * JAXB context provided for proper (un)marshalling of interface annotated classes. This particular implementation is used only in unit and integration tests. *

    * Application and interfaces have their own implementation of provider. */ @@ -126,6 +123,7 @@ public JAXBContext getJAXBContext() throws KapuaException { KapuaTocd.class, KapuaTad.class, KapuaTicon.class, + KapuaTscalar.class, KapuaToption.class, KapuaTdesignate.class, KapuaTobject.class, @@ -144,7 +142,6 @@ public JAXBContext getJAXBContext() throws KapuaException { JobXmlRegistry.class, // Job Engine - JobStartOptionsClient.class, JobStartOptions.class, JobTargetSublist.class, IsJobRunningResponse.class, @@ -186,7 +183,6 @@ public JAXBContext getJAXBContext() throws KapuaException { DeviceInventorySystemPackage.class, KuraInventorySystemPackages.class, KuraInventorySystemPackage.class, - DeviceInventoryXmlRegistry.class, // Device Management Keystore DeviceKeystore.class, @@ -197,7 +193,6 @@ public JAXBContext getJAXBContext() throws KapuaException { DeviceKeystoreItemQuery.class, DeviceKeystoreItems.class, DeviceKeystoreKeypair.class, - DeviceKeystoreXmlRegistry.class, DeviceKeystores.class, KuraDeviceComponentConfiguration.class, diff --git a/qa/integration-steps/pom.xml b/qa/integration-steps/pom.xml index af9e8f2e8ae..a96e71ae72a 100644 --- a/qa/integration-steps/pom.xml +++ b/qa/integration-steps/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-qa - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-qa-integration-steps diff --git a/qa/integration-steps/src/main/java/org/eclipse/kapua/qa/integration/steps/DockerSteps.java b/qa/integration-steps/src/main/java/org/eclipse/kapua/qa/integration/steps/DockerSteps.java index 02ed2367c94..05f0f3fad3a 100644 --- a/qa/integration-steps/src/main/java/org/eclipse/kapua/qa/integration/steps/DockerSteps.java +++ b/qa/integration-steps/src/main/java/org/eclipse/kapua/qa/integration/steps/DockerSteps.java @@ -12,6 +12,34 @@ *******************************************************************************/ package org.eclipse.kapua.qa.integration.steps; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +import javax.inject.Inject; + +import org.eclipse.kapua.commons.core.ServiceModuleBundle; +import org.eclipse.kapua.locator.KapuaLocator; +import org.eclipse.kapua.qa.common.BasicSteps; +import org.eclipse.kapua.qa.common.DBHelper; +import org.eclipse.kapua.qa.common.StepData; +import org.eclipse.kapua.qa.integration.steps.utils.TestReadinessHttpConnection; +import org.eclipse.kapua.qa.integration.steps.utils.TestReadinessMqttBrokerConnection; +import org.eclipse.paho.client.mqttv3.MqttException; +import org.junit.Assert; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.Lists; import com.google.inject.Singleton; @@ -32,35 +60,10 @@ import com.spotify.docker.client.messages.NetworkConfig; import com.spotify.docker.client.messages.NetworkCreation; import com.spotify.docker.client.messages.PortBinding; + import io.cucumber.java.en.And; import io.cucumber.java.en.Given; import io.cucumber.java.en.Then; -import org.eclipse.kapua.commons.core.ServiceModuleBundle; -import org.eclipse.kapua.locator.KapuaLocator; -import org.eclipse.kapua.qa.common.BasicSteps; -import org.eclipse.kapua.qa.common.DBHelper; -import org.eclipse.kapua.qa.common.StepData; -import org.eclipse.kapua.qa.integration.steps.utils.TestReadinessHttpConnection; -import org.eclipse.kapua.qa.integration.steps.utils.TestReadinessMqttBrokerConnection; -import org.eclipse.paho.client.mqttv3.MqttException; -import org.junit.Assert; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.inject.Inject; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.net.HttpURLConnection; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.TimeUnit; @Singleton public class DockerSteps { @@ -68,7 +71,7 @@ public class DockerSteps { private static final Logger logger = LoggerFactory.getLogger(DockerSteps.class); private static final String NETWORK_PREFIX = "kapua-net"; - private static final String KAPUA_VERSION = "2.1.0-SNAPSHOT"; + private static final String KAPUA_VERSION = "2.1.0-FALSE_EXTENSIONS-SNAPSHOT"; private static final String ES_IMAGE = "elasticsearch:7.8.1"; private static final String BROKER_IMAGE = "kapua-broker-artemis"; private static final String LIFECYCLE_CONSUMER_IMAGE = "kapua-consumer-lifecycle"; @@ -148,7 +151,6 @@ public class DockerSteps { private static final String ALL_IP = "0.0.0.0"; - @Inject public DockerSteps(StepData stepData, DBHelper database) { this.stepData = stepData; @@ -260,7 +262,8 @@ public void startFullDockerEnvironment() throws Exception { * TODO: Add missing Telemetry mapping * TODO: Move to start multiple resources and check readiness of components in parallel * - * @param dockerContainers The Docker containers to start + * @param dockerContainers + * The Docker containers to start * @throws Exception * @since 2.1.0 */ @@ -275,58 +278,68 @@ public void startDockerEnvironmentWithResources(List dockerContainers) t // Start them for (String dockerContainer : dockerContainers) { switch (dockerContainer) { - case "db": { - startDBContainer(BasicSteps.DB_CONTAINER_NAME); - - // This is the only container that we need to wait to start before starting others - waitDBContainer(BasicSteps.DB_CONTAINER_NAME); - } break; - case "es": { - startESContainer(BasicSteps.ES_CONTAINER_NAME); - waitEsContainer(BasicSteps.ES_CONTAINER_NAME); - } break; - case "events-broker": { - startEventBrokerContainer(BasicSteps.EVENTS_BROKER_CONTAINER_NAME); - waitEventBrokerContainer(BasicSteps.EVENTS_BROKER_CONTAINER_NAME); - } break; - case "job-engine": { - startJobEngineContainer(BasicSteps.JOB_ENGINE_CONTAINER_NAME); - waitJobEngineContainer(BasicSteps.JOB_ENGINE_CONTAINER_NAME); - } break; - case "message-broker": { - startMessageBrokerContainer(BasicSteps.MESSAGE_BROKER_CONTAINER_NAME); - waitMessageBrokerContainer(BasicSteps.MESSAGE_BROKER_CONTAINER_NAME); - } break; - case "broker-auth-service": { - startAuthServiceContainer(BasicSteps.AUTH_SERVICE_CONTAINER_NAME); - } break; - case "consumer-lifecycle": { - startLifecycleConsumerContainer(BasicSteps.LIFECYCLE_CONSUMER_CONTAINER_NAME); - } break; - default: - throw new UnsupportedOperationException("Unknown container resource: " + dockerContainer); + case "db": { + startDBContainer(BasicSteps.DB_CONTAINER_NAME); + + // This is the only container that we need to wait to start before starting others + waitDBContainer(BasicSteps.DB_CONTAINER_NAME); + } + break; + case "es": { + startESContainer(BasicSteps.ES_CONTAINER_NAME); + waitEsContainer(BasicSteps.ES_CONTAINER_NAME); + } + break; + case "events-broker": { + startEventBrokerContainer(BasicSteps.EVENTS_BROKER_CONTAINER_NAME); + waitEventBrokerContainer(BasicSteps.EVENTS_BROKER_CONTAINER_NAME); + } + break; + case "job-engine": { + startJobEngineContainer(BasicSteps.JOB_ENGINE_CONTAINER_NAME); + waitJobEngineContainer(BasicSteps.JOB_ENGINE_CONTAINER_NAME); + } + break; + case "message-broker": { + startMessageBrokerContainer(BasicSteps.MESSAGE_BROKER_CONTAINER_NAME); + waitMessageBrokerContainer(BasicSteps.MESSAGE_BROKER_CONTAINER_NAME); + } + break; + case "broker-auth-service": { + startAuthServiceContainer(BasicSteps.AUTH_SERVICE_CONTAINER_NAME); + } + break; + case "consumer-lifecycle": { + startLifecycleConsumerContainer(BasicSteps.LIFECYCLE_CONSUMER_CONTAINER_NAME); + } + break; + default: + throw new UnsupportedOperationException("Unknown container resource: " + dockerContainer); } } // Wait for them to be ready for (String dockerContainer : dockerContainers) { switch (dockerContainer) { - case "db": - case "es": - case "events-broker": - case "job-engine": - case "message-broker": { - // Nothing to do. - // Waiting to refactor them - } break; - case "broker-auth-service": { - waitAuthServiceContainer(BasicSteps.AUTH_SERVICE_CONTAINER_NAME); - } break; - case "consumer-lifecycle": { - waitLifecycleConsumerContainer(BasicSteps.LIFECYCLE_CONSUMER_CONTAINER_NAME); - } break; - default: - throw new UnsupportedOperationException("Unknown container resource: " + dockerContainer); + case "db": + case "es": + case "events-broker": + case "job-engine": + case "message-broker": { + // Nothing to do. + // Waiting to refactor them + } + break; + case "broker-auth-service": { + waitAuthServiceContainer(BasicSteps.AUTH_SERVICE_CONTAINER_NAME); + } + break; + case "consumer-lifecycle": { + waitLifecycleConsumerContainer(BasicSteps.LIFECYCLE_CONSUMER_CONTAINER_NAME); + } + break; + default: + throw new UnsupportedOperationException("Unknown container resource: " + dockerContainer); } } } @@ -453,7 +466,7 @@ private boolean isServiceReady(String type) throws IOException { int status = conn.getResponseCode(); if (status == 200) { try (InputStreamReader isr = new InputStreamReader(conn.getInputStream()); - BufferedReader in = new BufferedReader(isr)) { + BufferedReader in = new BufferedReader(isr)) { return isRunning(MAPPER.readValue(in, Map.class)); } } else { @@ -609,11 +622,13 @@ public void startDBContainer(String name) throws DockerException, InterruptedExc /** * Waits for the DB Docker container to be ready - * @param name The DB Docker container name + * + * @param name + * The DB Docker container name * @throws Exception * @since 2.1.0 */ - private void waitDBContainer(String name) throws Exception{ + private void waitDBContainer(String name) throws Exception { synchronized (this) { this.wait(WAIT_FOR_DB); } @@ -635,11 +650,12 @@ public void startESContainer(String name) throws DockerException, InterruptedExc /** * Waits for the Elasticsearch Docker container to be ready * - * @param name The Elasticsearch Docker container name + * @param name + * The Elasticsearch Docker container name * @throws Exception * @since 2.1.0 */ - private void waitEsContainer(String name) throws Exception{ + private void waitEsContainer(String name) throws Exception { synchronized (this) { this.wait(WAIT_FOR_ES); } @@ -661,11 +677,12 @@ public void startEventBrokerContainer(String name) throws DockerException, Inter /** * Waits for the Event Broker Docker container to be ready * - * @param name The Event Broker Docker container name + * @param name + * The Event Broker Docker container name * @throws Exception * @since 2.1.0 */ - private void waitEventBrokerContainer(String name) throws Exception{ + private void waitEventBrokerContainer(String name) throws Exception { synchronized (this) { this.wait(WAIT_FOR_EVENTS_BROKER); } @@ -687,11 +704,12 @@ public void startJobEngineContainer(String name) throws DockerException, Interru /** * Waits for the Job Engine Docker container to be ready * - * @param name The Job Engine Docker container name + * @param name + * The Job Engine Docker container name * @throws Exception * @since 2.1.0 */ - private void waitJobEngineContainer(String name) throws Exception{ + private void waitJobEngineContainer(String name) throws Exception { long now = System.currentTimeMillis(); while (now + JOB_ENGINE_READY_MAX_WAIT > System.currentTimeMillis()) { if (isJobEngineContainerReady(name)) { @@ -709,16 +727,16 @@ private void waitJobEngineContainer(String name) throws Exception{ /** * Checks if the Job Engine Docker container is ready * - * @param name The Job Engine Docker container name + * @param name + * The Job Engine Docker container name * @return {@code true} if is ready, {@code false} otherwise * @throws Exception * @since 2.1.0 */ private boolean isJobEngineContainerReady(String name) throws Exception { - try (TestReadinessHttpConnection testReadinessHttpConnection = new TestReadinessHttpConnection(JOB_ENGINE_ADDRESS_EXTERNAL)){ + try (TestReadinessHttpConnection testReadinessHttpConnection = new TestReadinessHttpConnection(JOB_ENGINE_ADDRESS_EXTERNAL)) { return testReadinessHttpConnection.isReady(); - } - catch (Exception e) { + } catch (Exception e) { // Ignoring... } @@ -741,11 +759,12 @@ public void startAPIContainer(String name, String tokenTTL, String refreshTokenT /** * Waits for the REST API Docker container to be ready * - * @param name The REST API Docker container name + * @param name + * The REST API Docker container name * @throws Exception * @since 2.1.0 */ - private void waitRestApiContainer(String name) throws Exception{ + private void waitRestApiContainer(String name) throws Exception { synchronized (this) { this.wait(WAIT_FOR_REST_API); } @@ -779,11 +798,12 @@ public void startMessageBrokerContainer(String name) throws DockerException, Int /** * Waits for the Message Broker Docker container to be ready * - * @param name The Message Broker Docker container name + * @param name + * The Message Broker Docker container name * @throws Exception * @since 2.1.0 */ - private void waitMessageBrokerContainer(String name) throws Exception{ + private void waitMessageBrokerContainer(String name) throws Exception { long now = System.currentTimeMillis(); while (now + MESSAGE_BROKER_READY_MAX_WAIT > System.currentTimeMillis()) { if (isMessageBrokerContainerReady(name)) { @@ -801,15 +821,15 @@ private void waitMessageBrokerContainer(String name) throws Exception{ /** * Checks if the Message Broker Docker container is ready * - * @param name The Message Broker Docker container name + * @param name + * The Message Broker Docker container name * @return {@code true} if is ready, {@code false} otherwise * @since 2.1.0 */ private boolean isMessageBrokerContainerReady(String name) { - try (TestReadinessMqttBrokerConnection testReadinessConnection = new TestReadinessMqttBrokerConnection(MESSAGE_BROKER_ADDRESS_EXTERNAL)){ + try (TestReadinessMqttBrokerConnection testReadinessConnection = new TestReadinessMqttBrokerConnection(MESSAGE_BROKER_ADDRESS_EXTERNAL)) { return testReadinessConnection.isReady(); - } - catch (Exception e) { + } catch (Exception e) { // Ignoring... } @@ -831,11 +851,12 @@ public void startAuthServiceContainer(String name) throws DockerException, Inter /** * Waits for the Auth Service Docker container to be ready * - * @param name The Auth Service container name + * @param name + * The Auth Service container name * @throws Exception * @since 2.1.0 */ - private void waitAuthServiceContainer(String name) throws Exception{ + private void waitAuthServiceContainer(String name) throws Exception { long timeout = System.currentTimeMillis(); while (System.currentTimeMillis() - timeout < 30000) { if (isServiceReady(AUTH_SERVICE_CHECK_WEB_APP)) { @@ -860,14 +881,15 @@ public void startLifecycleConsumerContainer(String name) throws DockerException, /** * Waits for the Lifecycle Consumer Docker container to be ready * - * @param name The Lifecycle Consumer container name + * @param name + * The Lifecycle Consumer container name * @throws Exception * @since 2.1.0 */ - private void waitLifecycleConsumerContainer(String name) throws Exception{ + private void waitLifecycleConsumerContainer(String name) throws Exception { long timeout = System.currentTimeMillis(); while (System.currentTimeMillis() - timeout < 30000) { - if (isServiceReady(LIFECYCLE_CHECK_WEB_APP)){ + if (isServiceReady(LIFECYCLE_CHECK_WEB_APP)) { break; } TimeUnit.MILLISECONDS.sleep(500); @@ -889,11 +911,12 @@ public void startTelemetryConsumerContainer(String name) throws DockerException, /** * Waits for the Telemetry Consumer Docker container to be ready * - * @param name The Telemetry Consumer container name + * @param name + * The Telemetry Consumer container name * @throws Exception * @since 2.1.0 */ - private void waitTelemetryConsumerContainer(String name) throws Exception{ + private void waitTelemetryConsumerContainer(String name) throws Exception { long timeout = System.currentTimeMillis(); while (System.currentTimeMillis() - timeout < 30000) { if (isServiceReady(TELEMETRY_CHECK_WEB_APP)) { @@ -980,7 +1003,8 @@ private void printContainerLog(String name) { try { LogStream logStream = DockerUtil.getDockerClient().logs(container.id(), LogsParam.stdout(), LogsParam.stderr()); Logger brokerLogger = LoggerFactory.getLogger(name); - brokerLogger.info("\n===================================================\n START LOG FOR CONTAINER: {} (id: {})\n===================================================", name, container.id()); + brokerLogger.info("\n===================================================\n START LOG FOR CONTAINER: {} (id: {})\n===================================================", name, + container.id()); StringBuilder builder = new StringBuilder(); int i = 0; while (logStream.hasNext()) { @@ -991,7 +1015,8 @@ private void printContainerLog(String name) { } } brokerLogger.info(builder.toString()); - brokerLogger.info("\n---------------------------------------------------\n END LOG FOR CONTAINER: {} (id: {})\n---------------------------------------------------", name, container.id()); + brokerLogger.info("\n---------------------------------------------------\n END LOG FOR CONTAINER: {} (id: {})\n---------------------------------------------------", name, + container.id()); } catch (Exception e1) { logger.warn("Cannot print container log for name/id '{}'/'{}'", name, container.id()); } @@ -1006,30 +1031,38 @@ private void printContainerLog(String name) { * Creation of docker container configuration for broker. * * @param brokerIp - * @param mqttPort mqtt port on docker - * @param mqttHostPort mqtt port on docker host - * @param mqttsPort mqtts port on docker - * @param mqttsHostPort mqtts port on docker host - * @param webPort web port on docker - * @param webHostPort web port on docker host - * @param debugPort debug port on docker - * @param debugHostPort debug port on docker host - * // * @param brokerInternalDebugPort - * @param dockerImage full name of image (e.g. "kapua/kapua-broker:" + version) + * @param mqttPort + * mqtt port on docker + * @param mqttHostPort + * mqtt port on docker host + * @param mqttsPort + * mqtts port on docker + * @param mqttsHostPort + * mqtts port on docker host + * @param webPort + * web port on docker + * @param webHostPort + * web port on docker host + * @param debugPort + * debug port on docker + * @param debugHostPort + * debug port on docker host // * @param brokerInternalDebugPort + * @param dockerImage + * full name of image (e.g. "kapua/kapua-broker:" + version) * @return Container configuration for specific boroker instance */ private ContainerConfig getBrokerContainerConfig(String brokerIp, - int mqttPort, - int mqttHostPort, - int mqttInternalPort, - int mqttInternalHostPort, - int mqttsPort, - int mqttsHostPort, - int webPort, - int webHostPort, - int debugPort, - int debugHostPort, - String dockerImage) { + int mqttPort, + int mqttHostPort, + int mqttInternalPort, + int mqttInternalHostPort, + int mqttsPort, + int mqttsHostPort, + int webPort, + int webHostPort, + int debugPort, + int debugHostPort, + String dockerImage) { final Map> portBindings = new HashMap<>(); addHostPort(ALL_IP, portBindings, mqttPort, mqttHostPort); @@ -1054,7 +1087,7 @@ private ContainerConfig getBrokerContainerConfig(String brokerIp, } if (debug) { -// envVars.add(String.format("ACTIVEMQ_DEBUG_OPTS=-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=%s", debugPort)); + // envVars.add(String.format("ACTIVEMQ_DEBUG_OPTS=-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=%s", debugPort)); envVars.add(String.format("DEBUG_ARGS=-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:%s", debugPort)); } @@ -1100,7 +1133,7 @@ private ContainerConfig getDbContainerConfig() { "DB_USER=kapua", "DB_PASSWORD=kapua", //uncomment this line to enable the H@ web console (WARNING enable it only for test and then disable it again!) -// "H2_WEB_OPTS=-web -webAllowOthers -webPort 8181", + // "H2_WEB_OPTS=-web -webAllowOthers -webPort 8181", "DB_PORT_3306_TCP_PORT=3306" ) .image("kapua/kapua-sql:" + KAPUA_VERSION) @@ -1261,17 +1294,20 @@ private ContainerConfig getJobEngineContainerConfig() { /** * Add Docker port to host port mappings. * - * @param host IP address of host - * @param portBindings {@link List} ob bindings that gets updated - * @param port Docker container port - * @param hostPort Port exposed on host - * + * @param host + * IP address of host + * @param portBindings + * {@link List} ob bindings that gets updated + * @param port + * Docker container port + * @param hostPort + * Port exposed on host * @since 2.0.0 */ private void addHostPort(String host, - Map> portBindings, - int port, - int hostPort) { + Map> portBindings, + int port, + int hostPort) { List hostPorts = new ArrayList<>(); hostPorts.add(PortBinding.of(host, hostPort)); portBindings.put(String.valueOf(port), hostPorts); diff --git a/qa/integration/pom.xml b/qa/integration/pom.xml index ba63d0fbcf5..da152233ab1 100644 --- a/qa/integration/pom.xml +++ b/qa/integration/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-qa - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT ${kapua-client.maven.toolchain.jdk.version} diff --git a/qa/integration/src/test/java/org/eclipse/kapua/integration/misc/AccessInfoCreatorImplTest.java b/qa/integration/src/test/java/org/eclipse/kapua/integration/misc/AccessInfoCreatorTest.java similarity index 87% rename from qa/integration/src/test/java/org/eclipse/kapua/integration/misc/AccessInfoCreatorImplTest.java rename to qa/integration/src/test/java/org/eclipse/kapua/integration/misc/AccessInfoCreatorTest.java index d8b56216200..a57eed88147 100644 --- a/qa/integration/src/test/java/org/eclipse/kapua/integration/misc/AccessInfoCreatorImplTest.java +++ b/qa/integration/src/test/java/org/eclipse/kapua/integration/misc/AccessInfoCreatorTest.java @@ -12,12 +12,12 @@ *******************************************************************************/ package org.eclipse.kapua.integration.misc; -import org.eclipse.kapua.locator.KapuaLocator; +import java.util.HashSet; +import java.util.Set; + import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.qa.markers.junit.JUnitTests; import org.eclipse.kapua.service.authorization.access.AccessInfoCreator; -import org.eclipse.kapua.service.authorization.access.AccessInfoFactory; -import org.eclipse.kapua.service.authorization.access.shiro.AccessInfoCreatorImpl; import org.eclipse.kapua.service.authorization.permission.Permission; import org.junit.Assert; import org.junit.Before; @@ -25,23 +25,17 @@ import org.junit.experimental.categories.Category; import org.mockito.Mockito; -import java.util.HashSet; -import java.util.Set; - - @Category(JUnitTests.class) -public class AccessInfoCreatorImplTest { +public class AccessInfoCreatorTest { - AccessInfoFactory accessInfoFactory; AccessInfoCreator accessInfoCreator; Set roleId; Set setPermission; - AccessInfoCreatorImpl accessInfoCreatorImpl1, accessInfoCreatorImpl2; + AccessInfoCreator accessInfoCreatorImpl1, accessInfoCreatorImpl2; @Before public void initialize() { - accessInfoFactory = KapuaLocator.getInstance().getFactory(AccessInfoFactory.class); - accessInfoCreator = accessInfoFactory.newCreator(KapuaId.ONE); + accessInfoCreator = new AccessInfoCreator(KapuaId.ONE); roleId = new HashSet<>(); setPermission = new HashSet<>(); roleId.add(KapuaId.ANY); @@ -51,8 +45,8 @@ public void initialize() { accessInfoCreator.setRoleIds(roleId); accessInfoCreator.setPermissions(setPermission); - accessInfoCreatorImpl1 = new AccessInfoCreatorImpl(accessInfoCreator); - accessInfoCreatorImpl2 = new AccessInfoCreatorImpl(KapuaId.ONE); + accessInfoCreatorImpl1 = new AccessInfoCreator(accessInfoCreator); + accessInfoCreatorImpl2 = new AccessInfoCreator(KapuaId.ONE); } @Test @@ -65,7 +59,7 @@ public void accessInfoCreatorImplAccessInfoCreatorParameterTest() { @Test(expected = NullPointerException.class) public void accessInfoCreatorImplNullAccessInfoCreatorParameterTest() { - accessInfoCreatorImpl1 = new AccessInfoCreatorImpl((AccessInfoCreator) null); + accessInfoCreatorImpl1 = new AccessInfoCreator((AccessInfoCreator) null); } @Test @@ -78,7 +72,7 @@ public void accessInfoCreatorScopeIdParameterTest() { @Test public void accessInfoCreatorNullScopeIdParameterTest() { - accessInfoCreatorImpl2 = new AccessInfoCreatorImpl((KapuaId) null); + accessInfoCreatorImpl2 = new AccessInfoCreator((KapuaId) null); Assert.assertNull("Null expected.", accessInfoCreatorImpl2.getScopeId()); Assert.assertNull("Null expected.", accessInfoCreatorImpl2.getUserId()); diff --git a/qa/integration/src/test/java/org/eclipse/kapua/integration/misc/AccessPermissionImplTest.java b/qa/integration/src/test/java/org/eclipse/kapua/integration/misc/AccessPermissionImplTest.java index e8c3f83fe50..9ff3d1c8a75 100644 --- a/qa/integration/src/test/java/org/eclipse/kapua/integration/misc/AccessPermissionImplTest.java +++ b/qa/integration/src/test/java/org/eclipse/kapua/integration/misc/AccessPermissionImplTest.java @@ -12,6 +12,10 @@ *******************************************************************************/ package org.eclipse.kapua.integration.misc; +import java.lang.reflect.Constructor; +import java.lang.reflect.Modifier; +import java.util.Date; + import org.eclipse.kapua.commons.model.id.KapuaEid; import org.eclipse.kapua.model.domain.Actions; import org.eclipse.kapua.model.id.KapuaId; @@ -19,24 +23,18 @@ import org.eclipse.kapua.service.authorization.access.AccessPermission; import org.eclipse.kapua.service.authorization.access.shiro.AccessPermissionImpl; import org.eclipse.kapua.service.authorization.permission.Permission; -import org.eclipse.kapua.service.authorization.permission.shiro.PermissionImpl; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.mockito.Mockito; -import java.lang.reflect.Constructor; -import java.lang.reflect.Modifier; -import java.util.Date; - - @Category(JUnitTests.class) public class AccessPermissionImplTest { AccessPermissionImpl accessPermissionImpl1, accessPermissionImpl2, accessPermissionImpl; AccessPermission accessPermission; - PermissionImpl permission1, permission2; + Permission permission1, permission2; Permission newPermission; Date createdOn; @@ -45,8 +43,8 @@ public void initialize() { accessPermissionImpl1 = new AccessPermissionImpl(KapuaId.ONE); accessPermissionImpl2 = new AccessPermissionImpl(KapuaId.ONE); accessPermission = Mockito.mock(AccessPermission.class); - permission1 = Mockito.mock(PermissionImpl.class); - permission2 = Mockito.mock(PermissionImpl.class); + permission1 = new Permission("domain", Actions.connect, KapuaId.ONE, KapuaId.ANY, false); + permission2 = new Permission("another", null, null); newPermission = Mockito.mock(Permission.class); createdOn = new Date(); @@ -56,10 +54,6 @@ public void initialize() { Mockito.when(accessPermission.getCreatedOn()).thenReturn(createdOn); Mockito.when(accessPermission.getAccessInfoId()).thenReturn(KapuaId.ONE); Mockito.when(accessPermission.getPermission()).thenReturn(permission1); - Mockito.when(permission1.getDomain()).thenReturn("domain"); - Mockito.when(permission1.getAction()).thenReturn(Actions.connect); - Mockito.when(permission1.getTargetScopeId()).thenReturn(KapuaId.ONE); - Mockito.when(permission1.getGroupId()).thenReturn(KapuaId.ANY); accessPermissionImpl = new AccessPermissionImpl(accessPermission); } @@ -168,8 +162,7 @@ public void hashCodeNullAccessInfoIdTest() { Mockito.when(permission.getAction()).thenReturn(null); Mockito.when(permission.getTargetScopeId()).thenReturn(null); Mockito.when(permission.getGroupId()).thenReturn(null); - PermissionImpl permissionImpl = new PermissionImpl(permission); - accessPermissionImpl1.setPermission(permissionImpl); + accessPermissionImpl1.setPermission(permission); Assert.assertEquals("Expected and actual values should be the same.", 924482, accessPermissionImpl1.hashCode()); } @@ -181,8 +174,7 @@ public void hashCodeTest() { Mockito.when(permission.getAction()).thenReturn(null); Mockito.when(permission.getTargetScopeId()).thenReturn(null); Mockito.when(permission.getGroupId()).thenReturn(null); - PermissionImpl permissionImpl = new PermissionImpl(permission); - accessPermissionImpl1.setPermission(permissionImpl); + accessPermissionImpl1.setPermission(permission); Assert.assertEquals("Expected and actual values should be the same.", 925474, accessPermissionImpl1.hashCode()); } @@ -252,7 +244,7 @@ public void equalsEqualAccessInfoIdsEqualPermissionsTest() { public void equalsEqualAccessInfoIdsDifferentPermissionsTest() { accessPermissionImpl1.setAccessInfoId(KapuaId.ONE); accessPermissionImpl2.setAccessInfoId(KapuaId.ONE); - accessPermissionImpl1.setPermission(Mockito.mock(PermissionImpl.class)); + accessPermissionImpl1.setPermission(new Permission("another", null, null)); Assert.assertFalse("False expected.", accessPermissionImpl1.equals(accessPermissionImpl2)); } } \ No newline at end of file diff --git a/qa/integration/src/test/java/org/eclipse/kapua/integration/misc/AccessTokenAuthenticationRealmTest.java b/qa/integration/src/test/java/org/eclipse/kapua/integration/misc/AccessTokenAuthenticationRealmTest.java index 64164480fd4..931f586f52f 100644 --- a/qa/integration/src/test/java/org/eclipse/kapua/integration/misc/AccessTokenAuthenticationRealmTest.java +++ b/qa/integration/src/test/java/org/eclipse/kapua/integration/misc/AccessTokenAuthenticationRealmTest.java @@ -23,7 +23,6 @@ import org.junit.experimental.categories.Category; import org.mockito.Mockito; - @Category(JUnitTests.class) public class AccessTokenAuthenticationRealmTest { diff --git a/qa/integration/src/test/java/org/eclipse/kapua/integration/misc/AccessTokenCredentialsMatcherTest.java b/qa/integration/src/test/java/org/eclipse/kapua/integration/misc/AccessTokenCredentialsMatcherTest.java index 81e54abca29..eca2d45fdee 100644 --- a/qa/integration/src/test/java/org/eclipse/kapua/integration/misc/AccessTokenCredentialsMatcherTest.java +++ b/qa/integration/src/test/java/org/eclipse/kapua/integration/misc/AccessTokenCredentialsMatcherTest.java @@ -23,7 +23,6 @@ import org.junit.experimental.categories.Category; import org.mockito.Mockito; - @Category(JUnitTests.class) public class AccessTokenCredentialsMatcherTest { diff --git a/qa/integration/src/test/java/org/eclipse/kapua/integration/misc/EventStoreServiceImplTest.java b/qa/integration/src/test/java/org/eclipse/kapua/integration/misc/EventStoreServiceImplTest.java index 9a0e6bcf552..f2b6a4f64dc 100644 --- a/qa/integration/src/test/java/org/eclipse/kapua/integration/misc/EventStoreServiceImplTest.java +++ b/qa/integration/src/test/java/org/eclipse/kapua/integration/misc/EventStoreServiceImplTest.java @@ -12,24 +12,20 @@ *******************************************************************************/ package org.eclipse.kapua.integration.misc; +import java.math.BigInteger; + import org.eclipse.kapua.commons.model.id.KapuaEid; -import org.eclipse.kapua.commons.service.event.store.api.EventStoreFactory; import org.eclipse.kapua.commons.service.event.store.api.EventStoreRecordCreator; import org.eclipse.kapua.commons.service.event.store.api.EventStoreRecordRepository; -import org.eclipse.kapua.commons.service.event.store.internal.EventStoreRecordCreatorImpl; import org.eclipse.kapua.commons.service.event.store.internal.EventStoreServiceImpl; import org.eclipse.kapua.qa.markers.junit.JUnitTests; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; import org.eclipse.kapua.storage.TxManager; import org.junit.Assert; import org.junit.Test; import org.junit.experimental.categories.Category; import org.mockito.Mockito; -import java.math.BigInteger; - - @Category(JUnitTests.class) //TODO: rewrite this public class EventStoreServiceImplTest { @@ -38,11 +34,9 @@ public class EventStoreServiceImplTest { public void createTest() { EventStoreServiceImpl eventStoreServiceImpl = new EventStoreServiceImpl( Mockito.mock(AuthorizationService.class), - Mockito.mock(PermissionFactory.class), Mockito.mock(TxManager.class), - Mockito.mock(EventStoreFactory.class), Mockito.mock(EventStoreRecordRepository.class)); - EventStoreRecordCreator[] creator = {null, new EventStoreRecordCreatorImpl(new KapuaEid(BigInteger.ONE))}; + EventStoreRecordCreator[] creator = { null, new EventStoreRecordCreator(new KapuaEid(BigInteger.ONE)) }; UnsupportedOperationException unsupportedOperationException = new UnsupportedOperationException(); for (EventStoreRecordCreator eventStoreRecordCreator : creator) { diff --git a/qa/integration/src/test/java/org/eclipse/kapua/integration/misc/JwtAuthenticatingRealmTest.java b/qa/integration/src/test/java/org/eclipse/kapua/integration/misc/JwtAuthenticatingRealmTest.java index 83c2de6eb9c..ce7e4b8d018 100644 --- a/qa/integration/src/test/java/org/eclipse/kapua/integration/misc/JwtAuthenticatingRealmTest.java +++ b/qa/integration/src/test/java/org/eclipse/kapua/integration/misc/JwtAuthenticatingRealmTest.java @@ -15,6 +15,7 @@ import org.apache.shiro.authc.AuthenticationToken; import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.qa.markers.junit.JUnitTests; +import org.eclipse.kapua.service.authentication.JwtCredentials; import org.eclipse.kapua.service.authentication.shiro.JwtCredentialsImpl; import org.eclipse.kapua.service.authentication.shiro.realm.JwtAuthenticatingRealm; import org.junit.Assert; @@ -23,7 +24,6 @@ import org.junit.experimental.categories.Category; import org.mockito.Mockito; - @Category(JUnitTests.class) public class JwtAuthenticatingRealmTest { @@ -50,8 +50,8 @@ public void destroyNullJwtProcessorTest() throws Exception { @Test public void supportsTrueTest() { - JwtCredentialsImpl authenticationToken = new JwtCredentialsImpl("jwt", "token id"); - Assert.assertTrue("True expected.", jwtAuthenticatingRealm.supports(authenticationToken)); + JwtCredentials authenticationToken = new JwtCredentials("jwt", "token id"); + Assert.assertTrue("True expected.", jwtAuthenticatingRealm.supports(new JwtCredentialsImpl(authenticationToken))); } @Test diff --git a/qa/integration/src/test/java/org/eclipse/kapua/integration/misc/KapuaTscalarAdapterTest.java b/qa/integration/src/test/java/org/eclipse/kapua/integration/misc/KapuaTscalarAdapterTest.java index d5638ca1ef5..df55cfb4af2 100644 --- a/qa/integration/src/test/java/org/eclipse/kapua/integration/misc/KapuaTscalarAdapterTest.java +++ b/qa/integration/src/test/java/org/eclipse/kapua/integration/misc/KapuaTscalarAdapterTest.java @@ -24,14 +24,14 @@ public class KapuaTscalarAdapterTest { KapuaTscalarAdapter kapuaTscalarAdapter; - KapuaTscalar[] kapuaTscalar; + KapuaTscalar[] kapuaTscalars; String[] stringValue; String[] invalidStringValue; @Before public void initialize() { kapuaTscalarAdapter = new KapuaTscalarAdapter(); - kapuaTscalar = new KapuaTscalar[] { KapuaTscalar.STRING, KapuaTscalar.LONG, KapuaTscalar.DOUBLE, KapuaTscalar.FLOAT, KapuaTscalar.INTEGER, + kapuaTscalars = new KapuaTscalar[] { KapuaTscalar.STRING, KapuaTscalar.LONG, KapuaTscalar.DOUBLE, KapuaTscalar.FLOAT, KapuaTscalar.INTEGER, KapuaTscalar.BYTE, KapuaTscalar.CHAR, KapuaTscalar.BOOLEAN, KapuaTscalar.SHORT, KapuaTscalar.PASSWORD }; stringValue = new String[] { "String", "Long", "Double", "Float", "Integer", "Byte", "Char", "Boolean", "Short", "Password" }; invalidStringValue = new String[] { null, "Invalid Value" }; @@ -40,8 +40,8 @@ public void initialize() { @Test public void marshalTest() throws Exception { String[] expectedStringValue = stringValue; - for (int i = 0; i < kapuaTscalar.length; i++) { - Assert.assertEquals("Expected and actual values should be the same.", expectedStringValue[i], kapuaTscalarAdapter.marshal(kapuaTscalar[i])); + for (int i = 0; i < kapuaTscalars.length; i++) { + Assert.assertEquals("Expected and actual values should be the same.", expectedStringValue[i], kapuaTscalarAdapter.marshal(kapuaTscalars[i])); } } @@ -52,7 +52,7 @@ public void marshalNullParameterTest() throws Exception { @Test public void unmarshalTest() throws Exception { - KapuaTscalar[] expectedTscalars = kapuaTscalar; + KapuaTscalar[] expectedTscalars = kapuaTscalars; for (int i = 0; i < stringValue.length; i++) { Assert.assertEquals("Expected and actual values should be the same.", expectedTscalars[i], kapuaTscalarAdapter.unmarshal(stringValue[i])); } diff --git a/qa/integration/src/test/java/org/eclipse/kapua/integration/misc/PermissionFactoryImplTest.java b/qa/integration/src/test/java/org/eclipse/kapua/integration/misc/PermissionFactoryImplTest.java deleted file mode 100644 index a682660611a..00000000000 --- a/qa/integration/src/test/java/org/eclipse/kapua/integration/misc/PermissionFactoryImplTest.java +++ /dev/null @@ -1,28 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.integration.misc; - -import org.eclipse.kapua.qa.markers.junit.JUnitTests; -import org.eclipse.kapua.service.authorization.permission.shiro.PermissionFactoryImpl; -import org.junit.Test; -import org.junit.experimental.categories.Category; - -@Category(JUnitTests.class) -public class PermissionFactoryImplTest { - - @Test - public void newPermissionTest() { - PermissionFactoryImpl permissionFactoryImpl = new PermissionFactoryImpl(); - System.out.println(permissionFactoryImpl.newPermission((String) null, null, null, null, true)); - } -} diff --git a/qa/integration/src/test/java/org/eclipse/kapua/integration/misc/RolePermissionFactoryTest.java b/qa/integration/src/test/java/org/eclipse/kapua/integration/misc/RolePermissionFactoryTest.java index 0c5d9152e5c..0762f272cf9 100644 --- a/qa/integration/src/test/java/org/eclipse/kapua/integration/misc/RolePermissionFactoryTest.java +++ b/qa/integration/src/test/java/org/eclipse/kapua/integration/misc/RolePermissionFactoryTest.java @@ -12,13 +12,13 @@ *******************************************************************************/ package org.eclipse.kapua.integration.misc; +import java.util.Date; + +import org.eclipse.kapua.model.domain.Actions; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.qa.markers.junit.JUnitTests; -import org.eclipse.kapua.service.authorization.permission.shiro.PermissionImpl; +import org.eclipse.kapua.service.authorization.permission.Permission; import org.eclipse.kapua.service.authorization.role.RolePermission; -import org.eclipse.kapua.service.authorization.role.RolePermissionCreator; -import org.eclipse.kapua.service.authorization.role.RolePermissionListResult; -import org.eclipse.kapua.service.authorization.role.RolePermissionQuery; import org.eclipse.kapua.service.authorization.role.shiro.RolePermissionFactoryImpl; import org.junit.Assert; import org.junit.Before; @@ -26,9 +26,6 @@ import org.junit.experimental.categories.Category; import org.mockito.Mockito; -import java.util.Date; - - @Category(JUnitTests.class) public class RolePermissionFactoryTest { @@ -36,7 +33,7 @@ public class RolePermissionFactoryTest { KapuaId scopeId; RolePermission rolePermission; Date createdOn, modifiedOn; - PermissionImpl permission; + Permission permission; @Before public void initialize() { @@ -45,7 +42,7 @@ public void initialize() { createdOn = new Date(); modifiedOn = new Date(); rolePermission = Mockito.mock(RolePermission.class); - permission = Mockito.mock(PermissionImpl.class); + permission = new Permission("domain", Actions.connect, KapuaId.ONE); Mockito.when(rolePermission.getId()).thenReturn(KapuaId.ANY); Mockito.when(rolePermission.getRoleId()).thenReturn(KapuaId.ONE); @@ -67,36 +64,6 @@ public void newEntityNullTest() { Assert.assertNull("Null expected.", rolePermissionFactoryImpl.newEntity(null).getScopeId()); } - @Test - public void newCreatorTest() { - Assert.assertTrue("True expected.", rolePermissionFactoryImpl.newCreator(scopeId) instanceof RolePermissionCreator); - Assert.assertEquals("Expected and actual values should be the same.", scopeId, rolePermissionFactoryImpl.newCreator(scopeId).getScopeId()); - } - - @Test - public void newCreatorNullTest() { - Assert.assertTrue("True expected.", rolePermissionFactoryImpl.newCreator(null) instanceof RolePermissionCreator); - Assert.assertNull("Null expected.", rolePermissionFactoryImpl.newCreator(null).getScopeId()); - } - - @Test - public void newQueryTest() { - Assert.assertTrue("True expected.", rolePermissionFactoryImpl.newQuery(scopeId) instanceof RolePermissionQuery); - Assert.assertEquals("Expected and actual values should be the same.", scopeId, rolePermissionFactoryImpl.newQuery(scopeId).getScopeId()); - } - - @Test - public void newQueryNullTest() { - Assert.assertTrue("True expected.", rolePermissionFactoryImpl.newQuery(null) instanceof RolePermissionQuery); - Assert.assertNull("Null expected.", rolePermissionFactoryImpl.newQuery(null).getScopeId()); - } - - @Test - public void newListResultTest() { - Assert.assertTrue("True expected.", rolePermissionFactoryImpl.newListResult() instanceof RolePermissionListResult); - Assert.assertTrue("True expected.", rolePermissionFactoryImpl.newListResult().isEmpty()); - } - @Test public void cloneTest() { RolePermission resultRolePermission = rolePermissionFactoryImpl.clone(rolePermission); diff --git a/qa/integration/src/test/java/org/eclipse/kapua/integration/misc/RolePermissionImplTest.java b/qa/integration/src/test/java/org/eclipse/kapua/integration/misc/RolePermissionImplTest.java index eb7ad94a812..50f778ca2bd 100644 --- a/qa/integration/src/test/java/org/eclipse/kapua/integration/misc/RolePermissionImplTest.java +++ b/qa/integration/src/test/java/org/eclipse/kapua/integration/misc/RolePermissionImplTest.java @@ -12,10 +12,13 @@ *******************************************************************************/ package org.eclipse.kapua.integration.misc; +import java.lang.reflect.Constructor; +import java.lang.reflect.Modifier; +import java.util.Date; + import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.qa.markers.junit.JUnitTests; import org.eclipse.kapua.service.authorization.permission.Permission; -import org.eclipse.kapua.service.authorization.permission.shiro.PermissionImpl; import org.eclipse.kapua.service.authorization.role.RolePermission; import org.eclipse.kapua.service.authorization.role.shiro.RolePermissionImpl; import org.junit.Assert; @@ -24,11 +27,6 @@ import org.junit.experimental.categories.Category; import org.mockito.Mockito; -import java.lang.reflect.Constructor; -import java.lang.reflect.Modifier; -import java.util.Date; - - @Category(JUnitTests.class) public class RolePermissionImplTest { @@ -40,9 +38,9 @@ public class RolePermissionImplTest { @Before public void initialize() { - scopeIds = new KapuaId[]{null, KapuaId.ONE}; - permission1 = Mockito.mock(Permission.class); - permission2 = Mockito.mock(PermissionImpl.class); + scopeIds = new KapuaId[] { null, KapuaId.ONE }; + permission1 = new Permission(null, null, null); + permission2 = new Permission(null, null, null); rolePermissionImpl1 = new RolePermissionImpl(KapuaId.ONE); rolePermissionImpl2 = new RolePermissionImpl(KapuaId.ANY); rolePermission = Mockito.mock(RolePermission.class); @@ -69,7 +67,7 @@ public void rolePermissionImpScopeIdTest() { for (KapuaId scopeId : scopeIds) { RolePermissionImpl rolePermissionImpl = new RolePermissionImpl(scopeId); Assert.assertEquals("Expected and actual values should be the same.", scopeId, rolePermissionImpl.getScopeId()); - Assert.assertEquals("Expected and actual values should be the same.", new PermissionImpl(null, null, null, null), rolePermissionImpl.getPermission()); + Assert.assertEquals("Expected and actual values should be the same.", new Permission(null, null, null), rolePermissionImpl.getPermission()); Assert.assertNull("Null expected.", rolePermissionImpl.getRoleId()); } } @@ -89,7 +87,7 @@ public void rolePermissionImplScopeIdNullPermissionTest() { for (KapuaId scopeId : scopeIds) { RolePermissionImpl rolePermissionImpl = new RolePermissionImpl(scopeId, null); Assert.assertEquals("Expected and actual values should be the same.", scopeId, rolePermissionImpl.getScopeId()); - Assert.assertEquals("Expected and actual values should be the same.", new PermissionImpl(null, null, null, null), rolePermissionImpl.getPermission()); + Assert.assertEquals("Expected and actual values should be the same.", new Permission(null, null, null), rolePermissionImpl.getPermission()); } } @@ -112,7 +110,7 @@ public void rolePermissionImplNullRolePermissionTest() { @Test public void setAndGetRoleIdTest() { - KapuaId[] roleIds = {null, KapuaId.ONE}; + KapuaId[] roleIds = { null, KapuaId.ONE }; RolePermissionImpl rolePermissionImpl1 = new RolePermissionImpl(KapuaId.ONE); RolePermissionImpl rolePermissionImpl2 = new RolePermissionImpl(KapuaId.ANY, permission2); @@ -135,8 +133,8 @@ public void setAndGetPermissionToStringTest() { RolePermissionImpl rolePermissionImpl1 = new RolePermissionImpl(KapuaId.ONE); RolePermissionImpl rolePermissionImpl2 = new RolePermissionImpl(KapuaId.ANY, permission2); RolePermissionImpl rolePermissionImpl3 = new RolePermissionImpl(rolePermission); - Permission[] permissions = {null, permission1, permission2}; - Permission[] expectedPermissions = {new PermissionImpl(null, null, null, null), new PermissionImpl(null, null, null, null), permission2}; + Permission[] permissions = { null, permission1, permission2 }; + Permission[] expectedPermissions = { new Permission(null, null, null), new Permission(null, null, null), permission2 }; for (int i = 0; i < permissions.length; i++) { rolePermissionImpl1.setPermission(permissions[i]); diff --git a/qa/integration/src/test/java/org/eclipse/kapua/integration/service/account/RunAccountServiceI9nTest.java b/qa/integration/src/test/java/org/eclipse/kapua/integration/service/account/RunAccountServiceI9nTest.java index f26003b687d..2d2ab4d48eb 100644 --- a/qa/integration/src/test/java/org/eclipse/kapua/integration/service/account/RunAccountServiceI9nTest.java +++ b/qa/integration/src/test/java/org/eclipse/kapua/integration/service/account/RunAccountServiceI9nTest.java @@ -13,11 +13,11 @@ *******************************************************************************/ package org.eclipse.kapua.integration.service.account; +import org.junit.runner.RunWith; + import io.cucumber.junit.Cucumber; import io.cucumber.junit.CucumberOptions; -import org.junit.runner.RunWith; - @RunWith(Cucumber.class) @CucumberOptions( features = { @@ -32,7 +32,7 @@ "classpath:features/account/AccountUserService.feature", "classpath:features/account/AccountCredentialService.feature" }, - glue = {"org.eclipse.kapua.qa.common", + glue = { "org.eclipse.kapua.qa.common", "org.eclipse.kapua.service.account.steps", "org.eclipse.kapua.service.user.steps", "org.eclipse.kapua.service.authorization.steps", @@ -40,10 +40,11 @@ "org.eclipse.kapua.service.job.steps", "org.eclipse.kapua.service.tag.steps" }, - plugin = {"pretty", + plugin = { "pretty", "html:target/cucumber/AccountServiceI9n", "json:target/AccountServiceI9n_cucumber.json" }, monochrome = true) public class RunAccountServiceI9nTest { + } diff --git a/qa/integration/src/test/java/org/eclipse/kapua/integration/service/datastoreJunit/AbstractMessageStoreServiceTest.java b/qa/integration/src/test/java/org/eclipse/kapua/integration/service/datastoreJunit/AbstractMessageStoreServiceTest.java index cc7b58c2f9e..194094a2710 100644 --- a/qa/integration/src/test/java/org/eclipse/kapua/integration/service/datastoreJunit/AbstractMessageStoreServiceTest.java +++ b/qa/integration/src/test/java/org/eclipse/kapua/integration/service/datastoreJunit/AbstractMessageStoreServiceTest.java @@ -12,7 +12,11 @@ *******************************************************************************/ package org.eclipse.kapua.integration.service.datastoreJunit; -import com.google.common.base.MoreObjects; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.util.Random; + import org.apache.commons.lang.RandomStringUtils; import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.commons.jpa.JdbcConnectionUrlResolvers; @@ -25,17 +29,14 @@ import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.qa.markers.junit.JUnitTests; import org.eclipse.kapua.service.authentication.AuthenticationService; -import org.eclipse.kapua.service.authentication.CredentialsFactory; +import org.eclipse.kapua.service.authentication.UsernamePasswordCredentials; import org.junit.After; import org.junit.Before; import org.junit.experimental.categories.Category; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; -import java.util.Random; +import com.google.common.base.MoreObjects; @Category(JUnitTests.class) public abstract class AbstractMessageStoreServiceTest { @@ -69,8 +70,7 @@ public void setUp() throws SQLException { String password = "kapua-password"; AuthenticationService authenticationService = locator.getService(AuthenticationService.class); - CredentialsFactory credentialsFactory = locator.getFactory(CredentialsFactory.class); - authenticationService.login(credentialsFactory.newUsernamePasswordCredentials(username, password)); + authenticationService.login(new UsernamePasswordCredentials(username, password)); // Get current user Id adminUserId = KapuaSecurityUtils.getSession().getUserId(); adminScopeId = KapuaSecurityUtils.getSession().getScopeId(); @@ -106,9 +106,12 @@ public void tearDown() { /** * Generates a random {@link String} from the given parameters * - * @param chars length of the generated {@link String} - * @param letters whether or not use chars - * @param numbers whether or not use numbers + * @param chars + * length of the generated {@link String} + * @param letters + * whether or not use chars + * @param numbers + * whether or not use numbers * @return the generated {@link String} */ private static String generateRandomString(int chars, boolean letters, boolean numbers) { diff --git a/qa/integration/src/test/java/org/eclipse/kapua/integration/service/datastoreJunit/MessageStoreServiceSslTest.java b/qa/integration/src/test/java/org/eclipse/kapua/integration/service/datastoreJunit/MessageStoreServiceSslTest.java index d4fad348bea..b747ffc5eec 100644 --- a/qa/integration/src/test/java/org/eclipse/kapua/integration/service/datastoreJunit/MessageStoreServiceSslTest.java +++ b/qa/integration/src/test/java/org/eclipse/kapua/integration/service/datastoreJunit/MessageStoreServiceSslTest.java @@ -12,6 +12,16 @@ *******************************************************************************/ package org.eclipse.kapua.integration.service.datastoreJunit; +import java.text.ParseException; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + import org.apache.commons.lang.StringUtils; import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.commons.model.id.KapuaEid; @@ -25,17 +35,15 @@ import org.eclipse.kapua.qa.markers.junit.JUnitTests; import org.eclipse.kapua.service.account.Account; import org.eclipse.kapua.service.account.AccountService; -import org.eclipse.kapua.service.datastore.MessageStoreFactory; import org.eclipse.kapua.service.datastore.MessageStoreService; import org.eclipse.kapua.service.datastore.internal.MessageStoreFacade; import org.eclipse.kapua.service.datastore.internal.mediator.DatastoreException; -import org.eclipse.kapua.service.datastore.internal.mediator.MessageField; -import org.eclipse.kapua.service.datastore.internal.schema.MessageSchema; +import org.eclipse.kapua.service.datastore.model.query.MessageField; import org.eclipse.kapua.service.datastore.model.query.MessageQuery; +import org.eclipse.kapua.service.datastore.model.query.MessageSchema; import org.eclipse.kapua.service.datastore.model.query.predicate.DatastorePredicateFactory; import org.eclipse.kapua.service.device.registry.Device; import org.eclipse.kapua.service.device.registry.DeviceCreator; -import org.eclipse.kapua.service.device.registry.DeviceFactory; import org.eclipse.kapua.service.device.registry.DeviceRegistryService; import org.eclipse.kapua.service.elasticsearch.client.ElasticsearchClientProvider; import org.eclipse.kapua.service.elasticsearch.client.exception.ClientException; @@ -52,16 +60,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.text.ParseException; -import java.time.Instant; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; - @Category(JUnitTests.class) public class MessageStoreServiceSslTest extends AbstractMessageStoreServiceTest { @@ -70,23 +68,21 @@ public class MessageStoreServiceSslTest extends AbstractMessageStoreServiceTest private final KapuaLocator locator = KapuaLocator.getInstance(); private final DeviceRegistryService deviceRegistryService = locator.getService(DeviceRegistryService.class); - private final DeviceFactory deviceFactory = locator.getFactory(DeviceFactory.class); private final DatastorePredicateFactory datastorePredicateFactory = locator.getFactory(DatastorePredicateFactory.class); private final MessageStoreService messageStoreService = locator.getService(MessageStoreService.class); private final MessageStoreFacade messageStoreFacade = locator.getComponent(MessageStoreFacade.class); - private final MessageStoreFactory messageStoreFactory = locator.getFactory(MessageStoreFactory.class); private final KapuaDataMessageFactory dataMessageFactory = locator.getFactory(KapuaDataMessageFactory.class); private final ElasticsearchClientProvider elasticsearchClientProvider = locator.getComponent(ElasticsearchClientProvider.class); /** * This method deletes all indices of the current ES instance *

    - * The method deletes all indices and resets the Kapua internal singleton state. - * This is required to ensure that each unit test, as it currently expects, starts with an empty ES setup + * The method deletes all indices and resets the Kapua internal singleton state. This is required to ensure that each unit test, as it currently expects, starts with an empty ES setup *

    * - * @throws Exception any case anything goes wrong + * @throws Exception + * any case anything goes wrong */ // @Before // public void deleteAllIndices() throws Exception { @@ -192,7 +188,7 @@ private void storeMessage(String semanticTopic) throws InterruptedException, Kap Account account = getTestAccountCreator(adminScopeId); String clientId = String.format("device-%d", new Date().getTime()); - DeviceCreator deviceCreator = deviceFactory.newCreator(account.getId(), clientId); + DeviceCreator deviceCreator = new DeviceCreator(account.getId(), clientId); Device device = deviceRegistryService.create(deviceCreator); // leave the message index by as default (DEVICE_TIMESTAMP) @@ -296,7 +292,7 @@ private void updatePayload(KapuaDataMessage message, KapuaDataPayload messagePay * @return */ private MessageQuery getBaseMessageQuery(KapuaId scopeId, int limit) { - MessageQuery query = messageStoreFactory.newQuery(scopeId); + MessageQuery query = new MessageQuery(scopeId); query.setAskTotalCount(true); query.setFetchStyle(StorableFetchStyle.SOURCE_FULL); diff --git a/qa/markers/pom.xml b/qa/markers/pom.xml index c75258c28c8..b8ddfe8cc27 100644 --- a/qa/markers/pom.xml +++ b/qa/markers/pom.xml @@ -17,7 +17,7 @@ org.eclipse.kapua kapua-qa - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-qa-markers diff --git a/qa/pom.xml b/qa/pom.xml index d8bf3712b3a..488ab473fed 100644 --- a/qa/pom.xml +++ b/qa/pom.xml @@ -19,7 +19,7 @@ org.eclipse.kapua kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-qa diff --git a/rest-api/core/pom.xml b/rest-api/core/pom.xml index 7d2e9868011..2f798fbafe3 100644 --- a/rest-api/core/pom.xml +++ b/rest-api/core/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-rest-api - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-rest-api-core diff --git a/rest-api/core/src/main/java/org/eclipse/kapua/app/api/core/auth/KapuaTokenAuthenticationFilter.java b/rest-api/core/src/main/java/org/eclipse/kapua/app/api/core/auth/KapuaTokenAuthenticationFilter.java index 59dfe9951e8..908c07ebb96 100644 --- a/rest-api/core/src/main/java/org/eclipse/kapua/app/api/core/auth/KapuaTokenAuthenticationFilter.java +++ b/rest-api/core/src/main/java/org/eclipse/kapua/app/api/core/auth/KapuaTokenAuthenticationFilter.java @@ -12,36 +12,31 @@ *******************************************************************************/ package org.eclipse.kapua.app.api.core.auth; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.web.filter.authc.AuthenticatingFilter; import org.apache.shiro.web.util.WebUtils; import org.eclipse.kapua.KapuaRuntimeException; -import org.eclipse.kapua.locator.KapuaLocator; -import org.eclipse.kapua.service.authentication.AccessTokenCredentials; -import org.eclipse.kapua.service.authentication.CredentialsFactory; +import org.eclipse.kapua.service.authentication.shiro.AccessTokenCredentialsImpl; import org.eclipse.kapua.service.authentication.shiro.exceptions.ExpiredAccessTokenException; import org.eclipse.kapua.service.authentication.shiro.exceptions.InvalidatedAccessTokenException; import org.eclipse.kapua.service.authentication.shiro.exceptions.MalformedAccessTokenException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - public class KapuaTokenAuthenticationFilter extends AuthenticatingFilter { private static final String OPTIONS = "OPTIONS"; private static final String AUTHORIZATION_HEADER = "Authorization"; private static final String BEARER = "Bearer"; - private final CredentialsFactory credentialsFactory; private final Logger logger = LoggerFactory.getLogger(this.getClass()); public KapuaTokenAuthenticationFilter() { - KapuaLocator locator = KapuaLocator.getInstance(); - this.credentialsFactory = locator.getFactory(CredentialsFactory.class); } @Override @@ -71,13 +66,13 @@ protected AuthenticationToken createToken(ServletRequest request, ServletRespons tokenId = httpRequest.getHeader(AUTHORIZATION_HEADER).replace(BEARER + " ", ""); } // Build AccessToken for Shiro Auth - AccessTokenCredentials accessTokenCredentials = credentialsFactory.newAccessTokenCredentials(tokenId); + AccessTokenCredentialsImpl accessTokenCredentials = new AccessTokenCredentialsImpl(tokenId); // Return token return (AuthenticationToken) accessTokenCredentials; } protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, - ServletRequest request, ServletResponse response) { + ServletRequest request, ServletResponse response) { HttpServletResponse httpResponse = WebUtils.toHttp(response); httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); //now I set a dummy header to propagate the error message to the CORSResponseFilter Class, that eventually will send this error message if CORS filter passes @@ -91,7 +86,6 @@ protected boolean onAccessDenied(ServletRequest request, ServletResponse respons return true; } - //with this method we choose what exceptions we want to hide in the response and what we want to show as an error message private String handleAuthException(AuthenticationException ae) { String errorMessageInResponse = "An error occurred during the authentication process with the provided access token"; diff --git a/rest-api/core/src/main/java/org/eclipse/kapua/app/api/core/model/data/JsonMessageListResult.java b/rest-api/core/src/main/java/org/eclipse/kapua/app/api/core/model/data/JsonMessageListResult.java index 3e2b970676e..2231e989905 100644 --- a/rest-api/core/src/main/java/org/eclipse/kapua/app/api/core/model/data/JsonMessageListResult.java +++ b/rest-api/core/src/main/java/org/eclipse/kapua/app/api/core/model/data/JsonMessageListResult.java @@ -13,12 +13,11 @@ package org.eclipse.kapua.app.api.core.model.data; import org.eclipse.kapua.service.elasticsearch.client.model.ResultList; -import org.eclipse.kapua.service.storable.model.AbstractStorableListResult; /** * @since 1.0.0 */ -public class JsonMessageListResult extends AbstractStorableListResult { +public class JsonMessageListResult extends org.eclipse.kapua.service.storable.model.StorableListResult { /** * Construct a message result list diff --git a/rest-api/core/src/main/java/org/eclipse/kapua/app/api/core/model/data/JsonMessageQuery.java b/rest-api/core/src/main/java/org/eclipse/kapua/app/api/core/model/data/JsonMessageQuery.java index 99dcaf37d78..91d225d2c7d 100644 --- a/rest-api/core/src/main/java/org/eclipse/kapua/app/api/core/model/data/JsonMessageQuery.java +++ b/rest-api/core/src/main/java/org/eclipse/kapua/app/api/core/model/data/JsonMessageQuery.java @@ -12,14 +12,8 @@ *******************************************************************************/ package org.eclipse.kapua.app.api.core.model.data; -import org.eclipse.kapua.commons.model.id.KapuaEid; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.model.id.KapuaIdAdapter; -import org.eclipse.kapua.service.datastore.internal.mediator.MessageField; -import org.eclipse.kapua.service.datastore.internal.schema.MessageSchema; -import org.eclipse.kapua.service.storable.model.query.StorableFetchStyle; -import org.eclipse.kapua.service.storable.model.query.XmlAdaptedSortField; -import org.eclipse.kapua.service.storable.model.query.predicate.StorablePredicate; +import java.util.ArrayList; +import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; @@ -28,8 +22,15 @@ import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; -import java.util.ArrayList; -import java.util.List; + +import org.eclipse.kapua.commons.model.id.KapuaEid; +import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.id.KapuaIdAdapter; +import org.eclipse.kapua.service.datastore.model.query.MessageField; +import org.eclipse.kapua.service.datastore.model.query.MessageSchema; +import org.eclipse.kapua.service.storable.model.query.StorableFetchStyle; +import org.eclipse.kapua.service.storable.model.query.XmlAdaptedSortField; +import org.eclipse.kapua.service.storable.model.query.predicate.StorablePredicate; /** * Message query implementation @@ -66,7 +67,8 @@ public JsonMessageQuery() { /** * Constructor. * - * @param scopeId The scopeId of the query + * @param scopeId + * The scopeId of the query * @since 1.0.0 */ public JsonMessageQuery(KapuaId scopeId) { @@ -159,14 +161,14 @@ public String[] getIncludes(StorableFetchStyle fetchStyle) { // Fetch mode String[] includeSource = null; switch (fetchStyle) { - case FIELDS: - includeSource = getFields(); - break; - case SOURCE_SELECT: - includeSource = new String[]{MessageSchema.MESSAGE_CAPTURED_ON, MessageSchema.MESSAGE_POSITION + ".*", MessageSchema.MESSAGE_METRICS + ".*"}; - break; - case SOURCE_FULL: - includeSource = new String[]{"*"}; + case FIELDS: + includeSource = getFields(); + break; + case SOURCE_SELECT: + includeSource = new String[] { MessageSchema.MESSAGE_CAPTURED_ON, MessageSchema.MESSAGE_POSITION + ".*", MessageSchema.MESSAGE_METRICS + ".*" }; + break; + case SOURCE_FULL: + includeSource = new String[] { "*" }; } return includeSource; } @@ -176,27 +178,27 @@ public String[] getExcludes(StorableFetchStyle fetchStyle) { // Fetch mode String[] excludeSource = null; switch (fetchStyle) { - case FIELDS: - excludeSource = new String[]{""}; - break; - case SOURCE_SELECT: - excludeSource = new String[]{MessageSchema.MESSAGE_BODY}; - break; - case SOURCE_FULL: - excludeSource = new String[]{""}; + case FIELDS: + excludeSource = new String[] { "" }; + break; + case SOURCE_SELECT: + excludeSource = new String[] { MessageSchema.MESSAGE_BODY }; + break; + case SOURCE_FULL: + excludeSource = new String[] { "" }; } return excludeSource; } @XmlTransient public String[] getFields() { - return new String[]{ + return new String[] { MessageField.MESSAGE_ID.field(), MessageField.SCOPE_ID.field(), MessageField.DEVICE_ID.field(), MessageField.CLIENT_ID.field(), MessageField.CHANNEL.field(), - MessageField.TIMESTAMP.field()}; + MessageField.TIMESTAMP.field() }; } } diff --git a/rest-api/core/src/main/java/org/eclipse/kapua/app/api/core/resources/AbstractKapuaResource.java b/rest-api/core/src/main/java/org/eclipse/kapua/app/api/core/resources/AbstractKapuaResource.java index 67a852ce6d3..0c154df1302 100644 --- a/rest-api/core/src/main/java/org/eclipse/kapua/app/api/core/resources/AbstractKapuaResource.java +++ b/rest-api/core/src/main/java/org/eclipse/kapua/app/api/core/resources/AbstractKapuaResource.java @@ -12,15 +12,16 @@ *******************************************************************************/ package org.eclipse.kapua.app.api.core.resources; -import org.eclipse.kapua.KapuaEntityNotFoundException; -import org.eclipse.kapua.model.KapuaEntity; -import org.eclipse.kapua.model.id.KapuaId; +import java.net.URI; import javax.ws.rs.NotFoundException; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; -import java.net.URI; + +import org.eclipse.kapua.KapuaEntityNotFoundException; +import org.eclipse.kapua.model.KapuaEntity; +import org.eclipse.kapua.model.id.KapuaId; /** * @since 1.0.0 @@ -32,14 +33,16 @@ public abstract class AbstractKapuaResource { *

    * If it is {@code null} a {@link NotFoundException} {@link WebApplicationException} is raised. *

    - * For {@link KapuaEntity} {@link #returnNotNullEntity(KapuaEntity, String, KapuaId)} is recommended. - * This is meant for generic {@link Object}s. + * For {@link KapuaEntity} {@link #returnNotNullEntity(Object, String, KapuaId)} is recommended. This is meant for generic {@link Object}s. * - * @param object The {@link Object} to check. + * @param object + * The {@link Object} to check. + * @param + * The type of the given {@link Object} * @return The given {@link Object} if not {@code null} - * @param The type of the given {@link Object} + * @throws NotFoundException + * if the given {@link Object} is {@code null} * @since 1.0.0 - * @throws NotFoundException if the given {@link Object} is {@code null} */ public T returnNotNullEntity(T object) { if (object == null) { @@ -52,15 +55,20 @@ public T returnNotNullEntity(T object) { /** * Checks id the given {@link KapuaEntity} is {@code null}. * - * @param entity The {@link KapuaEntity} to check. - * @param entityType The {@link KapuaEntity#getType()} - * @param entityId The {@link KapuaEntity#getId()} + * @param entity + * The {@link KapuaEntity} to check. + * @param entityType + * The {@link KapuaEntity#getType()} + * @param entityId + * The {@link KapuaEntity#getId()} + * @param + * The {@link KapuaEntity} type. * @return The given entity if not {@code null} - * @param The {@link KapuaEntity} type. - * @throws KapuaEntityNotFoundException if given {@link KapuaEntity} is {@code null}. + * @throws KapuaEntityNotFoundException + * if given {@link KapuaEntity} is {@code null}. * @since 2.0.0 */ - public T returnNotNullEntity(T entity, String entityType, KapuaId entityId) throws KapuaEntityNotFoundException { + public T returnNotNullEntity(T entity, String entityType, KapuaId entityId) throws KapuaEntityNotFoundException { if (entity == null) { throw new KapuaEntityNotFoundException(entityType, entityId); } @@ -89,7 +97,8 @@ public Response returnOk() { * return javax.ws.rs.core.Response.ok().entity(entity).build(); * * - * @param entity The entity to return. + * @param entity + * The entity to return. * @return A built {@link Response#ok()} * @since 1.0.0 */ @@ -104,7 +113,8 @@ public Response returnOk(Object entity) { * return javax.ws.rs.core.Response.status(Status.CREATED).entity(entity).build(); * * - * @param entity The entity to return. + * @param entity + * The entity to return. * @return A built {@link Response#created(URI)} * @since 1.2.0 */ diff --git a/rest-api/pom.xml b/rest-api/pom.xml index d3c38eccf2a..7daeb636926 100644 --- a/rest-api/pom.xml +++ b/rest-api/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-rest-api diff --git a/rest-api/resources/pom.xml b/rest-api/resources/pom.xml index e054c141599..7fdac14956c 100644 --- a/rest-api/resources/pom.xml +++ b/rest-api/resources/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-rest-api - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-rest-api-resources diff --git a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/AccessInfos.java b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/AccessInfos.java index e3ea828e27d..7965fe07ad7 100644 --- a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/AccessInfos.java +++ b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/AccessInfos.java @@ -12,35 +12,34 @@ *******************************************************************************/ package org.eclipse.kapua.app.api.resources.v1.resources; +import javax.inject.Inject; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.DefaultValue; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.app.api.core.model.CountResult; import org.eclipse.kapua.app.api.core.model.EntityId; import org.eclipse.kapua.app.api.core.model.ScopeId; import org.eclipse.kapua.app.api.core.resources.AbstractKapuaResource; +import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.model.query.predicate.AndPredicate; import org.eclipse.kapua.service.KapuaService; import org.eclipse.kapua.service.authorization.access.AccessInfo; import org.eclipse.kapua.service.authorization.access.AccessInfoAttributes; import org.eclipse.kapua.service.authorization.access.AccessInfoCreator; -import org.eclipse.kapua.service.authorization.access.AccessInfoFactory; import org.eclipse.kapua.service.authorization.access.AccessInfoListResult; -import org.eclipse.kapua.service.authorization.access.AccessInfoQuery; import org.eclipse.kapua.service.authorization.access.AccessInfoService; import org.eclipse.kapua.service.user.User; -import javax.inject.Inject; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.DefaultValue; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - /** * {@link AccessInfo} REST API resource. * @@ -51,29 +50,32 @@ public class AccessInfos extends AbstractKapuaResource { @Inject public AccessInfoService accessInfoService; - @Inject - public AccessInfoFactory accessInfoFactory; /** * Gets the {@link AccessInfo} list in the scope. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param userId The optional {@link User} id to filter results. - * @param offset The result set offset. - * @param limit The result set limit. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param userId + * The optional {@link User} id to filter results. + * @param offset + * The result set offset. + * @param limit + * The result set limit. * @return The {@link AccessInfoListResult} of all the {@link AccessInfo}s associated to the current selected scope. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @GET - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public AccessInfoListResult simpleQuery( @PathParam("scopeId") ScopeId scopeId, @QueryParam("userId") EntityId userId, @QueryParam("offset") @DefaultValue("0") int offset, @QueryParam("limit") @DefaultValue("50") int limit) throws KapuaException { - AccessInfoQuery query = accessInfoFactory.newQuery(scopeId); + final KapuaQuery query = new KapuaQuery(scopeId); AndPredicate andPredicate = query.andPredicate(); if (userId != null) { @@ -88,60 +90,68 @@ public AccessInfoListResult simpleQuery( } /** - * Queries the {@link AccessInfo}s with the given {@link AccessInfoQuery} parameter. + * Queries the {@link AccessInfo}s with the given {@link KapuaQuery} parameter. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param query The {@link AccessInfoQuery} to use to filter results. - * @return The {@link AccessInfoListResult} of all the result matching the given {@link AccessInfoQuery} parameter. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param query + * The {@link KapuaQuery} to use to filter results. + * @return The {@link AccessInfoListResult} of all the result matching the given {@link KapuaQuery} parameter. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @POST @Path("_query") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public AccessInfoListResult query( @PathParam("scopeId") ScopeId scopeId, - AccessInfoQuery query) throws KapuaException { + KapuaQuery query) throws KapuaException { query.setScopeId(scopeId); return accessInfoService.query(query); } /** - * Counts the {@link AccessInfo}s with the given {@link AccessInfoQuery} parameter. + * Counts the {@link AccessInfo}s with the given {@link KapuaQuery} parameter. * - * @param scopeId The {@link ScopeId} in which to count results. - * @param query The {@link AccessInfoQuery} to use to filter count results. - * @return The count of all the result matching the given {@link AccessInfoQuery} parameter. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @param scopeId + * The {@link ScopeId} in which to count results. + * @param query + * The {@link KapuaQuery} to use to filter count results. + * @return The count of all the result matching the given {@link KapuaQuery} parameter. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @POST @Path("_count") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public CountResult count( @PathParam("scopeId") ScopeId scopeId, - AccessInfoQuery query) throws KapuaException { + KapuaQuery query) throws KapuaException { query.setScopeId(scopeId); return new CountResult(accessInfoService.count(query)); } /** - * Creates a new {@link AccessInfo} based on the information provided in {@link AccessInfoCreator} - * parameter. + * Creates a new {@link AccessInfo} based on the information provided in {@link AccessInfoCreator} parameter. * - * @param scopeId The {@link ScopeId} in which to create the {@link AccessInfo}. - * @param accessInfoCreator Provides the information for the new {@link AccessInfo} to be created. + * @param scopeId + * The {@link ScopeId} in which to create the {@link AccessInfo}. + * @param accessInfoCreator + * Provides the information for the new {@link AccessInfo} to be created. * @return The newly created {@link AccessInfo} object. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @POST - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public Response create( @PathParam("scopeId") ScopeId scopeId, // AccessInfoCreator accessInfoCreator) throws KapuaException { @@ -153,15 +163,18 @@ public Response create( /** * Gets the {@link AccessInfo} specified by the "accessInfoId" path parameter. * - * @param scopeId The {@link ScopeId} of the requested {@link AccessInfo}. - * @param accessInfoId The id of the requested {@link AccessInfo}. + * @param scopeId + * The {@link ScopeId} of the requested {@link AccessInfo}. + * @param accessInfoId + * The id of the requested {@link AccessInfo}. * @return The requested {@link AccessInfo} object. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @GET @Path("{accessInfoId}") - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public AccessInfo find( @PathParam("scopeId") ScopeId scopeId, @PathParam("accessInfoId") EntityId accessInfoId) throws KapuaException { @@ -173,10 +186,13 @@ public AccessInfo find( /** * Deletes the {@link AccessInfo} specified by the "accessInfoId" path parameter. * - * @param scopeId The {@link ScopeId} of the {@link AccessInfo} to be deleted. - * @param accessInfoId The id of the {@link AccessInfo} to be deleted. + * @param scopeId + * The {@link ScopeId} of the {@link AccessInfo} to be deleted. + * @param accessInfoId + * The id of the {@link AccessInfo} to be deleted. * @return HTTP 200 if operation has completed successfully. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @DELETE diff --git a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/AccessPermissions.java b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/AccessPermissions.java index d6953da94f3..70bbddb320f 100644 --- a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/AccessPermissions.java +++ b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/AccessPermissions.java @@ -12,13 +12,26 @@ *******************************************************************************/ package org.eclipse.kapua.app.api.resources.v1.resources; -import com.google.common.base.Strings; +import javax.inject.Inject; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.DefaultValue; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.app.api.core.model.CountResult; import org.eclipse.kapua.app.api.core.model.EntityId; import org.eclipse.kapua.app.api.core.model.ScopeId; import org.eclipse.kapua.app.api.core.resources.AbstractKapuaResource; import org.eclipse.kapua.model.KapuaEntityAttributes; +import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.model.query.SortOrder; import org.eclipse.kapua.model.query.predicate.AndPredicate; import org.eclipse.kapua.service.KapuaService; @@ -26,23 +39,10 @@ import org.eclipse.kapua.service.authorization.access.AccessPermission; import org.eclipse.kapua.service.authorization.access.AccessPermissionAttributes; import org.eclipse.kapua.service.authorization.access.AccessPermissionCreator; -import org.eclipse.kapua.service.authorization.access.AccessPermissionFactory; import org.eclipse.kapua.service.authorization.access.AccessPermissionListResult; -import org.eclipse.kapua.service.authorization.access.AccessPermissionQuery; import org.eclipse.kapua.service.authorization.access.AccessPermissionService; -import javax.inject.Inject; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.DefaultValue; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; +import com.google.common.base.Strings; /** * {@link AccessPermission} REST API resource. @@ -54,24 +54,29 @@ public class AccessPermissions extends AbstractKapuaResource { @Inject public AccessPermissionService accessPermissionService; - @Inject - public AccessPermissionFactory accessPermissionFactory; /** * Gets the {@link AccessPermission} list in the scope. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param accessInfoId The optional {@link AccessInfo} id to filter results. - * @param offset The result set offset. - * @param limit The result set limit. - * @param sortParam The name of the parameter that will be used as a sorting key - * @param sortDir The sort direction. Can be ASCENDING (default), DESCENDING. Case-insensitive. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param accessInfoId + * The optional {@link AccessInfo} id to filter results. + * @param offset + * The result set offset. + * @param limit + * The result set limit. + * @param sortParam + * The name of the parameter that will be used as a sorting key + * @param sortDir + * The sort direction. Can be ASCENDING (default), DESCENDING. Case-insensitive. * @return The {@link AccessPermissionListResult} of all the {@link AccessPermission}s associated to the current selected scope. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @GET - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public AccessPermissionListResult simpleQuery( @PathParam("scopeId") ScopeId scopeId, @PathParam("accessInfoId") EntityId accessInfoId, @@ -80,7 +85,7 @@ public AccessPermissionListResult simpleQuery( @QueryParam("sortDir") @DefaultValue("ASCENDING") SortOrder sortDir, @QueryParam("offset") @DefaultValue("0") int offset, @QueryParam("limit") @DefaultValue("50") int limit) throws KapuaException { - AccessPermissionQuery query = accessPermissionFactory.newQuery(scopeId); + KapuaQuery query = new KapuaQuery(scopeId); query.setPredicate(query.attributePredicate(AccessPermissionAttributes.ACCESS_INFO_ID, accessInfoId)); if (!Strings.isNullOrEmpty(sortParam)) { @@ -95,23 +100,27 @@ public AccessPermissionListResult simpleQuery( } /** - * Queries the {@link AccessPermission}s with the given {@link AccessPermissionQuery} parameter. + * Queries the {@link AccessPermission}s with the given {@link KapuaQuery} parameter. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param accessInfoId The {@link AccessInfo} id in which to search results. - * @param query The {@link AccessPermissionQuery} to use to filter results. - * @return The {@link AccessPermissionListResult} of all the result matching the given {@link AccessPermissionQuery} parameter. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param accessInfoId + * The {@link AccessInfo} id in which to search results. + * @param query + * The {@link KapuaQuery} to use to filter results. + * @return The {@link AccessPermissionListResult} of all the result matching the given {@link KapuaQuery} parameter. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @POST @Path("_query") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public AccessPermissionListResult query( @PathParam("scopeId") ScopeId scopeId, @PathParam("accessInfoId") EntityId accessInfoId, - AccessPermissionQuery query) throws KapuaException { + KapuaQuery query) throws KapuaException { query.setScopeId(scopeId); @@ -121,23 +130,27 @@ public AccessPermissionListResult query( } /** - * Counts the {@link AccessPermission}s with the given {@link AccessPermissionQuery} parameter. + * Counts the {@link AccessPermission}s with the given {@link KapuaQuery} parameter. * - * @param scopeId The {@link ScopeId} in which to count results. - * @param accessInfoId The {@link AccessInfo} id in which to count results. - * @param query The {@link AccessPermissionQuery} to use to filter count results. - * @return The count of all the result matching the given {@link AccessPermissionQuery} parameter. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @param scopeId + * The {@link ScopeId} in which to count results. + * @param accessInfoId + * The {@link AccessInfo} id in which to count results. + * @param query + * The {@link KapuaQuery} to use to filter count results. + * @return The count of all the result matching the given {@link KapuaQuery} parameter. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @POST @Path("_count") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public CountResult count( @PathParam("scopeId") ScopeId scopeId, @PathParam("accessInfoId") EntityId accessInfoId, - AccessPermissionQuery query) throws KapuaException { + KapuaQuery query) throws KapuaException { query.setScopeId(scopeId); query.setPredicate(query.attributePredicate(AccessPermissionAttributes.ACCESS_INFO_ID, accessInfoId)); @@ -146,19 +159,22 @@ public CountResult count( } /** - * Creates a new {@link AccessPermission} based on the information provided in {@link AccessPermissionCreator} - * parameter. + * Creates a new {@link AccessPermission} based on the information provided in {@link AccessPermissionCreator} parameter. * - * @param scopeId The {@link ScopeId} in which to create the AccessPermission. - * @param accessInfoId The {@link AccessInfo} id in which to create the AccessPermission. - * @param accessPermissionCreator Provides the information for the new {@link AccessPermission} to be created. + * @param scopeId + * The {@link ScopeId} in which to create the AccessPermission. + * @param accessInfoId + * The {@link AccessInfo} id in which to create the AccessPermission. + * @param accessPermissionCreator + * Provides the information for the new {@link AccessPermission} to be created. * @return The newly created {@link AccessPermission} object. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @POST - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public Response create( @PathParam("scopeId") ScopeId scopeId, @PathParam("accessInfoId") EntityId accessInfoId, @@ -172,21 +188,25 @@ public Response create( /** * Returns the AccessPermission specified by the "accessPermissionId" path parameter. * - * @param scopeId The {@link ScopeId} of the requested {@link AccessPermission}. - * @param accessInfoId The {@link AccessInfo} id of the requested {@link AccessPermission}. - * @param accessPermissionId The id of the requested AccessPermission. + * @param scopeId + * The {@link ScopeId} of the requested {@link AccessPermission}. + * @param accessInfoId + * The {@link AccessInfo} id of the requested {@link AccessPermission}. + * @param accessPermissionId + * The id of the requested AccessPermission. * @return The requested AccessPermission object. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @GET @Path("{accessPermissionId}") - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public AccessPermission find( @PathParam("scopeId") ScopeId scopeId, @PathParam("accessInfoId") EntityId accessInfoId, @PathParam("accessPermissionId") EntityId accessPermissionId) throws KapuaException { - AccessPermissionQuery query = accessPermissionFactory.newQuery(scopeId); + final KapuaQuery query = new KapuaQuery(scopeId); AndPredicate andPredicate = query.andPredicate( query.attributePredicate(AccessPermissionAttributes.ACCESS_INFO_ID, accessInfoId), @@ -205,11 +225,15 @@ public AccessPermission find( /** * Deletes the {@link AccessPermission} specified by the "accessPermissionId" path parameter. * - * @param scopeId The {@link ScopeId} of the {@link AccessPermission} to delete. - * @param accessInfoId The {@link AccessInfo} id of the {@link AccessPermission} to delete. - * @param accessPermissionId The id of the AccessPermission to be deleted. + * @param scopeId + * The {@link ScopeId} of the {@link AccessPermission} to delete. + * @param accessInfoId + * The {@link AccessInfo} id of the {@link AccessPermission} to delete. + * @param accessPermissionId + * The id of the AccessPermission to be deleted. * @return HTTP 200 if operation has completed successfully. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @DELETE diff --git a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/AccessRoles.java b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/AccessRoles.java index dfcebe6ad41..a0b771b1a63 100644 --- a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/AccessRoles.java +++ b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/AccessRoles.java @@ -12,62 +12,63 @@ *******************************************************************************/ package org.eclipse.kapua.app.api.resources.v1.resources; +import javax.inject.Inject; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.DefaultValue; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.app.api.core.model.CountResult; import org.eclipse.kapua.app.api.core.model.EntityId; import org.eclipse.kapua.app.api.core.model.ScopeId; import org.eclipse.kapua.app.api.core.resources.AbstractKapuaResource; import org.eclipse.kapua.model.KapuaEntityAttributes; +import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.model.query.predicate.AndPredicate; import org.eclipse.kapua.service.KapuaService; import org.eclipse.kapua.service.authorization.access.AccessRole; import org.eclipse.kapua.service.authorization.access.AccessRoleAttributes; import org.eclipse.kapua.service.authorization.access.AccessRoleCreator; -import org.eclipse.kapua.service.authorization.access.AccessRoleFactory; import org.eclipse.kapua.service.authorization.access.AccessRoleListResult; -import org.eclipse.kapua.service.authorization.access.AccessRoleQuery; import org.eclipse.kapua.service.authorization.access.AccessRoleService; -import javax.inject.Inject; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.DefaultValue; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - @Path("{scopeId}/accessinfos/{accessInfoId}/roles") public class AccessRoles extends AbstractKapuaResource { @Inject public AccessRoleService accessRoleService; - @Inject - public AccessRoleFactory accessRoleFactory; /** * Gets the {@link AccessRole} list in the scope. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param offset The result set offset. - * @param limit The result set limit. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param offset + * The result set offset. + * @param limit + * The result set limit. * @return The {@link AccessRoleListResult} of all the accessRoles associated to the current selected scope. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @GET - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public AccessRoleListResult simpleQuery( @PathParam("scopeId") ScopeId scopeId, @PathParam("accessInfoId") EntityId accessInfoId, @QueryParam("askTotalCount") boolean askTotalCount, @QueryParam("offset") @DefaultValue("0") int offset, @QueryParam("limit") @DefaultValue("50") int limit) throws KapuaException { - AccessRoleQuery query = accessRoleFactory.newQuery(scopeId); + final KapuaQuery query = new KapuaQuery(scopeId); query.setPredicate(query.attributePredicate(AccessRoleAttributes.ACCESS_INFO_ID, accessInfoId)); @@ -79,22 +80,25 @@ public AccessRoleListResult simpleQuery( } /** - * Queries the results with the given {@link AccessRoleQuery} parameter. + * Queries the results with the given {@link KapuaQuery} parameter. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param query The {@link AccessRoleQuery} to use to filter results. - * @return The {@link AccessRoleListResult} of all the result matching the given {@link AccessRoleQuery} parameter. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param query + * The {@link KapuaQuery} to use to filter results. + * @return The {@link AccessRoleListResult} of all the result matching the given {@link KapuaQuery} parameter. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @POST @Path("_query") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public AccessRoleListResult query( @PathParam("scopeId") ScopeId scopeId, @PathParam("accessInfoId") EntityId accessInfoId, - AccessRoleQuery query) throws KapuaException { + KapuaQuery query) throws KapuaException { query.setScopeId(scopeId); query.setPredicate(query.attributePredicate(AccessRoleAttributes.ACCESS_INFO_ID, accessInfoId)); @@ -103,22 +107,25 @@ public AccessRoleListResult query( } /** - * Counts the results with the given {@link AccessRoleQuery} parameter. + * Counts the results with the given {@link KapuaQuery} parameter. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param query The {@link AccessRoleQuery} to use to filter results. - * @return The count of all the result matching the given {@link AccessRoleQuery} parameter. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param query + * The {@link KapuaQuery} to use to filter results. + * @return The count of all the result matching the given {@link KapuaQuery} parameter. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @POST @Path("_count") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public CountResult count( @PathParam("scopeId") ScopeId scopeId, @PathParam("accessInfoId") EntityId accessInfoId, - AccessRoleQuery query) throws KapuaException { + KapuaQuery query) throws KapuaException { query.setScopeId(scopeId); query.setPredicate(query.attributePredicate(AccessRoleAttributes.ACCESS_INFO_ID, accessInfoId)); @@ -127,18 +134,20 @@ public CountResult count( } /** - * Creates a new AccessRole based on the information provided in AccessRoleCreator - * parameter. + * Creates a new AccessRole based on the information provided in AccessRoleCreator parameter. * - * @param scopeId The {@link ScopeId} in which to create the {@link AccessRole}. - * @param accessRoleCreator Provides the information for the new AccessRole to be created. + * @param scopeId + * The {@link ScopeId} in which to create the {@link AccessRole}. + * @param accessRoleCreator + * Provides the information for the new AccessRole to be created. * @return The newly created {@link AccessRole} object. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @POST - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public Response create( @PathParam("scopeId") ScopeId scopeId, @PathParam("accessInfoId") EntityId accessInfoId, @@ -152,20 +161,23 @@ public Response create( /** * Returns the AccessRole specified by the "accessRoleId" path parameter. * - * @param scopeId The {@link ScopeId} of the requested {@link AccessRole}. - * @param accessRoleId The id of the requested {@link AccessRole}. + * @param scopeId + * The {@link ScopeId} of the requested {@link AccessRole}. + * @param accessRoleId + * The id of the requested {@link AccessRole}. * @return The requested {@link AccessRole} object. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @GET @Path("{accessRoleId}") - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public AccessRole find( @PathParam("scopeId") ScopeId scopeId, @PathParam("accessInfoId") EntityId accessInfoId, @PathParam("accessRoleId") EntityId accessRoleId) throws KapuaException { - AccessRoleQuery query = accessRoleFactory.newQuery(scopeId); + final KapuaQuery query = new KapuaQuery(scopeId); AndPredicate andPredicate = query.andPredicate( query.attributePredicate(AccessRoleAttributes.ACCESS_INFO_ID, accessInfoId), @@ -184,9 +196,11 @@ public AccessRole find( /** * Deletes the AccessRole specified by the "accessRoleId" path parameter. * - * @param accessRoleId The id of the AccessRole to be deleted. + * @param accessRoleId + * The id of the AccessRole to be deleted. * @return HTTP 200 if operation has completed successfully. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @DELETE diff --git a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/Accounts.java b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/Accounts.java index 4bfc274aba2..b1caad4293e 100644 --- a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/Accounts.java +++ b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/Accounts.java @@ -32,6 +32,7 @@ import org.eclipse.kapua.app.api.core.model.ScopeId; import org.eclipse.kapua.app.api.core.resources.AbstractKapuaResource; import org.eclipse.kapua.model.KapuaNamedEntityAttributes; +import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.model.query.SortOrder; import org.eclipse.kapua.model.query.predicate.AndPredicate; import org.eclipse.kapua.model.query.predicate.MatchPredicate; @@ -39,9 +40,7 @@ import org.eclipse.kapua.service.account.Account; import org.eclipse.kapua.service.account.AccountAttributes; import org.eclipse.kapua.service.account.AccountCreator; -import org.eclipse.kapua.service.account.AccountFactory; import org.eclipse.kapua.service.account.AccountListResult; -import org.eclipse.kapua.service.account.AccountQuery; import org.eclipse.kapua.service.account.AccountService; import com.google.common.base.Strings; @@ -51,8 +50,6 @@ public class Accounts extends AbstractKapuaResource { @Inject public AccountService accountService; - @Inject - public AccountFactory accountFactory; /** * Gets the {@link Account} list in the scope. @@ -93,7 +90,7 @@ public AccountListResult simpleQuery( return accountService.findChildrenRecursively(scopeId); } - AccountQuery query = accountFactory.newQuery(scopeId); + final KapuaQuery query = new KapuaQuery(scopeId); query.setAskTotalCount(askTotalCount); AndPredicate andPredicate = query.andPredicate(); @@ -126,13 +123,13 @@ public String getMatchTerm() { } /** - * Queries the results with the given {@link AccountQuery} parameter. + * Queries the results with the given {@link KapuaQuery} parameter. * * @param scopeId * The {@link ScopeId} in which to search results. * @param query - * The {@link AccountQuery} to use to filter results. - * @return The {@link AccountListResult} of all the result matching the given {@link AccountQuery} parameter. + * The {@link KapuaQuery} to use to filter results. + * @return The {@link AccountListResult} of all the result matching the given {@link KapuaQuery} parameter. * @throws KapuaException * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 @@ -143,20 +140,20 @@ public String getMatchTerm() { @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public AccountListResult query( @PathParam("scopeId") ScopeId scopeId, // - AccountQuery query) throws KapuaException { + KapuaQuery query) throws KapuaException { query.setScopeId(scopeId); return accountService.query(query); } /** - * Counts the results with the given {@link AccountQuery} parameter. + * Counts the results with the given {@link KapuaQuery} parameter. * * @param scopeId * The {@link ScopeId} in which to count results. * @param query - * The {@link AccountQuery} to use to filter results. - * @return The count of all the result matching the given {@link AccountQuery} parameter. + * The {@link KapuaQuery} to use to filter results. + * @return The count of all the result matching the given {@link KapuaQuery} parameter. * @throws KapuaException * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 @@ -168,7 +165,7 @@ public AccountListResult query( @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public CountResult count( @PathParam("scopeId") ScopeId scopeId, // - AccountQuery query) throws KapuaException { + KapuaQuery query) throws KapuaException { query.setScopeId(scopeId); return new CountResult(accountService.count(query)); diff --git a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/Credentials.java b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/Credentials.java index a40032f1612..cb9b3e50f87 100644 --- a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/Credentials.java +++ b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/Credentials.java @@ -26,13 +26,13 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -import com.google.common.base.Strings; import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.app.api.core.model.CountResult; import org.eclipse.kapua.app.api.core.model.EntityId; import org.eclipse.kapua.app.api.core.model.ScopeId; import org.eclipse.kapua.app.api.core.model.SetResult; import org.eclipse.kapua.app.api.core.resources.AbstractKapuaResource; +import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.model.query.SortOrder; import org.eclipse.kapua.model.query.predicate.AndPredicate; import org.eclipse.kapua.service.KapuaService; @@ -41,9 +41,10 @@ import org.eclipse.kapua.service.authentication.credential.CredentialCreator; import org.eclipse.kapua.service.authentication.credential.CredentialFactory; import org.eclipse.kapua.service.authentication.credential.CredentialListResult; -import org.eclipse.kapua.service.authentication.credential.CredentialQuery; import org.eclipse.kapua.service.authentication.credential.CredentialService; +import com.google.common.base.Strings; + @Path("{scopeId}/credentials") public class Credentials extends AbstractKapuaResource { @@ -53,19 +54,22 @@ public class Credentials extends AbstractKapuaResource { @Inject public CredentialFactory credentialFactory; - /** * Gets the {@link Credential} list in the scope. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param offset The result set offset. - * @param limit The result set limit. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param offset + * The result set offset. + * @param limit + * The result set limit. * @return The {@link CredentialListResult} of all the credentials associated to the current selected scope. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @GET - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public CredentialListResult simpleQuery( @PathParam("scopeId") ScopeId scopeId, @QueryParam("userId") EntityId userId, @@ -74,7 +78,7 @@ public CredentialListResult simpleQuery( @QueryParam("sortDir") @DefaultValue("ASCENDING") SortOrder sortDir, @QueryParam("offset") @DefaultValue("0") int offset, @QueryParam("limit") @DefaultValue("50") int limit) throws KapuaException { - CredentialQuery query = credentialFactory.newQuery(scopeId); + final KapuaQuery query = new KapuaQuery(scopeId); AndPredicate andPredicate = query.andPredicate(); if (userId != null) { @@ -93,60 +97,68 @@ public CredentialListResult simpleQuery( } /** - * Queries the results with the given {@link CredentialQuery} parameter. + * Queries the results with the given {@link KapuaQuery} parameter. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param query The {@link CredentialQuery} to use to filter results. - * @return The {@link CredentialListResult} of all the result matching the given {@link CredentialQuery} parameter. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param query + * The {@link KapuaQuery} to use to filter results. + * @return The {@link CredentialListResult} of all the result matching the given {@link KapuaQuery} parameter. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @POST @Path("_query") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public CredentialListResult query( @PathParam("scopeId") ScopeId scopeId, - CredentialQuery query) throws KapuaException { + KapuaQuery query) throws KapuaException { query.setScopeId(scopeId); return credentialService.query(query); } /** - * Counts the results with the given {@link CredentialQuery} parameter. + * Counts the results with the given {@link KapuaQuery} parameter. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param query The {@link CredentialQuery} to use to filter results. - * @return The count of all the result matching the given {@link CredentialQuery} parameter. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param query + * The {@link KapuaQuery} to use to filter results. + * @return The count of all the result matching the given {@link KapuaQuery} parameter. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @POST @Path("_count") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public CountResult count( @PathParam("scopeId") ScopeId scopeId, - CredentialQuery query) throws KapuaException { + KapuaQuery query) throws KapuaException { query.setScopeId(scopeId); return new CountResult(credentialService.count(query)); } /** - * Creates a new Credential based on the information provided in CredentialCreator - * parameter. + * Creates a new Credential based on the information provided in CredentialCreator parameter. * - * @param scopeId The {@link ScopeId} in which to create the {@link Credential} - * @param credentialCreator Provides the information for the new Credential to be created. + * @param scopeId + * The {@link ScopeId} in which to create the {@link Credential} + * @param credentialCreator + * Provides the information for the new Credential to be created. * @return The newly created Credential object. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @POST - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public Response create( @PathParam("scopeId") ScopeId scopeId, CredentialCreator credentialCreator) throws KapuaException { @@ -158,15 +170,18 @@ public Response create( /** * Returns the Credential specified by the "credentialId" path parameter. * - * @param scopeId The {@link ScopeId} of the requested {@link Credential}. - * @param credentialId The id of the requested Credential. + * @param scopeId + * The {@link ScopeId} of the requested {@link Credential}. + * @param credentialId + * The id of the requested Credential. * @return The requested Credential object. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @GET @Path("{credentialId}") - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public Credential find( @PathParam("scopeId") ScopeId scopeId, @PathParam("credentialId") EntityId credentialId) throws KapuaException { @@ -178,15 +193,17 @@ public Credential find( /** * Updates the Credential based on the information provided in the Credential parameter. * - * @param credential The modified Credential whose attributed need to be updated. + * @param credential + * The modified Credential whose attributed need to be updated. * @return The updated credential. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @PUT @Path("{credentialId}") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public Credential update( @PathParam("scopeId") ScopeId scopeId, @PathParam("credentialId") EntityId credentialId, @@ -200,9 +217,11 @@ public Credential update( /** * Deletes the Credential specified by the "credentialId" path parameter. * - * @param credentialId The id of the Credential to be deleted. + * @param credentialId + * The id of the Credential to be deleted. * @return HTTP 200 if operation has completed successfully. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @DELETE @@ -215,14 +234,16 @@ public Response deleteCredential( return returnNoContent(); } - /** * Unlocks a {@link Credential} that has been locked due to a lockout policy. * - * @param scopeId The {@link ScopeId} of {@link Credential} to unlock. - * @param credentialId The id of the Credential to be unlocked. + * @param scopeId + * The {@link ScopeId} of {@link Credential} to unlock. + * @param credentialId + * The id of the Credential to be unlocked. * @return HTTP 200 if operation has completed successfully. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 * @deprecated Since 2.0.0. Please make use of {@link #unlock(ScopeId, EntityId)} */ @@ -237,14 +258,16 @@ public Response unlockCredential( return returnNoContent(); } - /** * Unlocks a {@link Credential} that has been locked due to a lockout policy. * - * @param scopeId The {@link ScopeId} of {@link Credential} to unlock. - * @param credentialId The id of the Credential to be unlocked. + * @param scopeId + * The {@link ScopeId} of {@link Credential} to unlock. + * @param credentialId + * The id of the Credential to be unlocked. * @return HTTP 200 if operation has completed successfully. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 2.0.0 */ @POST @@ -257,10 +280,9 @@ public Response unlock( return returnNoContent(); } - @GET @Path("_availableCredentials") - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public SetResult getAvailableAuthAdapter() throws KapuaException { return new SetResult(credentialService.getAvailableCredentialTypes()); } diff --git a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/DataChannels.java b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/DataChannels.java index dcd7bd12cba..95d04f857df 100644 --- a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/DataChannels.java +++ b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/DataChannels.java @@ -36,12 +36,11 @@ import org.eclipse.kapua.app.api.core.resources.AbstractKapuaResource; import org.eclipse.kapua.model.query.SortOrder; import org.eclipse.kapua.service.KapuaService; -import org.eclipse.kapua.service.datastore.ChannelInfoFactory; import org.eclipse.kapua.service.datastore.ChannelInfoRegistryService; -import org.eclipse.kapua.service.datastore.internal.mediator.ChannelInfoField; import org.eclipse.kapua.service.datastore.internal.model.query.predicate.ChannelMatchPredicateImpl; import org.eclipse.kapua.service.datastore.model.ChannelInfo; import org.eclipse.kapua.service.datastore.model.ChannelInfoListResult; +import org.eclipse.kapua.service.datastore.model.query.ChannelInfoField; import org.eclipse.kapua.service.datastore.model.query.ChannelInfoQuery; import org.eclipse.kapua.service.datastore.model.query.predicate.ChannelMatchPredicate; import org.eclipse.kapua.service.datastore.model.query.predicate.DatastorePredicateFactory; @@ -59,8 +58,6 @@ public class DataChannels extends AbstractKapuaResource { @Inject public ChannelInfoRegistryService channelInfoRegistryService; @Inject - public ChannelInfoFactory channelInfoFactory; - @Inject public DatastorePredicateFactory datastorePredicateFactory; /** @@ -114,7 +111,7 @@ public ChannelInfoListResult simpleQuery(@PathParam("scopeId") ScopeId scopeId, andPredicate.getPredicates().add(channelPredicate); } - ChannelInfoQuery query = channelInfoFactory.newQuery(scopeId); + ChannelInfoQuery query = new ChannelInfoQuery(scopeId); query.setPredicate(andPredicate); query.setOffset(offset); query.setLimit(limit); diff --git a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/DataClients.java b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/DataClients.java index 04cc47abf10..863cefef04d 100644 --- a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/DataClients.java +++ b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/DataClients.java @@ -34,11 +34,10 @@ import org.eclipse.kapua.app.api.core.model.StorableEntityId; import org.eclipse.kapua.app.api.core.resources.AbstractKapuaResource; import org.eclipse.kapua.service.KapuaService; -import org.eclipse.kapua.service.datastore.ClientInfoFactory; import org.eclipse.kapua.service.datastore.ClientInfoRegistryService; -import org.eclipse.kapua.service.datastore.internal.mediator.ClientInfoField; import org.eclipse.kapua.service.datastore.model.ClientInfo; import org.eclipse.kapua.service.datastore.model.ClientInfoListResult; +import org.eclipse.kapua.service.datastore.model.query.ClientInfoField; import org.eclipse.kapua.service.datastore.model.query.ClientInfoQuery; import org.eclipse.kapua.service.datastore.model.query.predicate.DatastorePredicateFactory; import org.eclipse.kapua.service.storable.model.query.predicate.AndPredicate; @@ -53,8 +52,6 @@ public class DataClients extends AbstractKapuaResource { @Inject public ClientInfoRegistryService clientInfoRegistryService; @Inject - public ClientInfoFactory clientInfoFactory; - @Inject public DatastorePredicateFactory datastorePredicateFactory; /** @@ -94,7 +91,7 @@ public ClientInfoListResult simpleQuery(@PathParam("scopeId") ScopeId scopeId, andPredicate.addPredicate(orPredicate); } - ClientInfoQuery query = clientInfoFactory.newQuery(scopeId); + ClientInfoQuery query = new ClientInfoQuery(scopeId); query.setPredicate(andPredicate); diff --git a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/DataMessages.java b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/DataMessages.java index 99ca6fb94b2..8903b5c9149 100644 --- a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/DataMessages.java +++ b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/DataMessages.java @@ -43,12 +43,12 @@ import org.eclipse.kapua.service.KapuaService; import org.eclipse.kapua.service.datastore.MessageStoreFactory; import org.eclipse.kapua.service.datastore.MessageStoreService; -import org.eclipse.kapua.service.datastore.internal.mediator.ChannelInfoField; -import org.eclipse.kapua.service.datastore.internal.mediator.MessageField; -import org.eclipse.kapua.service.datastore.internal.schema.MessageSchema; import org.eclipse.kapua.service.datastore.model.DatastoreMessage; import org.eclipse.kapua.service.datastore.model.MessageListResult; +import org.eclipse.kapua.service.datastore.model.query.ChannelInfoField; +import org.eclipse.kapua.service.datastore.model.query.MessageField; import org.eclipse.kapua.service.datastore.model.query.MessageQuery; +import org.eclipse.kapua.service.datastore.model.query.MessageSchema; import org.eclipse.kapua.service.datastore.model.query.predicate.DatastorePredicateFactory; import org.eclipse.kapua.service.elasticsearch.client.model.InsertResponse; import org.eclipse.kapua.service.storable.model.query.SortDirection; @@ -252,7 +252,7 @@ protected static > MessageQuery parametersToQuery( andPredicate.getPredicates().add(getMetricPredicate(datastorePredicateFactory, metricName, metricType, metricMinValue, metricMaxValue)); } - MessageQuery query = messageStoreFactory.newQuery(scopeId); + MessageQuery query = new MessageQuery(scopeId); query.setPredicate(andPredicate); query.setOffset(offset); query.setLimit(limit); diff --git a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/DataMessagesJson.java b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/DataMessagesJson.java index e27df7455d7..032b17d7da9 100644 --- a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/DataMessagesJson.java +++ b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/DataMessagesJson.java @@ -229,7 +229,7 @@ public JsonDatastoreMessage findJson(@PathParam("scopeId") ScopeId scopeId, } private MessageQuery convertQuery(JsonMessageQuery query) { - MessageQuery messageQuery = messageStoreFactory.newQuery(query.getScopeId()); + MessageQuery messageQuery = new MessageQuery(query.getScopeId()); messageQuery.setAskTotalCount(query.isAskTotalCount()); messageQuery.setFetchAttributes(query.getFetchAttributes()); messageQuery.setFetchStyle(query.getFetchStyle()); diff --git a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/DataMetrics.java b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/DataMetrics.java index 650b0245928..ae18bc99ecb 100644 --- a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/DataMetrics.java +++ b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/DataMetrics.java @@ -35,10 +35,10 @@ import org.eclipse.kapua.app.api.core.resources.AbstractKapuaResource; import org.eclipse.kapua.service.datastore.MetricInfoFactory; import org.eclipse.kapua.service.datastore.MetricInfoRegistryService; -import org.eclipse.kapua.service.datastore.internal.mediator.MetricInfoField; import org.eclipse.kapua.service.datastore.internal.model.query.predicate.ChannelMatchPredicateImpl; import org.eclipse.kapua.service.datastore.model.MetricInfo; import org.eclipse.kapua.service.datastore.model.MetricInfoListResult; +import org.eclipse.kapua.service.datastore.model.query.MetricInfoField; import org.eclipse.kapua.service.datastore.model.query.MetricInfoQuery; import org.eclipse.kapua.service.datastore.model.query.predicate.ChannelMatchPredicate; import org.eclipse.kapua.service.datastore.model.query.predicate.DatastorePredicateFactory; @@ -110,7 +110,7 @@ public MetricInfoListResult simpleQuery(@PathParam("scopeId") ScopeId scopeId, andPredicate.getPredicates().add(clientIdPredicate); } - MetricInfoQuery query = metricInfoFactory.newQuery(scopeId); + MetricInfoQuery query = new MetricInfoQuery(scopeId); query.setPredicate(andPredicate); query.setOffset(offset); query.setLimit(limit); diff --git a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/DeviceConnections.java b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/DeviceConnections.java index dc4bf788d2d..0235f37fc17 100644 --- a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/DeviceConnections.java +++ b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/DeviceConnections.java @@ -12,7 +12,18 @@ *******************************************************************************/ package org.eclipse.kapua.app.api.resources.v1.resources; -import com.google.common.base.Strings; +import javax.inject.Inject; +import javax.ws.rs.Consumes; +import javax.ws.rs.DefaultValue; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.app.api.core.model.CountResult; import org.eclipse.kapua.app.api.core.model.EntityId; @@ -30,17 +41,7 @@ import org.eclipse.kapua.service.device.registry.connection.DeviceConnectionService; import org.eclipse.kapua.service.device.registry.connection.DeviceConnectionStatus; -import javax.inject.Inject; -import javax.ws.rs.Consumes; -import javax.ws.rs.DefaultValue; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; +import com.google.common.base.Strings; @Path("{scopeId}/deviceconnections") public class DeviceConnections extends AbstractKapuaResource { @@ -53,17 +54,23 @@ public class DeviceConnections extends AbstractKapuaResource { /** * Gets the {@link DeviceConnection} list in the scope. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param clientId The id of the {@link Device} in which to search results - * @param status The {@link DeviceConnectionStatus} in which to search results - * @param offset The result set offset. - * @param limit The result set limit. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param clientId + * The id of the {@link Device} in which to search results + * @param status + * The {@link DeviceConnectionStatus} in which to search results + * @param offset + * The result set offset. + * @param limit + * The result set limit. * @return The {@link DeviceConnectionListResult} of all the deviceConnections associated to the current selected scope. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @GET - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public DeviceConnectionListResult simpleQuery( @PathParam("scopeId") ScopeId scopeId, @QueryParam("clientId") String clientId, @@ -72,7 +79,7 @@ public DeviceConnectionListResult simpleQuery( @QueryParam("status") DeviceConnectionStatus status, @QueryParam("offset") @DefaultValue("0") int offset, @QueryParam("limit") @DefaultValue("50") int limit) throws KapuaException { - DeviceConnectionQuery query = deviceConnectionFactory.newQuery(scopeId); + DeviceConnectionQuery query = new DeviceConnectionQuery(scopeId); AndPredicate andPredicate = query.andPredicate(); if (!Strings.isNullOrEmpty(clientId)) { @@ -98,16 +105,19 @@ public DeviceConnectionListResult simpleQuery( /** * Queries the results with the given {@link DeviceConnectionQuery} parameter. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param query The {@link DeviceConnectionQuery} to use to filter results. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param query + * The {@link DeviceConnectionQuery} to use to filter results. * @return The {@link DeviceConnectionListResult} of all the result matching the given {@link DeviceConnectionQuery} parameter. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @POST @Path("_query") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public DeviceConnectionListResult query( @PathParam("scopeId") ScopeId scopeId, DeviceConnectionQuery query) throws KapuaException { @@ -119,16 +129,19 @@ public DeviceConnectionListResult query( /** * Counts the results with the given {@link DeviceConnectionQuery} parameter. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param query The {@link DeviceConnectionQuery} to use to filter results. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param query + * The {@link DeviceConnectionQuery} to use to filter results. * @return The count of all the result matching the given {@link DeviceConnectionQuery} parameter. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @POST @Path("_count") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public CountResult count( @PathParam("scopeId") ScopeId scopeId, DeviceConnectionQuery query) throws KapuaException { @@ -140,15 +153,18 @@ public CountResult count( /** * Returns the DeviceConnection specified by the "deviceConnectionId" path parameter. * - * @param scopeId The {@link ScopeId} of the requested {@link DeviceConnection}. - * @param deviceConnectionId The id of the requested DeviceConnection. + * @param scopeId + * The {@link ScopeId} of the requested {@link DeviceConnection}. + * @param deviceConnectionId + * The id of the requested DeviceConnection. * @return The requested DeviceConnection object. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @GET @Path("{deviceConnectionId}") - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public DeviceConnection find( @PathParam("scopeId") ScopeId scopeId, @PathParam("deviceConnectionId") EntityId deviceConnectionId) throws KapuaException { @@ -159,7 +175,7 @@ public DeviceConnection find( @GET @Path("_availableAuth") - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public SetResult getAvailableAuthAdapter() { return new SetResult(deviceConnectionService.getAvailableAuthTypes()); } @@ -167,15 +183,18 @@ public SetResult getAvailableAuthAdapter() { /** * Request that the DeviceConnection specified by the "deviceConnectionId" is disconnected from the broker. * - * @param scopeId The {@link ScopeId} of the requested {@link DeviceConnection}. - * @param deviceConnectionId The id of the requested DeviceConnection. + * @param scopeId + * The {@link ScopeId} of the requested {@link DeviceConnection}. + * @param deviceConnectionId + * The id of the requested DeviceConnection. * @return HTTP 200 if operation has completed successfully. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 2.0.0 */ @POST @Path("{deviceConnectionId}/_disconnect") - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public Response disconnect( @PathParam("scopeId") ScopeId scopeId, @PathParam("deviceConnectionId") EntityId deviceConnectionId) throws KapuaException { diff --git a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/DeviceEvents.java b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/DeviceEvents.java index 082f3f688e4..c9a3ee957f0 100644 --- a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/DeviceEvents.java +++ b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/DeviceEvents.java @@ -12,7 +12,19 @@ *******************************************************************************/ package org.eclipse.kapua.app.api.resources.v1.resources; -import com.google.common.base.Strings; +import javax.inject.Inject; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.DefaultValue; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + import org.eclipse.kapua.KapuaEntityNotFoundException; import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.app.api.core.model.CountResult; @@ -34,18 +46,7 @@ import org.eclipse.kapua.service.device.registry.event.DeviceEventQuery; import org.eclipse.kapua.service.device.registry.event.DeviceEventService; -import javax.inject.Inject; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.DefaultValue; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; +import com.google.common.base.Strings; @Path("{scopeId}/devices/{deviceId}/events") public class DeviceEvents extends AbstractKapuaResource { @@ -60,20 +61,29 @@ public class DeviceEvents extends AbstractKapuaResource { /** * Gets the {@link DeviceEvent} list in the scope. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param deviceId The id of the {@link Device} in which to search results - * @param resource The resource of the {@link DeviceEvent} in which to search results - * @param sortParam The name of the parameter that will be used as a sorting key - * @param sortDir The sort direction. Can be ASCENDING (default), DESCENDING. Case-insensitive. - * @param askTotalCount Ask for the total count of the matched entities in the result - * @param offset The result set offset. - * @param limit The result set limit. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param deviceId + * The id of the {@link Device} in which to search results + * @param resource + * The resource of the {@link DeviceEvent} in which to search results + * @param sortParam + * The name of the parameter that will be used as a sorting key + * @param sortDir + * The sort direction. Can be ASCENDING (default), DESCENDING. Case-insensitive. + * @param askTotalCount + * Ask for the total count of the matched entities in the result + * @param offset + * The result set offset. + * @param limit + * The result set limit. * @return The {@link DeviceEventListResult} of all the deviceEvents associated to the current selected scope. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @GET - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public DeviceEventListResult simpleQuery( @PathParam("scopeId") ScopeId scopeId, @PathParam("deviceId") EntityId deviceId, @@ -85,7 +95,7 @@ public DeviceEventListResult simpleQuery( @QueryParam("askTotalCount") boolean askTotalCount, @QueryParam("offset") @DefaultValue("0") int offset, @QueryParam("limit") @DefaultValue("50") int limit) throws KapuaException { - DeviceEventQuery query = deviceEventFactory.newQuery(scopeId); + DeviceEventQuery query = new DeviceEventQuery(scopeId); if (deviceRegistryService.find(scopeId, deviceId) == null) { throw new KapuaEntityNotFoundException(Device.TYPE, deviceId); @@ -119,17 +129,21 @@ public DeviceEventListResult simpleQuery( /** * Queries the results with the given {@link DeviceEventQuery} parameter. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param deviceId The id of the {@link Device} in which to search results - * @param query The {@link DeviceEventQuery} to use to filter results. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param deviceId + * The id of the {@link Device} in which to search results + * @param query + * The {@link DeviceEventQuery} to use to filter results. * @return The {@link DeviceEventListResult} of all the result matching the given {@link DeviceEventQuery} parameter. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @POST @Path("_query") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public DeviceEventListResult query( @PathParam("scopeId") ScopeId scopeId, @PathParam("deviceId") EntityId deviceId, @@ -153,17 +167,21 @@ public DeviceEventListResult query( /** * Counts the results with the given {@link DeviceEventQuery} parameter. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param deviceId The id of the {@link Device} in which to search results - * @param query The {@link DeviceEventQuery} to use to filter results. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param deviceId + * The id of the {@link Device} in which to search results + * @param query + * The {@link DeviceEventQuery} to use to filter results. * @return The count of all the result matching the given {@link DeviceEventQuery} parameter. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @POST @Path("_count") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public CountResult count( @PathParam("scopeId") ScopeId scopeId, @PathParam("deviceId") EntityId deviceId, @@ -182,16 +200,20 @@ public CountResult count( /** * Returns the DeviceEvent specified by the "deviceEventId" path parameter. * - * @param scopeId The {@link ScopeId} of the requested {@link DeviceEvent}. - * @param deviceId The {@link Device} id of the request {@link DeviceEvent}. - * @param deviceEventId The id of the requested DeviceEvent. + * @param scopeId + * The {@link ScopeId} of the requested {@link DeviceEvent}. + * @param deviceId + * The {@link Device} id of the request {@link DeviceEvent}. + * @param deviceEventId + * The id of the requested DeviceEvent. * @return The requested DeviceEvent object. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @GET @Path("{deviceEventId}") - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public DeviceEvent find( @PathParam("scopeId") ScopeId scopeId, @PathParam("deviceId") EntityId deviceId, @@ -201,7 +223,7 @@ public DeviceEvent find( throw new KapuaEntityNotFoundException(Device.TYPE, deviceId); } - DeviceEventQuery query = deviceEventFactory.newQuery(scopeId); + DeviceEventQuery query = new DeviceEventQuery(scopeId); AndPredicate andPredicate = query.andPredicate( query.attributePredicate(DeviceEventAttributes.DEVICE_ID, deviceId), @@ -220,17 +242,20 @@ public DeviceEvent find( /** * Deletes the DeviceEvent specified by the "deviceEventId" path parameter. * - * @param deviceId The id of the Device in which to delete the event - * @param deviceEventId The id of the DeviceEvent to be deleted. + * @param deviceId + * The id of the Device in which to delete the event + * @param deviceEventId + * The id of the DeviceEvent to be deleted. * @return HTTP 200 if operation has completed successfully. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @DELETE @Path("{deviceEventId}") public Response deleteDeviceEvent(@PathParam("scopeId") ScopeId scopeId, - @PathParam("deviceId") EntityId deviceId, - @PathParam("deviceEventId") EntityId deviceEventId) throws KapuaException { + @PathParam("deviceId") EntityId deviceId, + @PathParam("deviceEventId") EntityId deviceEventId) throws KapuaException { if (deviceRegistryService.find(scopeId, deviceId) == null) { throw new KapuaEntityNotFoundException(Device.TYPE, deviceId); diff --git a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/DeviceManagementAssets.java b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/DeviceManagementAssets.java index a3e12cc6f7d..dbc41596fd2 100644 --- a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/DeviceManagementAssets.java +++ b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/DeviceManagementAssets.java @@ -12,19 +12,6 @@ *******************************************************************************/ package org.eclipse.kapua.app.api.resources.v1.resources; -import org.eclipse.kapua.KapuaException; -import org.eclipse.kapua.app.api.core.model.EntityId; -import org.eclipse.kapua.app.api.core.model.ScopeId; -import org.eclipse.kapua.app.api.core.resources.AbstractKapuaResource; -import org.eclipse.kapua.service.KapuaService; -import org.eclipse.kapua.service.device.management.asset.DeviceAssetChannel; -import org.eclipse.kapua.service.device.management.asset.DeviceAssetFactory; -import org.eclipse.kapua.service.device.management.asset.DeviceAssetManagementService; -import org.eclipse.kapua.service.device.management.asset.DeviceAssets; -import org.eclipse.kapua.service.device.management.asset.store.DeviceAssetStoreService; -import org.eclipse.kapua.service.device.management.asset.store.settings.DeviceAssetStoreSettings; -import org.eclipse.kapua.service.device.registry.Device; - import javax.inject.Inject; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; @@ -37,47 +24,65 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; +import org.eclipse.kapua.KapuaException; +import org.eclipse.kapua.app.api.core.model.EntityId; +import org.eclipse.kapua.app.api.core.model.ScopeId; +import org.eclipse.kapua.app.api.core.resources.AbstractKapuaResource; +import org.eclipse.kapua.service.KapuaService; +import org.eclipse.kapua.service.device.management.asset.DeviceAssetChannel; +import org.eclipse.kapua.service.device.management.asset.DeviceAssetManagementService; +import org.eclipse.kapua.service.device.management.asset.DeviceAssets; +import org.eclipse.kapua.service.device.management.asset.store.DeviceAssetStoreService; +import org.eclipse.kapua.service.device.management.asset.store.settings.DeviceAssetStoreSettings; +import org.eclipse.kapua.service.device.registry.Device; + @Path("{scopeId}/devices/{deviceId}/assets") public class DeviceManagementAssets extends AbstractKapuaResource { @Inject public DeviceAssetManagementService deviceManagementAssetService; @Inject - public DeviceAssetFactory deviceAssetFilter; - @Inject public DeviceAssetStoreService deviceAssetStoreService; /** * Returns the list of all the Assets configured on the device. * - * @param scopeId The {@link ScopeId} of the {@link Device}. - * @param deviceId The id of the device - * @param timeout The timeout of the operation in milliseconds + * @param scopeId + * The {@link ScopeId} of the {@link Device}. + * @param deviceId + * The id of the device + * @param timeout + * The timeout of the operation in milliseconds * @return The list of Assets - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @GET - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public DeviceAssets get( @PathParam("scopeId") ScopeId scopeId, @PathParam("deviceId") EntityId deviceId, @QueryParam("timeout") @DefaultValue("30000") Long timeout) throws KapuaException { - return get(scopeId, deviceId, timeout, deviceAssetFilter.newAssetListResult()); + return get(scopeId, deviceId, timeout, new DeviceAssets()); } /** * Returns the list of all the Assets configured on the device filtered by the {@link DeviceAssets} parameter. * - * @param scopeId The {@link ScopeId} of the {@link Device}. - * @param deviceId The id of the device - * @param timeout The timeout of the operation in milliseconds + * @param scopeId + * The {@link ScopeId} of the {@link Device}. + * @param deviceId + * The id of the device + * @param timeout + * The timeout of the operation in milliseconds * @return The list of Assets - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @POST - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public DeviceAssets get( @PathParam("scopeId") ScopeId scopeId, @PathParam("deviceId") EntityId deviceId, @@ -89,16 +94,20 @@ public DeviceAssets get( /** * Reads {@link DeviceAssetChannel}s values available on the device filtered by the {@link DeviceAssets} parameter. * - * @param scopeId The {@link ScopeId} of the {@link Device}. - * @param deviceId The id of the device - * @param timeout The timeout of the operation in milliseconds + * @param scopeId + * The {@link ScopeId} of the {@link Device}. + * @param deviceId + * The id of the device + * @param timeout + * The timeout of the operation in milliseconds * @return The list of Assets - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @POST @Path("_read") - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public DeviceAssets read( @PathParam("scopeId") ScopeId scopeId, @PathParam("deviceId") EntityId deviceId, @@ -110,16 +119,20 @@ public DeviceAssets read( /** * Writes {@link DeviceAssetChannel}s configured on the device filtered by the {@link DeviceAssets} parameter. * - * @param scopeId The {@link ScopeId} of the {@link Device}. - * @param deviceId The id of the device - * @param timeout The timeout of the operation in milliseconds + * @param scopeId + * The {@link ScopeId} of the {@link Device}. + * @param deviceId + * The id of the device + * @param timeout + * The timeout of the operation in milliseconds * @return The list of Assets - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @POST @Path("_write") - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public DeviceAssets write( @PathParam("scopeId") ScopeId scopeId, @PathParam("deviceId") EntityId deviceId, @@ -130,7 +143,7 @@ public DeviceAssets write( @GET @Path("_settings") - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public DeviceAssetStoreSettings getSettings( @PathParam("scopeId") ScopeId scopeId, @PathParam("deviceId") EntityId deviceId) @@ -140,7 +153,7 @@ public DeviceAssetStoreSettings getSettings( @PUT @Path("_settings") - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public Response postSettings( @PathParam("scopeId") ScopeId scopeId, @PathParam("deviceId") EntityId deviceId, diff --git a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/DeviceManagementKeystores.java b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/DeviceManagementKeystores.java index b7f3f5ce21e..51dc31056a2 100644 --- a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/DeviceManagementKeystores.java +++ b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/DeviceManagementKeystores.java @@ -12,13 +12,24 @@ *******************************************************************************/ package org.eclipse.kapua.app.api.resources.v1.resources; +import javax.inject.Inject; +import javax.ws.rs.DELETE; +import javax.ws.rs.DefaultValue; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.app.api.core.model.EntityId; import org.eclipse.kapua.app.api.core.model.ScopeId; import org.eclipse.kapua.app.api.core.resources.AbstractKapuaResource; import org.eclipse.kapua.app.api.resources.v1.resources.model.device.management.keystore.DeviceKeystoreCertificateInfo; import org.eclipse.kapua.service.KapuaService; -import org.eclipse.kapua.service.device.management.keystore.DeviceKeystoreManagementFactory; import org.eclipse.kapua.service.device.management.keystore.DeviceKeystoreManagementService; import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystoreCSR; import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystoreCSRInfo; @@ -30,18 +41,6 @@ import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystores; import org.eclipse.kapua.service.device.registry.Device; -import javax.inject.Inject; -import javax.ws.rs.DELETE; -import javax.ws.rs.DefaultValue; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - /** * {@link DeviceKeystoreManagementService} {@link AbstractKapuaResource} * @@ -52,21 +51,23 @@ public class DeviceManagementKeystores extends AbstractKapuaResource { @Inject public DeviceKeystoreManagementService deviceKeystoreManagementService; - @Inject - public DeviceKeystoreManagementFactory deviceKeystoreManagementFactory; /** * Gets the {@link DeviceKeystores} present on the {@link Device}. * - * @param scopeId The {@link Device#getScopeId()}. - * @param deviceId The {@link Device#getId()}. - * @param timeout The timeout of the operation in milliseconds + * @param scopeId + * The {@link Device#getScopeId()}. + * @param deviceId + * The {@link Device#getId()}. + * @param timeout + * The timeout of the operation in milliseconds * @return The {@link DeviceKeystores}. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.5.0 */ @GET - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public DeviceKeystores getKeystores( @PathParam("scopeId") ScopeId scopeId, @PathParam("deviceId") EntityId deviceId, @@ -77,16 +78,20 @@ public DeviceKeystores getKeystores( /** * Gets the {@link DeviceKeystoreItems} present on the {@link Device}. * - * @param scopeId The {@link Device#getScopeId()}. - * @param deviceId The {@link Device#getId()}. - * @param timeout The timeout of the operation in milliseconds + * @param scopeId + * The {@link Device#getScopeId()}. + * @param deviceId + * The {@link Device#getId()}. + * @param timeout + * The timeout of the operation in milliseconds * @return The {@link DeviceKeystoreItems}. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.5.0 */ @GET @Path("items") - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public DeviceKeystoreItems getKeystoreItems( @PathParam("scopeId") ScopeId scopeId, @PathParam("deviceId") EntityId deviceId, @@ -94,7 +99,7 @@ public DeviceKeystoreItems getKeystoreItems( @QueryParam("alias") String alias, @QueryParam("timeout") @DefaultValue("30000") Long timeout) throws KapuaException { - DeviceKeystoreItemQuery itemQuery = deviceKeystoreManagementFactory.newDeviceKeystoreItemQuery(); + DeviceKeystoreItemQuery itemQuery = new DeviceKeystoreItemQuery(); itemQuery.setKeystoreId(keystoreId); itemQuery.setAlias(alias); @@ -104,16 +109,20 @@ public DeviceKeystoreItems getKeystoreItems( /** * Gets the {@link DeviceKeystoreItem} present on the {@link Device}. * - * @param scopeId The {@link Device#getScopeId()}. - * @param deviceId The {@link Device#getId()}. - * @param timeout The timeout of the operation in milliseconds + * @param scopeId + * The {@link Device#getScopeId()}. + * @param deviceId + * The {@link Device#getId()}. + * @param timeout + * The timeout of the operation in milliseconds * @return The {@link DeviceKeystoreItem}. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.5.0 */ @GET @Path("item") - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public DeviceKeystoreItem getKeystoreItem( @PathParam("scopeId") ScopeId scopeId, @PathParam("deviceId") EntityId deviceId, @@ -127,17 +136,22 @@ public DeviceKeystoreItem getKeystoreItem( /** * Creates a {@link DeviceKeystoreCertificate} into the {@link Device}. * - * @param scopeId The {@link Device#getScopeId()}. - * @param deviceId The {@link Device#getId()}. - * @param keystoreCertificateInfo The {@link DeviceKeystoreCertificateInfo} to create. - * @param timeout The timeout of the operation in milliseconds + * @param scopeId + * The {@link Device#getScopeId()}. + * @param deviceId + * The {@link Device#getId()}. + * @param keystoreCertificateInfo + * The {@link DeviceKeystoreCertificateInfo} to create. + * @param timeout + * The timeout of the operation in milliseconds * @return HTTP {@link Response#noContent()} code. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.5.0 */ @POST @Path("items/certificateInfo") - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public Response createDeviceKeystoreCertificate( @PathParam("scopeId") ScopeId scopeId, @PathParam("deviceId") EntityId deviceId, @@ -158,17 +172,22 @@ public Response createDeviceKeystoreCertificate( /** * Creates a {@link DeviceKeystoreCertificate} into the {@link Device}. * - * @param scopeId The {@link Device#getScopeId()}. - * @param deviceId The {@link Device#getId()}. - * @param keystoreCertificate The {@link DeviceKeystoreCertificate} to create. - * @param timeout The timeout of the operation in milliseconds + * @param scopeId + * The {@link Device#getScopeId()}. + * @param deviceId + * The {@link Device#getId()}. + * @param keystoreCertificate + * The {@link DeviceKeystoreCertificate} to create. + * @param timeout + * The timeout of the operation in milliseconds * @return HTTP {@link Response#noContent()} code. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.5.0 */ @POST @Path("items/certificateRaw") - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public Response createDeviceKeystoreCertificate( @PathParam("scopeId") ScopeId scopeId, @PathParam("deviceId") EntityId deviceId, @@ -180,21 +199,25 @@ public Response createDeviceKeystoreCertificate( return returnNoContent(); } - /** * Creates a {@link DeviceKeystoreKeypair} into the {@link Device}. * - * @param scopeId The {@link Device#getScopeId()}. - * @param deviceId The {@link Device#getId()}. - * @param deviceKeystoreKeypair The {@link DeviceKeystoreKeypair} to create. - * @param timeout The timeout of the operation in milliseconds + * @param scopeId + * The {@link Device#getScopeId()}. + * @param deviceId + * The {@link Device#getId()}. + * @param deviceKeystoreKeypair + * The {@link DeviceKeystoreKeypair} to create. + * @param timeout + * The timeout of the operation in milliseconds * @return HTTP {@link Response#noContent()} code. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.5.0 */ @POST @Path("items/keypair") - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public Response createDeviceKeystoreKeypair( @PathParam("scopeId") ScopeId scopeId, @PathParam("deviceId") EntityId deviceId, @@ -209,17 +232,22 @@ public Response createDeviceKeystoreKeypair( /** * Sends a {@link DeviceKeystoreCSRInfo} into the {@link Device}. * - * @param scopeId The {@link Device#getScopeId()}. - * @param deviceId The {@link Device#getId()}. - * @param deviceKeystoreCSRInfo The {@link DeviceKeystoreCSRInfo} to create. - * @param timeout The timeout of the operation in milliseconds + * @param scopeId + * The {@link Device#getScopeId()}. + * @param deviceId + * The {@link Device#getId()}. + * @param deviceKeystoreCSRInfo + * The {@link DeviceKeystoreCSRInfo} to create. + * @param timeout + * The timeout of the operation in milliseconds * @return The {@link DeviceKeystoreCSR}. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.5.0 */ @POST @Path("items/csr") - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public DeviceKeystoreCSR createDeviceKeystoreCSR( @PathParam("scopeId") ScopeId scopeId, @PathParam("deviceId") EntityId deviceId, @@ -232,16 +260,20 @@ public DeviceKeystoreCSR createDeviceKeystoreCSR( /** * Gets the {@link DeviceKeystoreItem} present on the {@link Device}. * - * @param scopeId The {@link Device#getScopeId()}. - * @param deviceId The {@link Device#getId()}. - * @param timeout The timeout of the operation in milliseconds + * @param scopeId + * The {@link Device#getScopeId()}. + * @param deviceId + * The {@link Device#getId()}. + * @param timeout + * The timeout of the operation in milliseconds * @return HTTP {@link Response#noContent()} code. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.5.0 */ @DELETE @Path("item") - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public Response deleteKeystoreItem( @PathParam("scopeId") ScopeId scopeId, @PathParam("deviceId") EntityId deviceId, diff --git a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/DeviceManagementOperationNotifications.java b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/DeviceManagementOperationNotifications.java index c41a0ab8933..b980ef13472 100644 --- a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/DeviceManagementOperationNotifications.java +++ b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/DeviceManagementOperationNotifications.java @@ -25,7 +25,6 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -import com.google.common.base.Strings; import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.app.api.core.model.CountResult; import org.eclipse.kapua.app.api.core.model.EntityId; @@ -43,6 +42,8 @@ import org.eclipse.kapua.service.device.management.registry.operation.notification.ManagementOperationNotificationService; import org.eclipse.kapua.service.device.registry.Device; +import com.google.common.base.Strings; + @Path("{scopeId}/devices/{deviceId}/operations/{operationId}/notifications") public class DeviceManagementOperationNotifications extends AbstractKapuaResource { @@ -54,17 +55,23 @@ public class DeviceManagementOperationNotifications extends AbstractKapuaResourc /** * Gets the {@link ManagementOperationNotification} list in the scope. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param operationId The id of the {@link Device} in which to search results - * @param resource The resource of the {@link ManagementOperationNotification} in which to search results - * @param offset The result set offset. - * @param limit The result set limit. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param operationId + * The id of the {@link Device} in which to search results + * @param resource + * The resource of the {@link ManagementOperationNotification} in which to search results + * @param offset + * The result set offset. + * @param limit + * The result set limit. * @return The {@link ManagementOperationNotificationListResult} of all the ManagementOperationNotifications associated to the current selected scope. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @GET - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public ManagementOperationNotificationListResult simpleQuery( @PathParam("scopeId") ScopeId scopeId, @PathParam("deviceId") EntityId deviceId, @@ -75,7 +82,7 @@ public ManagementOperationNotificationListResult simpleQuery( @QueryParam("sortDir") @DefaultValue("ASCENDING") SortOrder sortDir, @QueryParam("offset") @DefaultValue("0") int offset, @QueryParam("limit") @DefaultValue("50") int limit) throws KapuaException { - ManagementOperationNotificationQuery query = managementOperationNotificationFactory.newQuery(scopeId); + ManagementOperationNotificationQuery query = new ManagementOperationNotificationQuery(scopeId); AndPredicate andPredicate = query.andPredicate(query.attributePredicate(ManagementOperationNotificationAttributes.OPERATION_ID, operationId)); @@ -99,17 +106,21 @@ public ManagementOperationNotificationListResult simpleQuery( /** * Queries the results with the given {@link ManagementOperationNotificationQuery} parameter. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param operationId The id of the {@link Device} in which to search results - * @param query The {@link ManagementOperationNotificationQuery} to use to filter results. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param operationId + * The id of the {@link Device} in which to search results + * @param query + * The {@link ManagementOperationNotificationQuery} to use to filter results. * @return The {@link ManagementOperationNotificationListResult} of all the result matching the given {@link ManagementOperationNotificationQuery} parameter. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @POST @Path("_query") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public ManagementOperationNotificationListResult query( @PathParam("scopeId") ScopeId scopeId, @PathParam("deviceId") EntityId deviceId, @@ -127,17 +138,21 @@ public ManagementOperationNotificationListResult query( /** * Counts the results with the given {@link ManagementOperationNotificationQuery} parameter. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param operationId The id of the {@link Device} in which to search results - * @param query The {@link ManagementOperationNotificationQuery} to use to filter results. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param operationId + * The id of the {@link Device} in which to search results + * @param query + * The {@link ManagementOperationNotificationQuery} to use to filter results. * @return The count of all the result matching the given {@link ManagementOperationNotificationQuery} parameter. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @POST @Path("_count") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public CountResult count( @PathParam("scopeId") ScopeId scopeId, @PathParam("deviceId") EntityId deviceId, @@ -152,23 +167,27 @@ public CountResult count( /** * Returns the ManagementOperationNotification specified by the "ManagementOperationNotificationId" path parameter. * - * @param scopeId The {@link ScopeId} of the requested {@link ManagementOperationNotification}. - * @param operationId The {@link Device} id of the request {@link ManagementOperationNotification}. - * @param managementOperationNotificationId The id of the requested ManagementOperationNotification. + * @param scopeId + * The {@link ScopeId} of the requested {@link ManagementOperationNotification}. + * @param operationId + * The {@link Device} id of the request {@link ManagementOperationNotification}. + * @param managementOperationNotificationId + * The id of the requested ManagementOperationNotification. * @return The requested ManagementOperationNotification object. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @GET @Path("{managementOperationNotificationId}") - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public ManagementOperationNotification find( @PathParam("scopeId") ScopeId scopeId, @PathParam("deviceId") EntityId deviceId, @PathParam("operationId") EntityId operationId, @PathParam("managementOperationNotificationId") EntityId managementOperationNotificationId) throws KapuaException { -//TODO: #LAYER_VIOLATION - findFirst should be resolved in bottom layer - ManagementOperationNotificationQuery query = managementOperationNotificationFactory.newQuery(scopeId); + //TODO: #LAYER_VIOLATION - findFirst should be resolved in bottom layer + ManagementOperationNotificationQuery query = new ManagementOperationNotificationQuery(scopeId); AndPredicate andPredicate = query.andPredicate( query.attributePredicate(ManagementOperationNotificationAttributes.OPERATION_ID, operationId), @@ -187,10 +206,13 @@ public ManagementOperationNotification find( /** * Deletes the ManagementOperationNotification specified by the "ManagementOperationNotificationId" path parameter. * - * @param operationId The id of the Device in which to delete the ManagementOperation - * @param managementOperationNotificationId The id of the ManagementOperationNotification to be deleted. + * @param operationId + * The id of the Device in which to delete the ManagementOperation + * @param managementOperationNotificationId + * The id of the ManagementOperationNotification to be deleted. * @return HTTP 200 if operation has completed successfully. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @DELETE diff --git a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/DeviceManagementOperations.java b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/DeviceManagementOperations.java index 85087c62154..791da951ed3 100644 --- a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/DeviceManagementOperations.java +++ b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/DeviceManagementOperations.java @@ -25,7 +25,6 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -import com.google.common.base.Strings; import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.app.api.core.model.CountResult; import org.eclipse.kapua.app.api.core.model.EntityId; @@ -44,6 +43,8 @@ import org.eclipse.kapua.service.device.management.registry.operation.DeviceManagementOperationStatus; import org.eclipse.kapua.service.device.registry.Device; +import com.google.common.base.Strings; + @Path("{scopeId}/devices/{deviceId}/operations") public class DeviceManagementOperations extends AbstractKapuaResource { @@ -55,17 +56,23 @@ public class DeviceManagementOperations extends AbstractKapuaResource { /** * Gets the {@link DeviceManagementOperation} list in the scope. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param deviceId The id of the {@link Device} in which to search results - * @param resource The resource of the {@link DeviceManagementOperation} in which to search results - * @param offset The result set offset. - * @param limit The result set limit. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param deviceId + * The id of the {@link Device} in which to search results + * @param resource + * The resource of the {@link DeviceManagementOperation} in which to search results + * @param offset + * The result set offset. + * @param limit + * The result set limit. * @return The {@link DeviceManagementOperationListResult} of all the deviceManagementOperations associated to the current selected scope. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @GET - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public DeviceManagementOperationListResult simpleQuery( @PathParam("scopeId") ScopeId scopeId, @PathParam("deviceId") EntityId deviceId, @@ -77,7 +84,7 @@ public DeviceManagementOperationListResult simpleQuery( @QueryParam("sortDir") @DefaultValue("ASCENDING") SortOrder sortDir, @QueryParam("offset") @DefaultValue("0") int offset, @QueryParam("limit") @DefaultValue("50") int limit) throws KapuaException { - DeviceManagementOperationQuery query = deviceManagementOperationFactory.newQuery(scopeId); + DeviceManagementOperationQuery query = new DeviceManagementOperationQuery(scopeId); AndPredicate andPredicate = query.andPredicate(); @@ -110,25 +117,29 @@ public DeviceManagementOperationListResult simpleQuery( /** * Queries the results with the given {@link DeviceManagementOperationQuery} parameter. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param deviceId The id of the {@link Device} in which to search results - * @param query The {@link DeviceManagementOperationQuery} to use to filter results. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param deviceId + * The id of the {@link Device} in which to search results + * @param query + * The {@link DeviceManagementOperationQuery} to use to filter results. * @return The {@link DeviceManagementOperationListResult} of all the result matching the given {@link DeviceManagementOperationQuery} parameter. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @POST @Path("_query") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public DeviceManagementOperationListResult query( @PathParam("scopeId") ScopeId scopeId, @PathParam("deviceId") EntityId deviceId, DeviceManagementOperationQuery query) throws KapuaException { if (query.getPredicate() != null) { final AndPredicate andPredicate = query.andPredicate( - query.attributePredicate(DeviceManagementOperationAttributes.DEVICE_ID, deviceId), - query.getPredicate() + query.attributePredicate(DeviceManagementOperationAttributes.DEVICE_ID, deviceId), + query.getPredicate() ); query.setPredicate(andPredicate); } else { @@ -140,17 +151,21 @@ public DeviceManagementOperationListResult query( /** * Counts the results with the given {@link DeviceManagementOperationQuery} parameter. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param deviceId The id of the {@link Device} in which to search results - * @param query The {@link DeviceManagementOperationQuery} to use to filter results. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param deviceId + * The id of the {@link Device} in which to search results + * @param query + * The {@link DeviceManagementOperationQuery} to use to filter results. * @return The count of all the result matching the given {@link DeviceManagementOperationQuery} parameter. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @POST @Path("_count") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public CountResult count( @PathParam("scopeId") ScopeId scopeId, @PathParam("deviceId") EntityId deviceId, @@ -164,21 +179,25 @@ public CountResult count( /** * Returns the DeviceManagementOperation specified by the "deviceManagementOperationId" path parameter. * - * @param scopeId The {@link ScopeId} of the requested {@link DeviceManagementOperation}. - * @param deviceId The {@link Device} id of the request {@link DeviceManagementOperation}. - * @param deviceManagementOperationId The id of the requested DeviceManagementOperation. + * @param scopeId + * The {@link ScopeId} of the requested {@link DeviceManagementOperation}. + * @param deviceId + * The {@link Device} id of the request {@link DeviceManagementOperation}. + * @param deviceManagementOperationId + * The id of the requested DeviceManagementOperation. * @return The requested DeviceManagementOperation object. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @GET @Path("{deviceManagementOperationId}") - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public DeviceManagementOperation find( @PathParam("scopeId") ScopeId scopeId, @PathParam("deviceId") EntityId deviceId, @PathParam("deviceManagementOperationId") EntityId deviceManagementOperationId) throws KapuaException { - DeviceManagementOperationQuery query = deviceManagementOperationFactory.newQuery(scopeId); + DeviceManagementOperationQuery query = new DeviceManagementOperationQuery(scopeId); AndPredicate andPredicate = query.andPredicate( query.attributePredicate(DeviceManagementOperationAttributes.DEVICE_ID, deviceId), @@ -197,17 +216,20 @@ public DeviceManagementOperation find( /** * Deletes the DeviceManagementOperation specified by the "deviceManagementOperationId" path parameter. * - * @param deviceId The id of the Device in which to delete the ManagementOperation - * @param deviceManagementOperationId The id of the DeviceManagementOperation to be deleted. + * @param deviceId + * The id of the Device in which to delete the ManagementOperation + * @param deviceManagementOperationId + * The id of the DeviceManagementOperation to be deleted. * @return HTTP 200 if operation has completed successfully. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @DELETE @Path("{deviceManagementOperationId}") public Response deleteDeviceManagementOperation(@PathParam("scopeId") ScopeId scopeId, - @PathParam("deviceId") EntityId deviceId, - @PathParam("deviceManagementOperationId") EntityId deviceManagementOperationId) throws KapuaException { + @PathParam("deviceId") EntityId deviceId, + @PathParam("deviceManagementOperationId") EntityId deviceManagementOperationId) throws KapuaException { deviceManagementOperationRegistryService.delete(scopeId, deviceManagementOperationId); return returnNoContent(); diff --git a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/DeviceManagementPackages.java b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/DeviceManagementPackages.java index 4cb368ecfff..cb696d05ad4 100644 --- a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/DeviceManagementPackages.java +++ b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/DeviceManagementPackages.java @@ -12,6 +12,17 @@ *******************************************************************************/ package org.eclipse.kapua.app.api.resources.v1.resources; +import javax.inject.Inject; +import javax.ws.rs.DefaultValue; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.app.api.core.model.EntityId; import org.eclipse.kapua.app.api.core.model.ScopeId; @@ -21,7 +32,6 @@ import org.eclipse.kapua.locator.KapuaLocator; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.KapuaService; -import org.eclipse.kapua.service.device.management.packages.DevicePackageFactory; import org.eclipse.kapua.service.device.management.packages.DevicePackageManagementService; import org.eclipse.kapua.service.device.management.packages.model.DevicePackages; import org.eclipse.kapua.service.device.management.packages.model.download.DevicePackageDownloadOptions; @@ -32,41 +42,33 @@ import org.eclipse.kapua.service.device.management.registry.operation.DeviceManagementOperationRegistryService; import org.eclipse.kapua.service.device.registry.Device; -import javax.inject.Inject; -import javax.ws.rs.DefaultValue; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - @Path("{scopeId}/devices/{deviceId}/packages") public class DeviceManagementPackages extends AbstractKapuaResource { - private final Boolean responseLegacyMode = KapuaLocator.getInstance().getComponent(KapuaApiCoreSetting.class).getBoolean(KapuaApiCoreSettingKeys.API_DEVICE_MANAGEMENT_PACKAGE_RESPONSE_LEGACY_MODE, false); + private final Boolean responseLegacyMode = KapuaLocator.getInstance().getComponent(KapuaApiCoreSetting.class) + .getBoolean(KapuaApiCoreSettingKeys.API_DEVICE_MANAGEMENT_PACKAGE_RESPONSE_LEGACY_MODE, false); @Inject public DevicePackageManagementService devicePackageManagementService; @Inject - public DevicePackageFactory devicePackageFactory; - @Inject public DeviceManagementOperationRegistryService deviceManagementOperationRegistryService; /** * Returns the list of all the packages installed on the device. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param deviceId The id of the device - * @param timeout The timeout of the operation + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param deviceId + * The id of the device + * @param timeout + * The timeout of the operation * @return The list of packages installed. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @GET - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public DevicePackages get( @PathParam("scopeId") ScopeId scopeId, @PathParam("deviceId") EntityId deviceId, @@ -77,17 +79,22 @@ public DevicePackages get( /** * Download and optionally installs a package into the device. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param deviceId The {@link Device} ID. - * @param timeout The timeout of the operation - * @param packageDownloadRequest Mandatory object with all the informations needed to download and install a package + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param deviceId + * The {@link Device} ID. + * @param timeout + * The timeout of the operation + * @param packageDownloadRequest + * Mandatory object with all the informations needed to download and install a package * @return HTTP 200 if operation has completed successfully. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @POST @Path("_download") - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public Response download( @PathParam("scopeId") ScopeId scopeId, @PathParam("deviceId") EntityId deviceId, @@ -95,7 +102,7 @@ public Response download( @QueryParam("legacy") @DefaultValue("false") boolean legacy, DevicePackageDownloadRequest packageDownloadRequest) throws KapuaException { - DevicePackageDownloadOptions options = devicePackageFactory.newPackageDownloadOptions(); + DevicePackageDownloadOptions options = new DevicePackageDownloadOptions(); options.setTimeout(timeout); KapuaId deviceManagementOperationId = devicePackageManagementService.downloadExec(scopeId, deviceId, packageDownloadRequest, options); @@ -108,24 +115,29 @@ public Response download( /** * Uninstalls a package into the device. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param deviceId The {@link Device} ID. - * @param timeout The timeout of the operation - * @param packageUninstallRequest Mandatory object with all the informations needed to uninstall a package + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param deviceId + * The {@link Device} ID. + * @param timeout + * The timeout of the operation + * @param packageUninstallRequest + * Mandatory object with all the informations needed to uninstall a package * @return HTTP 200 if operation has completed successfully. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @POST @Path("_uninstall") - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public Response uninstall( @PathParam("scopeId") ScopeId scopeId, @PathParam("deviceId") EntityId deviceId, @QueryParam("timeout") @DefaultValue("30000") Long timeout, @QueryParam("legacy") @DefaultValue("false") boolean legacy, DevicePackageUninstallRequest packageUninstallRequest) throws KapuaException { - DevicePackageUninstallOptions options = devicePackageFactory.newPackageUninstallOptions(); + DevicePackageUninstallOptions options = new DevicePackageUninstallOptions(); options.setTimeout(timeout); KapuaId deviceManagementOperationId = devicePackageManagementService.uninstallExec(scopeId, deviceId, packageUninstallRequest, options); diff --git a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/Devices.java b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/Devices.java index 8bfea63283d..98f7948d111 100644 --- a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/Devices.java +++ b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/Devices.java @@ -12,7 +12,22 @@ *******************************************************************************/ package org.eclipse.kapua.app.api.resources.v1.resources; -import com.google.common.base.Strings; +import java.util.List; + +import javax.inject.Inject; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.DefaultValue; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.app.api.core.model.CountResult; import org.eclipse.kapua.app.api.core.model.EntityId; @@ -31,20 +46,7 @@ import org.eclipse.kapua.service.device.registry.connection.DeviceConnectionStatus; import org.eclipse.kapua.service.tag.Tag; -import javax.inject.Inject; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.DefaultValue; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import java.util.List; +import com.google.common.base.Strings; @Path("{scopeId}/devices") public class Devices extends AbstractKapuaResource { @@ -57,23 +59,35 @@ public class Devices extends AbstractKapuaResource { /** * Gets the {@link Device} list in the scope. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param tagId The id of the {@link Tag} in which to search results - * @param clientId The id of the {@link Device} in which to search results - * @param connectionStatus The {@link DeviceConnectionStatus} in which to search results - * @param matchTerm A term to be matched in at least one of the configured fields of this entity - * @param fetchAttributes Additional attributes to be returned. Allowed values: connection, lastEvent - * @param askTotalCount Ask for the total count of the matched entities in the result - * @param sortParam The name of the parameter that will be used as a sorting key - * @param sortDir The sort direction. Can be ASCENDING (default), DESCENDING. Case-insensitive. - * @param offset The result set offset. - * @param limit The result set limit. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param tagId + * The id of the {@link Tag} in which to search results + * @param clientId + * The id of the {@link Device} in which to search results + * @param connectionStatus + * The {@link DeviceConnectionStatus} in which to search results + * @param matchTerm + * A term to be matched in at least one of the configured fields of this entity + * @param fetchAttributes + * Additional attributes to be returned. Allowed values: connection, lastEvent + * @param askTotalCount + * Ask for the total count of the matched entities in the result + * @param sortParam + * The name of the parameter that will be used as a sorting key + * @param sortDir + * The sort direction. Can be ASCENDING (default), DESCENDING. Case-insensitive. + * @param offset + * The result set offset. + * @param limit + * The result set limit. * @return The {@link DeviceListResult} of all the devices associated to the current selected scope. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @GET - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public DeviceListResult simpleQuery( @PathParam("scopeId") ScopeId scopeId, @QueryParam("tagId") EntityId tagId, @@ -86,7 +100,7 @@ public DeviceListResult simpleQuery( @QueryParam("sortDir") @DefaultValue("ASCENDING") SortOrder sortDir, @QueryParam("offset") @DefaultValue("0") int offset, @QueryParam("limit") @DefaultValue("50") int limit) throws KapuaException { - DeviceQuery query = deviceFactory.newQuery(scopeId); + DeviceQuery query = new DeviceQuery(scopeId); AndPredicate andPredicate = query.andPredicate(); if (tagId != null) { @@ -118,16 +132,19 @@ public DeviceListResult simpleQuery( /** * Queries the results with the given {@link DeviceQuery} parameter. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param query The {@link DeviceQuery} to use to filter results. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param query + * The {@link DeviceQuery} to use to filter results. * @return The {@link DeviceListResult} of all the result matching the given {@link DeviceQuery} parameter. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @POST @Path("_query") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public DeviceListResult query( @PathParam("scopeId") ScopeId scopeId, DeviceQuery query) throws KapuaException { @@ -139,16 +156,19 @@ public DeviceListResult query( /** * Counts the results with the given {@link DeviceQuery} parameter. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param query The {@link DeviceQuery} to use to filter results. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param query + * The {@link DeviceQuery} to use to filter results. * @return The count of all the result matching the given {@link DeviceQuery} parameter. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @POST @Path("_count") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public CountResult count( @PathParam("scopeId") ScopeId scopeId, DeviceQuery query) throws KapuaException { @@ -158,18 +178,20 @@ public CountResult count( } /** - * Creates a new Device based on the information provided in DeviceCreator - * parameter. + * Creates a new Device based on the information provided in DeviceCreator parameter. * - * @param scopeId The {@link ScopeId} in which to create the {@link Device} - * @param deviceCreator Provides the information for the new Device to be created. + * @param scopeId + * The {@link ScopeId} in which to create the {@link Device} + * @param deviceCreator + * Provides the information for the new Device to be created. * @return The newly created Device object. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @POST - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public Response create( @PathParam("scopeId") ScopeId scopeId, DeviceCreator deviceCreator) throws KapuaException { @@ -181,15 +203,18 @@ public Response create( /** * Returns the Device specified by the "deviceId" path parameter. * - * @param scopeId The {@link ScopeId} of the requested {@link Device}. - * @param deviceId The id of the requested Device. + * @param scopeId + * The {@link ScopeId} of the requested {@link Device}. + * @param deviceId + * The id of the requested Device. * @return The requested Device object. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @GET @Path("{deviceId}") - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public Device find( @PathParam("scopeId") ScopeId scopeId, @PathParam("deviceId") EntityId deviceId) throws KapuaException { @@ -201,17 +226,21 @@ public Device find( /** * Updates the Device based on the information provided in the Device parameter. * - * @param scopeId The ScopeId of the requested Device. - * @param deviceId The id of the requested {@link Device} - * @param device The modified Device whose attributed need to be updated. + * @param scopeId + * The ScopeId of the requested Device. + * @param deviceId + * The id of the requested {@link Device} + * @param device + * The modified Device whose attributed need to be updated. * @return The updated device. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @PUT @Path("{deviceId}") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public Device update( @PathParam("scopeId") ScopeId scopeId, @PathParam("deviceId") EntityId deviceId, @@ -225,10 +254,13 @@ public Device update( /** * Deletes the Device specified by the "deviceId" path parameter. * - * @param scopeId The ScopeId of the requested {@link Device}. - * @param deviceId The id of the Device to be deleted. + * @param scopeId + * The ScopeId of the requested {@link Device}. + * @param deviceId + * The id of the Device to be deleted. * @return HTTP 200 if operation has completed successfully. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @DELETE diff --git a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/Domains.java b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/Domains.java index 9effc5a8d46..258bc5bad55 100644 --- a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/Domains.java +++ b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/Domains.java @@ -12,59 +12,63 @@ *******************************************************************************/ package org.eclipse.kapua.app.api.resources.v1.resources; -import com.google.common.base.Strings; +import javax.inject.Inject; +import javax.ws.rs.Consumes; +import javax.ws.rs.DefaultValue; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.app.api.core.model.CountResult; import org.eclipse.kapua.app.api.core.model.EntityId; import org.eclipse.kapua.app.api.core.model.ScopeId; import org.eclipse.kapua.app.api.core.resources.AbstractKapuaResource; import org.eclipse.kapua.model.KapuaNamedEntityAttributes; +import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.model.query.predicate.AndPredicate; import org.eclipse.kapua.service.KapuaService; import org.eclipse.kapua.service.authorization.domain.Domain; -import org.eclipse.kapua.service.authorization.domain.DomainFactory; import org.eclipse.kapua.service.authorization.domain.DomainListResult; -import org.eclipse.kapua.service.authorization.domain.DomainQuery; import org.eclipse.kapua.service.authorization.domain.DomainRegistryService; -import javax.inject.Inject; -import javax.ws.rs.Consumes; -import javax.ws.rs.DefaultValue; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.MediaType; +import com.google.common.base.Strings; @Path("{scopeId}/domains") public class Domains extends AbstractKapuaResource { @Inject public DomainRegistryService domainRegistryService; - @Inject - public DomainFactory domainFactory; /** * Gets the {@link Domain} list in the scope. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param name The {@link Domain} name in which to search results. - * @param offset The result set offset. - * @param limit The result set limit. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param name + * The {@link Domain} name in which to search results. + * @param offset + * The result set offset. + * @param limit + * The result set limit. * @return The {@link DomainListResult} of all the domains associated to the current selected scope. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @GET - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public DomainListResult simpleQuery( @PathParam("scopeId") ScopeId scopeId, @QueryParam("name") String name, @QueryParam("offset") @DefaultValue("0") int offset, @QueryParam("limit") @DefaultValue("50") int limit) throws KapuaException { - DomainQuery query = domainFactory.newQuery(null); + final KapuaQuery query = new KapuaQuery((KapuaId) null); AndPredicate andPredicate = query.andPredicate(); if (!Strings.isNullOrEmpty(name)) { @@ -79,55 +83,64 @@ public DomainListResult simpleQuery( } /** - * Queries the results with the given {@link DomainQuery} parameter. + * Queries the results with the given {@link KapuaQuery} parameter. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param query The {@link DomainQuery} to use to filter results. - * @return The {@link DomainListResult} of all the result matching the given {@link DomainQuery} parameter. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param query + * The {@link KapuaQuery} to use to filter results. + * @return The {@link DomainListResult} of all the result matching the given {@link KapuaQuery} parameter. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @POST @Path("_query") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public DomainListResult query( @PathParam("scopeId") ScopeId scopeId, - DomainQuery query) throws KapuaException { + KapuaQuery query) throws KapuaException { return domainRegistryService.query(query); } /** - * Counts the results with the given {@link DomainQuery} parameter. + * Counts the results with the given {@link KapuaQuery} parameter. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param query The {@link DomainQuery} to use to filter results. - * @return The count of all the result matching the given {@link DomainQuery} parameter. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param query + * The {@link KapuaQuery} to use to filter results. + * @return The count of all the result matching the given {@link KapuaQuery} parameter. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @POST @Path("_count") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public CountResult count( @PathParam("scopeId") ScopeId scopeId, - DomainQuery query) throws KapuaException { + KapuaQuery query) throws KapuaException { return new CountResult(domainRegistryService.count(query)); } /** * Returns the Domain specified by the "domainId" path parameter. * - * @param scopeId The {@link ScopeId} of the requested {@link Domain}. - * @param domainId The id of the requested {@link Domain}. + * @param scopeId + * The {@link ScopeId} of the requested {@link Domain}. + * @param domainId + * The id of the requested {@link Domain}. * @return The requested Domain object. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @GET @Path("{domainId}") - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public Domain find( @PathParam("scopeId") ScopeId scopeId, @PathParam("domainId") EntityId domainId) throws KapuaException { diff --git a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/EndpointInfos.java b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/EndpointInfos.java index 164fb0a7aeb..cf4d82473a9 100644 --- a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/EndpointInfos.java +++ b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/EndpointInfos.java @@ -26,7 +26,6 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -import com.google.common.base.Strings; import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.app.api.core.model.CountResult; import org.eclipse.kapua.app.api.core.model.EntityId; @@ -43,6 +42,8 @@ import org.eclipse.kapua.service.endpoint.EndpointInfoQuery; import org.eclipse.kapua.service.endpoint.EndpointInfoService; +import com.google.common.base.Strings; + @Path("{scopeId}/endpointInfos") public class EndpointInfos extends AbstractKapuaResource { @@ -54,17 +55,22 @@ public class EndpointInfos extends AbstractKapuaResource { /** * Gets the {@link EndpointInfo} list in the scope. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param usage The {@link EndpointInfo} usage to filter results - * @param offset The result set offset. - * @param limit The result set limit. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param usage + * The {@link EndpointInfo} usage to filter results + * @param offset + * The result set offset. + * @param limit + * The result set limit. * @return The {@link EndpointInfoListResult} of all the endpointInfos associated to the current selected scope. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @GET - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public EndpointInfoListResult simpleQuery( @PathParam("scopeId") ScopeId scopeId, @QueryParam("usage") String usage, @@ -75,7 +81,7 @@ public EndpointInfoListResult simpleQuery( @QueryParam("sortDir") @DefaultValue("ASCENDING") SortOrder sortDir, @QueryParam("offset") @DefaultValue("0") int offset, @QueryParam("limit") @DefaultValue("50") int limit) throws KapuaException { - EndpointInfoQuery query = endpointInfoFactory.newQuery(scopeId); + EndpointInfoQuery query = new EndpointInfoQuery(scopeId); AndPredicate andPredicate = query.andPredicate(); if (!Strings.isNullOrEmpty(usage)) { @@ -99,17 +105,20 @@ public EndpointInfoListResult simpleQuery( /** * Queries the results with the given {@link EndpointInfoQuery} parameter. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param query The {@link EndpointInfoQuery} to use to filter results. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param query + * The {@link EndpointInfoQuery} to use to filter results. * @return The {@link EndpointInfoListResult} of all the result matching the given {@link EndpointInfoQuery} parameter. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @POST @Path("_query") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public EndpointInfoListResult query( @PathParam("scopeId") ScopeId scopeId, @QueryParam("endpointType") @DefaultValue(EndpointInfo.ENDPOINT_TYPE_RESOURCE) String endpointType, @@ -122,17 +131,20 @@ public EndpointInfoListResult query( /** * Counts the results with the given {@link EndpointInfoQuery} parameter. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param query The {@link EndpointInfoQuery} to use to filter results. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param query + * The {@link EndpointInfoQuery} to use to filter results. * @return The count of all the result matching the given {@link EndpointInfoQuery} parameter. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @POST @Path("_count") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public CountResult count( @PathParam("scopeId") ScopeId scopeId, @QueryParam("endpointType") @DefaultValue(EndpointInfo.ENDPOINT_TYPE_RESOURCE) String endpointType, @@ -143,19 +155,21 @@ public CountResult count( } /** - * Creates a new EndpointInfo based on the information provided in EndpointInfoCreator - * parameter. + * Creates a new EndpointInfo based on the information provided in EndpointInfoCreator parameter. * - * @param scopeId The {@link ScopeId} in which to create the {@link EndpointInfo} - * @param endpointInfoCreator Provides the information for the new {@link EndpointInfo} to be created. + * @param scopeId + * The {@link ScopeId} in which to create the {@link EndpointInfo} + * @param endpointInfoCreator + * Provides the information for the new {@link EndpointInfo} to be created. * @return The newly created {@link EndpointInfo} object. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @POST - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public Response create( @PathParam("scopeId") ScopeId scopeId, EndpointInfoCreator endpointInfoCreator) throws KapuaException { @@ -167,39 +181,46 @@ public Response create( /** * Returns the EndpointInfo specified by the "endpointInfoId" path parameter. * - * @param scopeId The {@link ScopeId} of the requested {@link EndpointInfo}. - * @param endpointInfoId The id of the requested EndpointInfo. + * @param scopeId + * The {@link ScopeId} of the requested {@link EndpointInfo}. + * @param endpointInfoId + * The id of the requested EndpointInfo. * @return The requested EndpointInfo object. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @GET @Path("{endpointInfoId}") - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public EndpointInfo find( @PathParam("scopeId") ScopeId scopeId, @PathParam("endpointInfoId") EntityId endpointInfoId) throws KapuaException { EndpointInfo endpointInfo = endpointInfoService.find(scopeId, endpointInfoId); - return returnNotNullEntity(endpointInfo,EndpointInfo.TYPE, endpointInfoId); + return returnNotNullEntity(endpointInfo, EndpointInfo.TYPE, endpointInfoId); } /** * Updates the EndpointInfo based on the information provided in the EndpointInfo parameter. * - * @param scopeId The ScopeId of the requested {@link EndpointInfo}. - * @param endpointInfoId The id of the requested {@link EndpointInfo} - * @param endpointInfo The modified EndpointInfo whose attributed need to be updated. + * @param scopeId + * The ScopeId of the requested {@link EndpointInfo}. + * @param endpointInfoId + * The id of the requested {@link EndpointInfo} + * @param endpointInfo + * The modified EndpointInfo whose attributed need to be updated. * @return The updated endpointInfo. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @PUT @Path("{endpointInfoId}") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public EndpointInfo update( @PathParam("scopeId") ScopeId scopeId, @PathParam("endpointInfoId") EntityId endpointInfoId, @@ -213,10 +234,13 @@ public EndpointInfo update( /** * Deletes the EndpointInfo specified by the "endpointInfoId" path parameter. * - * @param scopeId The ScopeId of the requested {@link EndpointInfo}. - * @param endpointInfoId The id of the EndpointInfo to be deleted. + * @param scopeId + * The ScopeId of the requested {@link EndpointInfo}. + * @param endpointInfoId + * The id of the EndpointInfo to be deleted. * @return HTTP 200 if operation has completed successfully. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ diff --git a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/Groups.java b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/Groups.java index 5eb39d15aa4..38e1f6f0124 100644 --- a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/Groups.java +++ b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/Groups.java @@ -26,7 +26,6 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -import com.google.common.base.Strings; import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.app.api.core.model.CountResult; import org.eclipse.kapua.app.api.core.model.EntityId; @@ -43,6 +42,8 @@ import org.eclipse.kapua.service.authorization.group.GroupQuery; import org.eclipse.kapua.service.authorization.group.GroupService; +import com.google.common.base.Strings; + @Path("{scopeId}/groups") public class Groups extends AbstractKapuaResource { @@ -54,16 +55,21 @@ public class Groups extends AbstractKapuaResource { /** * Gets the {@link Group} list in the scope. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param name The {@link Group} name to filter results - * @param offset The result set offset. - * @param limit The result set limit. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param name + * The {@link Group} name to filter results + * @param offset + * The result set offset. + * @param limit + * The result set limit. * @return The {@link GroupListResult} of all the groups associated to the current selected scope. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @GET - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public GroupListResult simpleQuery( @PathParam("scopeId") ScopeId scopeId, @QueryParam("name") String name, @@ -73,7 +79,7 @@ public GroupListResult simpleQuery( @QueryParam("sortDir") @DefaultValue("ASCENDING") SortOrder sortDir, @QueryParam("offset") @DefaultValue("0") int offset, @QueryParam("limit") @DefaultValue("50") int limit) throws KapuaException { - GroupQuery query = groupFactory.newQuery(scopeId); + final GroupQuery query = new GroupQuery(scopeId); AndPredicate andPredicate = query.andPredicate(); if (!Strings.isNullOrEmpty(name)) { @@ -97,16 +103,19 @@ public GroupListResult simpleQuery( /** * Queries the results with the given {@link GroupQuery} parameter. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param query The {@link GroupQuery} to use to filter results. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param query + * The {@link GroupQuery} to use to filter results. * @return The {@link GroupListResult} of all the result matching the given {@link GroupQuery} parameter. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @POST @Path("_query") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public GroupListResult query( @PathParam("scopeId") ScopeId scopeId, GroupQuery query) throws KapuaException { @@ -118,16 +127,19 @@ public GroupListResult query( /** * Counts the results with the given {@link GroupQuery} parameter. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param query The {@link GroupQuery} to use to filter results. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param query + * The {@link GroupQuery} to use to filter results. * @return The count of all the result matching the given {@link GroupQuery} parameter. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @POST @Path("_count") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public CountResult count( @PathParam("scopeId") ScopeId scopeId, GroupQuery query) throws KapuaException { @@ -137,16 +149,17 @@ public CountResult count( } /** - * Creates a new Group based on the information provided in GroupCreator - * parameter. + * Creates a new Group based on the information provided in GroupCreator parameter. * - * @param scopeId The {@link ScopeId} in which to create the {@link Group} - * @param groupCreator Provides the information for the new {@link Group} to be created. + * @param scopeId + * The {@link ScopeId} in which to create the {@link Group} + * @param groupCreator + * Provides the information for the new {@link Group} to be created. * @return The newly created {@link Group} object. */ @POST - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public Response create( @PathParam("scopeId") ScopeId scopeId, GroupCreator groupCreator) throws KapuaException { @@ -158,15 +171,18 @@ public Response create( /** * Returns the Group specified by the "groupId" path parameter. * - * @param scopeId The {@link ScopeId} of the requested {@link Group}. - * @param groupId The id of the requested Group. + * @param scopeId + * The {@link ScopeId} of the requested {@link Group}. + * @param groupId + * The id of the requested Group. * @return The requested Group object. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @GET @Path("{groupId}") - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public Group find( @PathParam("scopeId") ScopeId scopeId, @PathParam("groupId") EntityId groupId) throws KapuaException { @@ -178,17 +194,21 @@ public Group find( /** * Updates the Group based on the information provided in the Group parameter. * - * @param scopeId The ScopeId of the requested {@link Group}. - * @param groupId The id of the requested {@link Group} - * @param group The modified Group whose attributed need to be updated. + * @param scopeId + * The ScopeId of the requested {@link Group}. + * @param groupId + * The id of the requested {@link Group} + * @param group + * The modified Group whose attributed need to be updated. * @return The updated group. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @PUT @Path("{groupId}") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public Group update( @PathParam("scopeId") ScopeId scopeId, @PathParam("groupId") EntityId groupId, @@ -202,10 +222,13 @@ public Group update( /** * Deletes the Group specified by the "groupId" path parameter. * - * @param scopeId The ScopeId of the requested {@link Group}. - * @param groupId The id of the Group to be deleted. + * @param scopeId + * The ScopeId of the requested {@link Group}. + * @param groupId + * The id of the Group to be deleted. * @return HTTP 200 if operation has completed successfully. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @DELETE diff --git a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/JobExecutions.java b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/JobExecutions.java index 4c0b6661783..812304a628d 100644 --- a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/JobExecutions.java +++ b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/JobExecutions.java @@ -23,7 +23,6 @@ import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; -import com.google.common.base.Strings; import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.app.api.core.model.CountResult; import org.eclipse.kapua.app.api.core.model.DateParam; @@ -31,6 +30,7 @@ import org.eclipse.kapua.app.api.core.model.ScopeId; import org.eclipse.kapua.app.api.core.resources.AbstractKapuaResource; import org.eclipse.kapua.model.KapuaEntityAttributes; +import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.model.query.SortOrder; import org.eclipse.kapua.model.query.predicate.AndPredicate; import org.eclipse.kapua.model.query.predicate.AttributePredicate; @@ -44,9 +44,10 @@ import org.eclipse.kapua.service.job.execution.JobExecutionService; import org.eclipse.kapua.service.job.targets.JobTargetFactory; import org.eclipse.kapua.service.job.targets.JobTargetListResult; -import org.eclipse.kapua.service.job.targets.JobTargetQuery; import org.eclipse.kapua.service.job.targets.JobTargetService; +import com.google.common.base.Strings; + @Path("{scopeId}/jobs/{jobId}/executions") public class JobExecutions extends AbstractKapuaResource { @@ -62,19 +63,27 @@ public class JobExecutions extends AbstractKapuaResource { /** * Gets the {@link JobExecution} list for a given {@link Job}. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param jobId The {@link Job} id to filter results - * @param askTotalCount Ask for the total count of the matched entities in the result - * @param sortParam The name of the parameter that will be used as a sorting key - * @param sortDir The sort direction. Can be ASCENDING (default), DESCENDING. Case-insensitive. - * @param offset The result set offset. - * @param limit The result set limit. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param jobId + * The {@link Job} id to filter results + * @param askTotalCount + * Ask for the total count of the matched entities in the result + * @param sortParam + * The name of the parameter that will be used as a sorting key + * @param sortDir + * The sort direction. Can be ASCENDING (default), DESCENDING. Case-insensitive. + * @param offset + * The result set offset. + * @param limit + * The result set limit. * @return The {@link JobExecutionListResult} of all the jobs executions associated to the current selected job. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @GET - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public JobExecutionListResult simpleQuery( @PathParam("scopeId") ScopeId scopeId, @PathParam("jobId") EntityId jobId, @@ -85,7 +94,7 @@ public JobExecutionListResult simpleQuery( @QueryParam("sortDir") @DefaultValue("ASCENDING") SortOrder sortDir, @QueryParam("offset") @DefaultValue("0") int offset, @QueryParam("limit") @DefaultValue("50") int limit) throws KapuaException { - JobExecutionQuery query = jobExecutionFactory.newQuery(scopeId); + JobExecutionQuery query = new JobExecutionQuery(scopeId); AndPredicate andPredicate = query.andPredicate(query.attributePredicate(JobExecutionAttributes.JOB_ID, jobId)); @@ -112,24 +121,27 @@ public JobExecutionListResult simpleQuery( /** * Queries the results with the given {@link JobExecutionQuery} parameter. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param query The {@link JobExecutionQuery} to use to filter results. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param query + * The {@link JobExecutionQuery} to use to filter results. * @return The {@link JobExecutionListResult} of all the result matching the given {@link JobExecutionQuery} parameter. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @POST @Path("_query") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public JobExecutionListResult query( @PathParam("scopeId") ScopeId scopeId, @PathParam("jobId") EntityId jobId, JobExecutionQuery query) throws KapuaException { query.setScopeId(scopeId); final AndPredicate andPredicate = query.andPredicate( - query.attributePredicate(JobExecutionAttributes.JOB_ID, jobId), - query.getPredicate() + query.attributePredicate(JobExecutionAttributes.JOB_ID, jobId), + query.getPredicate() ); query.setPredicate(andPredicate); return jobExecutionService.query(query); @@ -138,16 +150,19 @@ public JobExecutionListResult query( /** * Counts the results with the given {@link JobExecutionQuery} parameter. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param query The {@link JobExecutionQuery} to use to filter results. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param query + * The {@link JobExecutionQuery} to use to filter results. * @return The count of all the result matching the given {@link JobExecutionQuery} parameter. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @POST @Path("_count") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public CountResult count( @PathParam("scopeId") ScopeId scopeId, @PathParam("jobId") EntityId jobId, @@ -161,21 +176,25 @@ public CountResult count( /** * Returns the Job specified by the "jobId" path parameter. * - * @param scopeId The {@link ScopeId} of the requested {@link Job}. - * @param jobId The id of the requested Job. - * @param executionId The id of the requested JobExecution. + * @param scopeId + * The {@link ScopeId} of the requested {@link Job}. + * @param jobId + * The id of the requested Job. + * @param executionId + * The id of the requested JobExecution. * @return The requested Job object. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @GET @Path("{executionId}") - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public JobExecution find( @PathParam("scopeId") ScopeId scopeId, @PathParam("jobId") EntityId jobId, @PathParam("executionId") EntityId executionId) throws KapuaException { - JobExecutionQuery jobExecutionQuery = jobExecutionFactory.newQuery(scopeId); + JobExecutionQuery jobExecutionQuery = new JobExecutionQuery(scopeId); jobExecutionQuery.setPredicate(jobExecutionQuery.andPredicate( jobExecutionQuery.attributePredicate(JobExecutionAttributes.JOB_ID, jobId), jobExecutionQuery.attributePredicate(KapuaEntityAttributes.ENTITY_ID, executionId) @@ -189,7 +208,7 @@ public JobExecution find( @GET @Path("{executionId}/targets") - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public JobTargetListResult executionsByTarget( @PathParam("scopeId") ScopeId scopeId, @PathParam("jobId") EntityId jobId, @@ -197,7 +216,7 @@ public JobTargetListResult executionsByTarget( @QueryParam("offset") @DefaultValue("0") int offset, @QueryParam("limit") @DefaultValue("50") int limit) throws KapuaException { JobExecution jobExecution = jobExecutionService.find(scopeId, executionId); - JobTargetQuery jobTargetQuery = jobTargetFactory.newQuery(scopeId); + KapuaQuery jobTargetQuery = new KapuaQuery(scopeId); jobTargetQuery.setPredicate(jobTargetQuery.attributePredicate(KapuaEntityAttributes.ENTITY_ID, jobExecution.getTargetIds())); jobTargetQuery.setLimit(limit); jobTargetQuery.setOffset(offset); diff --git a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/JobStepDefinitions.java b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/JobStepDefinitions.java index d6109fb64e3..fe5071c9ff1 100644 --- a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/JobStepDefinitions.java +++ b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/JobStepDefinitions.java @@ -12,34 +12,35 @@ *******************************************************************************/ package org.eclipse.kapua.app.api.resources.v1.resources; -import com.google.common.base.Strings; +import javax.inject.Inject; +import javax.ws.rs.Consumes; +import javax.ws.rs.DefaultValue; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.app.api.core.model.CountResult; import org.eclipse.kapua.app.api.core.model.EntityId; import org.eclipse.kapua.app.api.core.model.ScopeId; import org.eclipse.kapua.app.api.core.resources.AbstractKapuaResource; +import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.model.query.SortOrder; import org.eclipse.kapua.service.KapuaService; import org.eclipse.kapua.service.job.Job; import org.eclipse.kapua.service.job.step.JobStep; import org.eclipse.kapua.service.job.step.JobStepListResult; -import org.eclipse.kapua.service.job.step.JobStepQuery; import org.eclipse.kapua.service.job.step.definition.JobStepDefinition; import org.eclipse.kapua.service.job.step.definition.JobStepDefinitionFactory; import org.eclipse.kapua.service.job.step.definition.JobStepDefinitionListResult; import org.eclipse.kapua.service.job.step.definition.JobStepDefinitionQuery; import org.eclipse.kapua.service.job.step.definition.JobStepDefinitionService; -import javax.inject.Inject; -import javax.ws.rs.Consumes; -import javax.ws.rs.DefaultValue; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.MediaType; +import com.google.common.base.Strings; @Path("{scopeId}/jobStepDefinitions") public class JobStepDefinitions extends AbstractKapuaResource { @@ -52,17 +53,23 @@ public class JobStepDefinitions extends AbstractKapuaResource { /** * Gets the {@link JobStep} list for a given {@link Job}. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param sortParam The name of the parameter that will be used as a sorting key - * @param sortDir The sort direction. Can be ASCENDING (default), DESCENDING. Case-insensitive. - * @param offset The result set offset. - * @param limit The result set limit. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param sortParam + * The name of the parameter that will be used as a sorting key + * @param sortDir + * The sort direction. Can be ASCENDING (default), DESCENDING. Case-insensitive. + * @param offset + * The result set offset. + * @param limit + * The result set limit. * @return The {@link JobStepListResult} of all the jobs jobSteps associated to the current selected job. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.5.0 */ @GET - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public JobStepDefinitionListResult simpleQuery( @PathParam("scopeId") ScopeId scopeId, @QueryParam("sortParam") String sortParam, @@ -70,7 +77,7 @@ public JobStepDefinitionListResult simpleQuery( @QueryParam("offset") @DefaultValue("0") int offset, @QueryParam("limit") @DefaultValue("50") int limit) throws KapuaException { - JobStepDefinitionQuery query = jobStepDefinitionFactory.newQuery(scopeId); + JobStepDefinitionQuery query = new JobStepDefinitionQuery(scopeId); if (!Strings.isNullOrEmpty(sortParam)) { query.setSortCriteria(query.fieldSortCriteria(sortParam, sortDir)); @@ -83,18 +90,21 @@ public JobStepDefinitionListResult simpleQuery( } /** - * Queries the results with the given {@link JobStepQuery} parameter. + * Queries the results with the given {@link JobStepDefinitionQuery} parameter. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param query The {@link JobStepQuery} to use to filter results. - * @return The {@link JobStepListResult} of all the result matching the given {@link JobStepQuery} parameter. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param query + * The {@link JobStepDefinitionQuery} to use to filter results. + * @return The {@link JobStepListResult} of all the result matching the given {@link JobStepDefinitionQuery} parameter. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.5.0 */ @POST @Path("_query") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public JobStepDefinitionListResult query( @PathParam("scopeId") ScopeId scopeId, JobStepDefinitionQuery query) throws KapuaException { @@ -104,21 +114,24 @@ public JobStepDefinitionListResult query( } /** - * Counts the results with the given {@link JobStepQuery} parameter. + * Counts the results with the given {@link KapuaQuery} parameter. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param query The {@link JobStepQuery} to use to filter results. - * @return The count of all the result matching the given {@link JobStepQuery} parameter. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param query + * The {@link KapuaQuery} to use to filter results. + * @return The count of all the result matching the given {@link KapuaQuery} parameter. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.5.0 */ @POST @Path("_count") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public CountResult count( @PathParam("scopeId") ScopeId scopeId, - JobStepQuery query) throws KapuaException { + KapuaQuery query) throws KapuaException { query.setScopeId(scopeId); return new CountResult(jobStepDefinitionService.count(query)); @@ -127,15 +140,18 @@ public CountResult count( /** * Returns the Job specified by the "jobId" path parameter. * - * @param scopeId The {@link ScopeId} of the requested {@link Job}. - * @param stepDefinitionId The id of the requested JobStep. + * @param scopeId + * The {@link ScopeId} of the requested {@link Job}. + * @param stepDefinitionId + * The id of the requested JobStep. * @return The requested Job object. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.5.0 */ @GET @Path("{stepDefinitionId}") - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public JobStepDefinition find( @PathParam("scopeId") ScopeId scopeId, @PathParam("stepDefinitionId") EntityId stepDefinitionId) throws KapuaException { diff --git a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/JobSteps.java b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/JobSteps.java index e545f351bcd..cec577c28e3 100644 --- a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/JobSteps.java +++ b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/JobSteps.java @@ -12,13 +12,27 @@ *******************************************************************************/ package org.eclipse.kapua.app.api.resources.v1.resources; -import com.google.common.base.Strings; +import javax.inject.Inject; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.DefaultValue; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.app.api.core.model.CountResult; import org.eclipse.kapua.app.api.core.model.EntityId; import org.eclipse.kapua.app.api.core.model.ScopeId; import org.eclipse.kapua.app.api.core.resources.AbstractKapuaResource; import org.eclipse.kapua.model.KapuaNamedEntityAttributes; +import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.model.query.SortOrder; import org.eclipse.kapua.model.query.predicate.AndPredicate; import org.eclipse.kapua.model.query.predicate.QueryPredicate; @@ -29,22 +43,9 @@ import org.eclipse.kapua.service.job.step.JobStepCreator; import org.eclipse.kapua.service.job.step.JobStepFactory; import org.eclipse.kapua.service.job.step.JobStepListResult; -import org.eclipse.kapua.service.job.step.JobStepQuery; import org.eclipse.kapua.service.job.step.JobStepService; -import javax.inject.Inject; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.DefaultValue; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; +import com.google.common.base.Strings; @Path("{scopeId}/jobs/{jobId}/steps") public class JobSteps extends AbstractKapuaResource { @@ -57,20 +58,29 @@ public class JobSteps extends AbstractKapuaResource { /** * Gets the {@link JobStep} list for a given {@link Job}. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param jobId The {@link Job} id to filter results - * @param name The name of the {@link JobStep} to filter result - * @param sortParam The name of the parameter that will be used as a sorting key - * @param sortDir The sort direction. Can be ASCENDING (default), DESCENDING. Case-insensitive. - * @param askTotalCount Ask for the total count of the matched entities in the result - * @param offset The result set offset. - * @param limit The result set limit. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param jobId + * The {@link Job} id to filter results + * @param name + * The name of the {@link JobStep} to filter result + * @param sortParam + * The name of the parameter that will be used as a sorting key + * @param sortDir + * The sort direction. Can be ASCENDING (default), DESCENDING. Case-insensitive. + * @param askTotalCount + * Ask for the total count of the matched entities in the result + * @param offset + * The result set offset. + * @param limit + * The result set limit. * @return The {@link JobStepListResult} of all the jobs jobSteps associated to the current selected job. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @GET - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public JobStepListResult simpleQuery( @PathParam("scopeId") ScopeId scopeId, @PathParam("jobId") EntityId jobId, @@ -81,7 +91,7 @@ public JobStepListResult simpleQuery( @QueryParam("offset") @DefaultValue("0") int offset, @QueryParam("limit") @DefaultValue("50") int limit) throws KapuaException { - JobStepQuery query = jobStepFactory.newQuery(scopeId); + KapuaQuery query = new KapuaQuery(scopeId); AndPredicate andPredicate = query.andPredicate(query.attributePredicate(JobStepAttributes.JOB_ID, jobId)); @@ -103,22 +113,25 @@ public JobStepListResult simpleQuery( } /** - * Queries the results with the given {@link JobStepQuery} parameter. + * Queries the results with the given {@link KapuaQuery} parameter. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param query The {@link JobStepQuery} to use to filter results. - * @return The {@link JobStepListResult} of all the result matching the given {@link JobStepQuery} parameter. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param query + * The {@link KapuaQuery} to use to filter results. + * @return The {@link JobStepListResult} of all the result matching the given {@link KapuaQuery} parameter. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @POST @Path("_query") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public JobStepListResult query( @PathParam("scopeId") ScopeId scopeId, @PathParam("jobId") EntityId jobId, - JobStepQuery query) throws KapuaException { + KapuaQuery query) throws KapuaException { query.setScopeId(scopeId); QueryPredicate predicate; if (query.getPredicate() != null) { @@ -131,22 +144,25 @@ public JobStepListResult query( } /** - * Counts the results with the given {@link JobStepQuery} parameter. + * Counts the results with the given {@link KapuaQuery} parameter. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param query The {@link JobStepQuery} to use to filter results. - * @return The count of all the result matching the given {@link JobStepQuery} parameter. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param query + * The {@link KapuaQuery} to use to filter results. + * @return The count of all the result matching the given {@link KapuaQuery} parameter. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @POST @Path("_count") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public CountResult count( @PathParam("scopeId") ScopeId scopeId, @PathParam("jobId") EntityId jobId, - JobStepQuery query) throws KapuaException { + KapuaQuery query) throws KapuaException { query.setScopeId(scopeId); query.setPredicate(query.attributePredicate(JobStepAttributes.JOB_ID, jobId)); @@ -156,16 +172,20 @@ public CountResult count( /** * Returns the Job specified by the "jobId" path parameter. * - * @param scopeId The {@link ScopeId} of the requested {@link Job}. - * @param jobId The id of the requested Job. - * @param stepId The id of the requested JobStep. + * @param scopeId + * The {@link ScopeId} of the requested {@link Job}. + * @param jobId + * The id of the requested Job. + * @param stepId + * The id of the requested JobStep. * @return The requested Job object. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @GET @Path("{stepId}") - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public JobStep find( @PathParam("scopeId") ScopeId scopeId, @PathParam("jobId") EntityId jobId, @@ -174,19 +194,22 @@ public JobStep find( } /** - * Creates a new {@link JobStep} based on the information provided in {@link JobStepCreator} - * parameter. + * Creates a new {@link JobStep} based on the information provided in {@link JobStepCreator} parameter. * - * @param scopeId The {@link ScopeId} in which to create the {@link JobStep} - * @param jobId The ID of the {@link Job} to attach the {@link JobStep} to - * @param jobStepCreator Provides the information for the new {@link JobStep} to be created. + * @param scopeId + * The {@link ScopeId} in which to create the {@link JobStep} + * @param jobId + * The ID of the {@link Job} to attach the {@link JobStep} to + * @param jobStepCreator + * Provides the information for the new {@link JobStep} to be created. * @return The newly created {@link JobStep} object. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.5.0 */ @POST - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public Response create( @PathParam("scopeId") ScopeId scopeId, @PathParam("jobId") EntityId jobId, @@ -197,21 +220,25 @@ public Response create( } /** - * Updates a new {@link JobStep} based on the information provided in {@link JobStep} - * parameter. + * Updates a new {@link JobStep} based on the information provided in {@link JobStep} parameter. * - * @param scopeId The {@link ScopeId} in which to create the {@link JobStep} - * @param jobId The ID of the {@link Job} to attach the {@link JobStep} to - * @param jobStep Provides the information for the new {@link JobStep} to be created. - * @param jobStepId The ID of the {@link JobStep} to be updated + * @param scopeId + * The {@link ScopeId} in which to create the {@link JobStep} + * @param jobId + * The ID of the {@link Job} to attach the {@link JobStep} to + * @param jobStep + * Provides the information for the new {@link JobStep} to be created. + * @param jobStepId + * The ID of the {@link JobStep} to be updated * @return The newly created {@link JobStep} object. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.5.0 */ @PUT @Path("{stepId}") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public JobStep update( @PathParam("scopeId") ScopeId scopeId, @PathParam("jobId") EntityId jobId, @@ -226,10 +253,13 @@ public JobStep update( /** * Deletes the JobStep specified by the "stepId" path parameter. * - * @param scopeId The ScopeId of the requested {@link JobStep}. - * @param stepId The id of the JobStep to be deleted. + * @param scopeId + * The ScopeId of the requested {@link JobStep}. + * @param stepId + * The id of the JobStep to be deleted. * @return HTTP 201 if operation has completed successfully. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.5.0 */ @DELETE diff --git a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/JobTargets.java b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/JobTargets.java index 3e460bad8ee..d05800be133 100644 --- a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/JobTargets.java +++ b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/JobTargets.java @@ -12,7 +12,19 @@ *******************************************************************************/ package org.eclipse.kapua.app.api.resources.v1.resources; -import com.google.common.base.Strings; +import javax.inject.Inject; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.DefaultValue; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.app.api.core.model.CountResult; import org.eclipse.kapua.app.api.core.model.EntityId; @@ -20,6 +32,7 @@ import org.eclipse.kapua.app.api.core.resources.AbstractKapuaResource; import org.eclipse.kapua.model.KapuaEntityAttributes; import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.model.query.SortOrder; import org.eclipse.kapua.model.query.predicate.AndPredicate; import org.eclipse.kapua.service.KapuaService; @@ -34,22 +47,10 @@ import org.eclipse.kapua.service.job.targets.JobTargetCreator; import org.eclipse.kapua.service.job.targets.JobTargetFactory; import org.eclipse.kapua.service.job.targets.JobTargetListResult; -import org.eclipse.kapua.service.job.targets.JobTargetQuery; import org.eclipse.kapua.service.job.targets.JobTargetService; import org.eclipse.kapua.service.job.targets.JobTargetStatus; -import javax.inject.Inject; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.DefaultValue; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; +import com.google.common.base.Strings; @Path("{scopeId}/jobs/{jobId}/targets") public class JobTargets extends AbstractKapuaResource { @@ -66,19 +67,27 @@ public class JobTargets extends AbstractKapuaResource { /** * Gets the {@link JobTarget} list for a given {@link Job}. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param jobId The {@link Job} id to filter results - * @param sortParam The name of the parameter that will be used as a sorting key - * @param sortDir The sort direction. Can be ASCENDING (default), DESCENDING. Case-insensitive. - * @param askTotalCount Ask for the total count of the matched entities in the result - * @param offset The result set offset. - * @param limit The result set limit. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param jobId + * The {@link Job} id to filter results + * @param sortParam + * The name of the parameter that will be used as a sorting key + * @param sortDir + * The sort direction. Can be ASCENDING (default), DESCENDING. Case-insensitive. + * @param askTotalCount + * Ask for the total count of the matched entities in the result + * @param offset + * The result set offset. + * @param limit + * The result set limit. * @return The {@link JobTargetListResult} of all the jobs targets associated to the current selected job. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @GET - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public JobTargetListResult simpleQuery( @PathParam("scopeId") ScopeId scopeId, @PathParam("jobId") EntityId jobId, @@ -88,7 +97,7 @@ public JobTargetListResult simpleQuery( @QueryParam("askTotalCount") boolean askTotalCount, @QueryParam("offset") @DefaultValue("0") int offset, @QueryParam("limit") @DefaultValue("50") int limit) throws KapuaException { - JobTargetQuery query = jobTargetFactory.newQuery(scopeId); + KapuaQuery query = new KapuaQuery(scopeId); AndPredicate andPredicate = query.andPredicate(query.attributePredicate(JobExecutionAttributes.JOB_ID, jobId)); @@ -110,44 +119,50 @@ public JobTargetListResult simpleQuery( } /** - * Queries the results with the given {@link JobTargetQuery} parameter. + * Queries the results with the given {@link KapuaQuery} parameter. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param query The {@link JobTargetQuery} to use to filter results. - * @return The {@link JobTargetListResult} of all the result matching the given {@link JobTargetQuery} parameter. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param query + * The {@link KapuaQuery} to use to filter results. + * @return The {@link JobTargetListResult} of all the result matching the given {@link KapuaQuery} parameter. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @POST @Path("_query") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public JobTargetListResult query( @PathParam("scopeId") ScopeId scopeId, @PathParam("jobId") EntityId jobId, - JobTargetQuery query) throws KapuaException { + KapuaQuery query) throws KapuaException { query.setScopeId(scopeId); query.setPredicate(query.attributePredicate(JobTargetAttributes.JOB_ID, jobId)); return jobTargetService.query(query); } /** - * Counts the results with the given {@link JobTargetQuery} parameter. + * Counts the results with the given {@link KapuaQuery} parameter. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param query The {@link JobTargetQuery} to use to filter results. - * @return The count of all the result matching the given {@link JobTargetQuery} parameter. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param query + * The {@link KapuaQuery} to use to filter results. + * @return The count of all the result matching the given {@link KapuaQuery} parameter. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @POST @Path("_count") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public CountResult count( @PathParam("scopeId") ScopeId scopeId, @PathParam("jobId") EntityId jobId, - JobTargetQuery query) throws KapuaException { + KapuaQuery query) throws KapuaException { query.setScopeId(scopeId); query.setPredicate(query.attributePredicate(JobTargetAttributes.JOB_ID, jobId)); @@ -157,21 +172,25 @@ public CountResult count( /** * Returns the Job specified by the "jobId" path parameter. * - * @param scopeId The {@link ScopeId} of the requested {@link Job}. - * @param jobId The id of the requested Job. - * @param targetId The id of the requested JobTarget. + * @param scopeId + * The {@link ScopeId} of the requested {@link Job}. + * @param jobId + * The id of the requested Job. + * @param targetId + * The id of the requested JobTarget. * @return The requested Job object. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @GET @Path("{targetId}") - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public JobTarget find( @PathParam("scopeId") ScopeId scopeId, @PathParam("jobId") EntityId jobId, @PathParam("targetId") EntityId targetId) throws KapuaException { - JobTargetQuery jobTargetQuery = jobTargetFactory.newQuery(scopeId); + KapuaQuery jobTargetQuery = new KapuaQuery(scopeId); jobTargetQuery.setPredicate(jobTargetQuery.andPredicate( jobTargetQuery.attributePredicate(JobTargetAttributes.JOB_ID, jobId), jobTargetQuery.attributePredicate(KapuaEntityAttributes.ENTITY_ID, targetId) @@ -185,15 +204,15 @@ public JobTarget find( @GET @Path("{targetId}/executions") - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public JobExecutionListResult executionsByTarget( @PathParam("scopeId") ScopeId scopeId, @PathParam("jobId") EntityId jobId, @PathParam("targetId") EntityId targetId, @QueryParam("offset") @DefaultValue("0") int offset, @QueryParam("limit") @DefaultValue("50") int limit) throws KapuaException { - JobExecutionQuery jobExecutionQuery = jobExecutionFactory.newQuery(scopeId); - jobExecutionQuery.setPredicate(jobExecutionQuery.attributePredicate(JobExecutionAttributes.TARGET_IDS, new KapuaId[]{targetId})); + JobExecutionQuery jobExecutionQuery = new JobExecutionQuery(scopeId); + jobExecutionQuery.setPredicate(jobExecutionQuery.attributePredicate(JobExecutionAttributes.TARGET_IDS, new KapuaId[] { targetId })); JobExecutionListResult jobExecutionListResult = jobExecutionService.query(jobExecutionQuery); jobExecutionQuery.setOffset(offset); @@ -203,20 +222,23 @@ public JobExecutionListResult executionsByTarget( } /** - * Creates a new {@link JobTarget} based on the information provided in {@link JobTargetCreator} - * parameter. + * Creates a new {@link JobTarget} based on the information provided in {@link JobTargetCreator} parameter. * - * @param scopeId The {@link ScopeId} in which to create the {@link JobTarget} - * @param jobId The ID of the {@link Job} to attach the {@link JobTarget} to - * @param jobTargetCreator Provides the information for the new {@link JobTarget} to be created. + * @param scopeId + * The {@link ScopeId} in which to create the {@link JobTarget} + * @param jobId + * The ID of the {@link Job} to attach the {@link JobTarget} to + * @param jobTargetCreator + * Provides the information for the new {@link JobTarget} to be created. * @return The newly created {@link JobTarget} object. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.5.0 */ @POST - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public Response create( @PathParam("scopeId") ScopeId scopeId, @PathParam("jobId") EntityId jobId, @@ -230,10 +252,13 @@ public Response create( /** * Deletes the JobTarget specified by the "targetId" path parameter. * - * @param scopeId The ScopeId of the requested {@link JobTarget}. - * @param targetId The id of the JobTarget to be deleted. + * @param scopeId + * The ScopeId of the requested {@link JobTarget}. + * @param targetId + * The id of the JobTarget to be deleted. * @return HTTP 201 if operation has completed successfully. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.5.0 */ diff --git a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/JobTriggerDefinitions.java b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/JobTriggerDefinitions.java index c6c2bb867b2..ac33e964370 100644 --- a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/JobTriggerDefinitions.java +++ b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/JobTriggerDefinitions.java @@ -12,7 +12,17 @@ *******************************************************************************/ package org.eclipse.kapua.app.api.resources.v1.resources; -import com.google.common.base.Strings; +import javax.inject.Inject; +import javax.ws.rs.Consumes; +import javax.ws.rs.DefaultValue; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.app.api.core.model.CountResult; import org.eclipse.kapua.app.api.core.model.EntityId; @@ -27,16 +37,7 @@ import org.eclipse.kapua.service.scheduler.trigger.definition.TriggerDefinitionQuery; import org.eclipse.kapua.service.scheduler.trigger.definition.TriggerDefinitionService; -import javax.inject.Inject; -import javax.ws.rs.Consumes; -import javax.ws.rs.DefaultValue; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.MediaType; +import com.google.common.base.Strings; @Path("{scopeId}/triggerDefinitions") public class JobTriggerDefinitions extends AbstractKapuaResource { @@ -49,17 +50,23 @@ public class JobTriggerDefinitions extends AbstractKapuaResource { /** * Gets the {@link TriggerDefinition} list for a given {@link Job}. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param sortParam The name of the parameter that will be used as a sorting key - * @param sortDir The sort direction. Can be ASCENDING (default), DESCENDING. Case-insensitive. - * @param offset The result set offset. - * @param limit The result set limit. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param sortParam + * The name of the parameter that will be used as a sorting key + * @param sortDir + * The sort direction. Can be ASCENDING (default), DESCENDING. Case-insensitive. + * @param offset + * The result set offset. + * @param limit + * The result set limit. * @return The {@link TriggerDefinitionListResult} of all the jobs triggers associated to the current selected job. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.5.0 */ @GET - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public TriggerDefinitionListResult simpleQuery( @PathParam("scopeId") ScopeId scopeId, @QueryParam("sortParam") String sortParam, @@ -67,7 +74,7 @@ public TriggerDefinitionListResult simpleQuery( @QueryParam("offset") @DefaultValue("0") int offset, @QueryParam("limit") @DefaultValue("50") int limit) throws KapuaException { - TriggerDefinitionQuery query = triggerDefinitionFactory.newQuery(null); + TriggerDefinitionQuery query = new TriggerDefinitionQuery(); if (!Strings.isNullOrEmpty(sortParam)) { query.setSortCriteria(query.fieldSortCriteria(sortParam, sortDir)); @@ -82,16 +89,19 @@ public TriggerDefinitionListResult simpleQuery( /** * Queries the results with the given {@link TriggerDefinitionQuery} parameter. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param query The {@link TriggerDefinitionQuery} to use to filter results. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param query + * The {@link TriggerDefinitionQuery} to use to filter results. * @return The {@link TriggerDefinitionListResult} of all the result matching the given {@link TriggerDefinitionQuery} parameter. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.5.0 */ @POST @Path("_query") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public TriggerDefinitionListResult query( @PathParam("scopeId") ScopeId scopeId, TriggerDefinitionQuery query) throws KapuaException { @@ -102,16 +112,19 @@ public TriggerDefinitionListResult query( /** * Counts the results with the given {@link TriggerDefinitionQuery} parameter. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param query The {@link TriggerDefinitionQuery} to use to filter results. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param query + * The {@link TriggerDefinitionQuery} to use to filter results. * @return The count of all the result matching the given {@link TriggerDefinitionQuery} parameter. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.5.0 */ @POST @Path("_count") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public CountResult count( @PathParam("scopeId") ScopeId scopeId, TriggerDefinitionQuery query) throws KapuaException { @@ -123,15 +136,18 @@ public CountResult count( /** * Returns the Job specified by the "jobId" path parameter. * - * @param scopeId The {@link ScopeId} of the requested {@link Job}. - * @param triggerDefinitionId The id of the requested Trigger Definition. + * @param scopeId + * The {@link ScopeId} of the requested {@link Job}. + * @param triggerDefinitionId + * The id of the requested Trigger Definition. * @return The requested Job object. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.5.0 */ @GET @Path("{triggerDefinitionId}") - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public TriggerDefinition find( @PathParam("scopeId") ScopeId scopeId, @PathParam("triggerDefinitionId") EntityId triggerDefinitionId) throws KapuaException { diff --git a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/JobTriggers.java b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/JobTriggers.java index 67a87649e15..56f86874ba6 100644 --- a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/JobTriggers.java +++ b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/JobTriggers.java @@ -12,7 +12,24 @@ *******************************************************************************/ package org.eclipse.kapua.app.api.resources.v1.resources; -import com.google.common.base.Strings; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import javax.inject.Inject; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.DefaultValue; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.app.api.core.model.CountResult; import org.eclipse.kapua.app.api.core.model.EntityId; @@ -21,6 +38,7 @@ import org.eclipse.kapua.model.KapuaEntityAttributes; import org.eclipse.kapua.model.KapuaNamedEntityAttributes; import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.model.query.SortOrder; import org.eclipse.kapua.model.query.predicate.AndPredicate; import org.eclipse.kapua.model.query.predicate.AttributePredicate; @@ -32,26 +50,10 @@ import org.eclipse.kapua.service.scheduler.trigger.TriggerCreator; import org.eclipse.kapua.service.scheduler.trigger.TriggerFactory; import org.eclipse.kapua.service.scheduler.trigger.TriggerListResult; -import org.eclipse.kapua.service.scheduler.trigger.TriggerQuery; import org.eclipse.kapua.service.scheduler.trigger.TriggerService; import org.eclipse.kapua.service.scheduler.trigger.definition.TriggerProperty; -import javax.inject.Inject; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.DefaultValue; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; +import com.google.common.base.Strings; @Path("{scopeId}/jobs/{jobId}/triggers") public class JobTriggers extends AbstractKapuaResource { @@ -64,20 +66,29 @@ public class JobTriggers extends AbstractKapuaResource { /** * Gets the {@link Trigger} list for a given {@link Job}. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param jobId The {@link Job} id to filter results - * @param name The name of the {@link Trigger} to filter result - * @param sortParam The name of the parameter that will be used as a sorting key - * @param sortDir The sort direction. Can be ASCENDING (default), DESCENDING. Case-insensitive. - * @param askTotalCount Ask for the total count of the matched entities in the result - * @param offset The result set offset. - * @param limit The result set limit. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param jobId + * The {@link Job} id to filter results + * @param name + * The name of the {@link Trigger} to filter result + * @param sortParam + * The name of the parameter that will be used as a sorting key + * @param sortDir + * The sort direction. Can be ASCENDING (default), DESCENDING. Case-insensitive. + * @param askTotalCount + * Ask for the total count of the matched entities in the result + * @param offset + * The result set offset. + * @param limit + * The result set limit. * @return The {@link TriggerListResult} of all the jobs triggers associated to the current selected job. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @GET - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public TriggerListResult simpleQuery( @PathParam("scopeId") ScopeId scopeId, @PathParam("jobId") EntityId jobId, @@ -88,7 +99,7 @@ public TriggerListResult simpleQuery( @QueryParam("offset") @DefaultValue("0") int offset, @QueryParam("limit") @DefaultValue("50") int limit) throws KapuaException { - TriggerQuery query = triggerFactory.newQuery(scopeId); + KapuaQuery query = new KapuaQuery(scopeId); AndPredicate andPredicate = query.andPredicate(returnJobIdPredicate(jobId, query)); @@ -109,22 +120,25 @@ public TriggerListResult simpleQuery( } /** - * Queries the results with the given {@link TriggerQuery} parameter. + * Queries the results with the given {@link KapuaQuery} parameter. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param query The {@link TriggerQuery} to use to filter results. - * @return The {@link TriggerListResult} of all the result matching the given {@link TriggerQuery} parameter. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param query + * The {@link KapuaQuery} to use to filter results. + * @return The {@link TriggerListResult} of all the result matching the given {@link KapuaQuery} parameter. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @POST @Path("_query") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public TriggerListResult query( @PathParam("scopeId") ScopeId scopeId, @PathParam("jobId") EntityId jobId, - TriggerQuery query) throws KapuaException { + KapuaQuery query) throws KapuaException { query.setScopeId(scopeId); QueryPredicate predicate; if (query.getPredicate() != null) { @@ -137,22 +151,25 @@ public TriggerListResult query( } /** - * Counts the results with the given {@link TriggerQuery} parameter. + * Counts the results with the given {@link KapuaQuery} parameter. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param query The {@link TriggerQuery} to use to filter results. - * @return The count of all the result matching the given {@link TriggerQuery} parameter. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param query + * The {@link KapuaQuery} to use to filter results. + * @return The count of all the result matching the given {@link KapuaQuery} parameter. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @POST @Path("_count") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public CountResult count( @PathParam("scopeId") ScopeId scopeId, @PathParam("jobId") EntityId jobId, - TriggerQuery query) throws KapuaException { + KapuaQuery query) throws KapuaException { query.setScopeId(scopeId); query.setPredicate(returnJobIdPredicate(jobId, query)); @@ -162,21 +179,25 @@ public CountResult count( /** * Returns the Job specified by the "jobId" path parameter. * - * @param scopeId The {@link ScopeId} of the requested {@link Job}. - * @param jobId The id of the requested Job. - * @param triggerId The id of the requested Trigger. + * @param scopeId + * The {@link ScopeId} of the requested {@link Job}. + * @param jobId + * The id of the requested Job. + * @param triggerId + * The id of the requested Trigger. * @return The requested Job object. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @GET @Path("{triggerId}") - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public Trigger find( @PathParam("scopeId") ScopeId scopeId, @PathParam("jobId") EntityId jobId, @PathParam("triggerId") EntityId triggerId) throws KapuaException { - TriggerQuery triggerQuery = triggerFactory.newQuery(scopeId); + KapuaQuery triggerQuery = new KapuaQuery(scopeId); triggerQuery.setPredicate(triggerQuery.andPredicate( returnJobIdPredicate(jobId, triggerQuery), triggerQuery.attributePredicate(KapuaEntityAttributes.ENTITY_ID, triggerId) @@ -188,7 +209,7 @@ public Trigger find( return returnNotNullEntity(triggerListResult.getFirstItem(), Trigger.TYPE, triggerId); } - private AndPredicate returnJobIdPredicate(KapuaId jobId, TriggerQuery query) { + private AndPredicate returnJobIdPredicate(KapuaId jobId, KapuaQuery query) { AttributePredicate kapuaPropertyNameAttributePredicate = query.attributePredicate(TriggerAttributes.TRIGGER_PROPERTIES_NAME, "jobId"); AttributePredicate kapuaPropertyValueAttributePredicate = query.attributePredicate(TriggerAttributes.TRIGGER_PROPERTIES_VALUE, jobId.toCompactId()); AttributePredicate kapuaPropertyTypeAttributePredicate = query.attributePredicate(TriggerAttributes.TRIGGER_PROPERTIES_TYPE, KapuaId.class.getName()); @@ -201,20 +222,23 @@ private AndPredicate returnJobIdPredicate(KapuaId jobId, TriggerQuery query) { } /** - * Creates a new {@link Trigger} based on the information provided in {@link TriggerCreator} - * parameter. + * Creates a new {@link Trigger} based on the information provided in {@link TriggerCreator} parameter. * - * @param scopeId The {@link ScopeId} in which to create the {@link Trigger} - * @param triggerCreator Provides the information for the new {@link Trigger} to be created. - * @param jobId The ID of the {@link Job} to attach the {@link Trigger} to + * @param scopeId + * The {@link ScopeId} in which to create the {@link Trigger} + * @param triggerCreator + * Provides the information for the new {@link Trigger} to be created. + * @param jobId + * The ID of the {@link Job} to attach the {@link Trigger} to * @return The newly created {@link Trigger} object. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.5.0 */ @POST - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public Response create( @PathParam("scopeId") ScopeId scopeId, @PathParam("jobId") EntityId jobId, @@ -225,29 +249,33 @@ public Response create( triggerProperties = new ArrayList<>(); triggerCreator.setTriggerProperties(triggerProperties); } - triggerProperties.removeIf(triggerProperty -> Arrays.stream(new String[]{"scopeId", "jobId"}).anyMatch(propertyToRemove -> propertyToRemove.equals(triggerProperty.getName()))); + triggerProperties.removeIf(triggerProperty -> Arrays.stream(new String[] { "scopeId", "jobId" }).anyMatch(propertyToRemove -> propertyToRemove.equals(triggerProperty.getName()))); triggerProperties.add(triggerFactory.newTriggerProperty("scopeId", KapuaId.class.getCanonicalName(), scopeId.toCompactId())); triggerProperties.add(triggerFactory.newTriggerProperty("jobId", KapuaId.class.getCanonicalName(), jobId.toCompactId())); return returnCreated(triggerService.create(triggerCreator)); } /** - * Updates a {@link Trigger} based on the information provided in the provided {@link Trigger} - * parameter. + * Updates a {@link Trigger} based on the information provided in the provided {@link Trigger} parameter. * - * @param scopeId The {@link ScopeId} in which to create the {@link Trigger} - * @param triggerId The ID of the {@link Trigger} to update - * @param trigger Provides the information for the new {@link Trigger} to be updated. - * @param jobId The ID of the {@link Job} to attach the {@link Trigger} to + * @param scopeId + * The {@link ScopeId} in which to create the {@link Trigger} + * @param triggerId + * The ID of the {@link Trigger} to update + * @param trigger + * Provides the information for the new {@link Trigger} to be updated. + * @param jobId + * The ID of the {@link Job} to attach the {@link Trigger} to * @return The updated {@link Trigger} object. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.5.0 */ @PUT @Path("{triggerId}") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public Trigger update( @PathParam("scopeId") ScopeId scopeId, @PathParam("jobId") EntityId jobId, @@ -258,7 +286,7 @@ public Trigger update( triggerProperties = new ArrayList<>(); trigger.setTriggerProperties(triggerProperties); } - triggerProperties.removeIf(triggerProperty -> Arrays.stream(new String[]{"scopeId", "jobId"}).anyMatch(propertyToRemove -> propertyToRemove.equals(triggerProperty.getName()))); + triggerProperties.removeIf(triggerProperty -> Arrays.stream(new String[] { "scopeId", "jobId" }).anyMatch(propertyToRemove -> propertyToRemove.equals(triggerProperty.getName()))); triggerProperties.add(triggerFactory.newTriggerProperty("scopeId", KapuaId.class.getCanonicalName(), scopeId.toCompactId())); triggerProperties.add(triggerFactory.newTriggerProperty("jobId", KapuaId.class.getCanonicalName(), jobId.toCompactId())); trigger.setScopeId(scopeId); @@ -269,10 +297,13 @@ public Trigger update( /** * Deletes the Trigger specified by the "triggerId" path parameter. * - * @param scopeId The ScopeId of the requested {@link Trigger}. - * @param triggerId The id of the Trigger to be deleted. + * @param scopeId + * The ScopeId of the requested {@link Trigger}. + * @param triggerId + * The id of the Trigger to be deleted. * @return HTTP 201 if operation has completed successfully. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.5.0 */ diff --git a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/JobTriggersFired.java b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/JobTriggersFired.java index 120501db918..45107a0d5c8 100644 --- a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/JobTriggersFired.java +++ b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/JobTriggersFired.java @@ -12,11 +12,23 @@ *******************************************************************************/ package org.eclipse.kapua.app.api.resources.v1.resources; +import javax.inject.Inject; +import javax.ws.rs.Consumes; +import javax.ws.rs.DefaultValue; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.app.api.core.model.CountResult; import org.eclipse.kapua.app.api.core.model.EntityId; import org.eclipse.kapua.app.api.core.model.ScopeId; import org.eclipse.kapua.app.api.core.resources.AbstractKapuaResource; +import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.model.query.SortOrder; import org.eclipse.kapua.model.query.predicate.AndPredicate; import org.eclipse.kapua.service.KapuaService; @@ -25,21 +37,9 @@ import org.eclipse.kapua.service.scheduler.trigger.fired.FiredTriggerAttributes; import org.eclipse.kapua.service.scheduler.trigger.fired.FiredTriggerFactory; import org.eclipse.kapua.service.scheduler.trigger.fired.FiredTriggerListResult; -import org.eclipse.kapua.service.scheduler.trigger.fired.FiredTriggerQuery; import org.eclipse.kapua.service.scheduler.trigger.fired.FiredTriggerService; import org.eclipse.kapua.service.scheduler.trigger.fired.FiredTriggerStatus; -import javax.inject.Inject; -import javax.ws.rs.Consumes; -import javax.ws.rs.DefaultValue; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.MediaType; - @Path("{scopeId}/jobs/{jobId}/triggers/{triggerId}/fired") public class JobTriggersFired extends AbstractKapuaResource { @@ -51,17 +51,23 @@ public class JobTriggersFired extends AbstractKapuaResource { /** * Gets the {@link Trigger} list for a given {@link Job}. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param jobId The {@link Job} id to filter results. - * @param offset The result set offset. - * @param limit The result set limit. - * @param askTotalCount Whether or not to fetch the total count of elements. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param jobId + * The {@link Job} id to filter results. + * @param offset + * The result set offset. + * @param limit + * The result set limit. + * @param askTotalCount + * Whether or not to fetch the total count of elements. * @return The {@link FiredTriggerListResult} of all the jobs triggers associated to the current selected job. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.5.0 */ @GET - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public FiredTriggerListResult simpleQuery( @PathParam("scopeId") ScopeId scopeId, @PathParam("jobId") EntityId jobId, @@ -71,7 +77,7 @@ public FiredTriggerListResult simpleQuery( @QueryParam("offset") @DefaultValue("0") int offset, @QueryParam("limit") @DefaultValue("50") int limit) throws KapuaException { - FiredTriggerQuery query = firedTriggerFactory.newQuery(scopeId); + KapuaQuery query = new KapuaQuery(scopeId); AndPredicate andPredicate = query.andPredicate( query.attributePredicate(FiredTriggerAttributes.TRIGGER_ID, triggerId) @@ -92,23 +98,26 @@ public FiredTriggerListResult simpleQuery( } /** - * Queries the results with the given {@link FiredTriggerQuery} parameter. + * Queries the results with the given {@link KapuaQuery} parameter. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param query The {@link FiredTriggerQuery} to use to filter results. - * @return The {@link FiredTriggerListResult} of all the result matching the given {@link FiredTriggerQuery} parameter. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param query + * The {@link KapuaQuery} to use to filter results. + * @return The {@link FiredTriggerListResult} of all the result matching the given {@link KapuaQuery} parameter. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.5.0 */ @POST @Path("_query") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public FiredTriggerListResult query( @PathParam("scopeId") ScopeId scopeId, @PathParam("jobId") EntityId jobId, @PathParam("triggerId") EntityId triggerId, - FiredTriggerQuery query) throws KapuaException { + KapuaQuery query) throws KapuaException { query.setScopeId(scopeId); AndPredicate andPredicate = query.andPredicate( @@ -125,23 +134,26 @@ public FiredTriggerListResult query( } /** - * Counts the results with the given {@link FiredTriggerQuery} parameter. + * Counts the results with the given {@link KapuaQuery} parameter. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param query The {@link FiredTriggerQuery} to use to filter results. - * @return The count of all the result matching the given {@link FiredTriggerQuery} parameter. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param query + * The {@link KapuaQuery} to use to filter results. + * @return The count of all the result matching the given {@link KapuaQuery} parameter. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.5.0 */ @POST @Path("_count") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public CountResult count( @PathParam("scopeId") ScopeId scopeId, @PathParam("jobId") EntityId jobId, @PathParam("triggerId") EntityId triggerId, - FiredTriggerQuery query) throws KapuaException { + KapuaQuery query) throws KapuaException { query.setScopeId(scopeId); AndPredicate andPredicate = query.andPredicate( diff --git a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/Jobs.java b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/Jobs.java index 093e92a473e..59d626b7cb1 100644 --- a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/Jobs.java +++ b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/Jobs.java @@ -12,7 +12,20 @@ *******************************************************************************/ package org.eclipse.kapua.app.api.resources.v1.resources; -import com.google.common.base.Strings; +import javax.inject.Inject; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.DefaultValue; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.app.api.core.model.CountResult; import org.eclipse.kapua.app.api.core.model.EntityId; @@ -29,19 +42,7 @@ import org.eclipse.kapua.service.job.JobQuery; import org.eclipse.kapua.service.job.JobService; -import javax.inject.Inject; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.DefaultValue; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; +import com.google.common.base.Strings; @Path("{scopeId}/jobs") public class Jobs extends AbstractKapuaResource { @@ -54,19 +55,27 @@ public class Jobs extends AbstractKapuaResource { /** * Gets the {@link Job} list in the scope. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param name The {@link Job} name to filter results - * @param sortParam The name of the parameter that will be used as a sorting key - * @param sortDir The sort direction. Can be ASCENDING (default), DESCENDING. Case-insensitive. - * @param askTotalCount Ask for the total count of the matched entities in the result - * @param offset The result set offset. - * @param limit The result set limit. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param name + * The {@link Job} name to filter results + * @param sortParam + * The name of the parameter that will be used as a sorting key + * @param sortDir + * The sort direction. Can be ASCENDING (default), DESCENDING. Case-insensitive. + * @param askTotalCount + * Ask for the total count of the matched entities in the result + * @param offset + * The result set offset. + * @param limit + * The result set limit. * @return The {@link JobListResult} of all the jobs associated to the current selected scope. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @GET - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public JobListResult simpleQuery( @PathParam("scopeId") ScopeId scopeId, @QueryParam("name") String name, @@ -76,7 +85,7 @@ public JobListResult simpleQuery( @QueryParam("askTotalCount") boolean askTotalCount, @QueryParam("offset") @DefaultValue("0") int offset, @QueryParam("limit") @DefaultValue("50") int limit) throws KapuaException { - JobQuery query = jobFactory.newQuery(scopeId); + JobQuery query = new JobQuery(scopeId); AndPredicate andPredicate = query.andPredicate(); if (!Strings.isNullOrEmpty(name)) { @@ -101,16 +110,19 @@ public JobListResult simpleQuery( /** * Queries the results with the given {@link JobQuery} parameter. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param query The {@link JobQuery} to use to filter results. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param query + * The {@link JobQuery} to use to filter results. * @return The {@link JobListResult} of all the result matching the given {@link JobQuery} parameter. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @POST @Path("_query") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public JobListResult query( @PathParam("scopeId") ScopeId scopeId, JobQuery query) throws KapuaException { @@ -122,16 +134,19 @@ public JobListResult query( /** * Counts the results with the given {@link JobQuery} parameter. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param query The {@link JobQuery} to use to filter results. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param query + * The {@link JobQuery} to use to filter results. * @return The count of all the result matching the given {@link JobQuery} parameter. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @POST @Path("_count") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public CountResult count( @PathParam("scopeId") ScopeId scopeId, JobQuery query) throws KapuaException { @@ -143,15 +158,18 @@ public CountResult count( /** * Returns the Job specified by the "jobId" path parameter. * - * @param scopeId The {@link ScopeId} of the requested {@link Job}. - * @param jobId The id of the requested Job. + * @param scopeId + * The {@link ScopeId} of the requested {@link Job}. + * @param jobId + * The id of the requested Job. * @return The requested Job object. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @GET @Path("{jobId}") - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public Job find( @PathParam("scopeId") ScopeId scopeId, @PathParam("jobId") EntityId jobId) throws KapuaException { @@ -161,18 +179,20 @@ public Job find( } /** - * Creates a new {@link Job} based on the information provided in {@link JobCreator} - * parameter. + * Creates a new {@link Job} based on the information provided in {@link JobCreator} parameter. * - * @param scopeId The {@link ScopeId} in which to create the {@link Job} - * @param jobCreator Provides the information for the new {@link Job} to be created. + * @param scopeId + * The {@link ScopeId} in which to create the {@link Job} + * @param jobCreator + * Provides the information for the new {@link Job} to be created. * @return The newly created {@link Job} object. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.5.0 */ @POST - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public Response create( @PathParam("scopeId") ScopeId scopeId, JobCreator jobCreator) throws KapuaException { @@ -184,17 +204,21 @@ public Response create( /** * Updates the Job based on the information provided in the Job parameter. * - * @param scopeId The ScopeId of the requested {@link Job}. - * @param jobId The id of the requested {@link Job} - * @param job The modified Job whose attributed need to be updated. + * @param scopeId + * The ScopeId of the requested {@link Job}. + * @param jobId + * The id of the requested {@link Job} + * @param job + * The modified Job whose attributed need to be updated. * @return The updated job. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.5.0 */ @PUT @Path("{jobId}") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public Job update( @PathParam("scopeId") ScopeId scopeId, @PathParam("jobId") EntityId jobId, @@ -208,10 +232,13 @@ public Job update( /** * Deletes the Job specified by the "jobId" path parameter. * - * @param scopeId The ScopeId of the requested {@link Job}. - * @param jobId The id of the Job to be deleted. + * @param scopeId + * The ScopeId of the requested {@link Job}. + * @param jobId + * The id of the Job to be deleted. * @return HTTP 201 if operation has completed successfully. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.5.0 */ @DELETE diff --git a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/Roles.java b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/Roles.java index a1e453f87ad..da9548fa296 100644 --- a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/Roles.java +++ b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/Roles.java @@ -13,6 +13,7 @@ package org.eclipse.kapua.app.api.resources.v1.resources; import java.util.List; + import javax.inject.Inject; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; @@ -27,7 +28,6 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -import com.google.common.base.Strings; import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.app.api.core.model.CountResult; import org.eclipse.kapua.app.api.core.model.EntityId; @@ -41,41 +41,42 @@ import org.eclipse.kapua.service.KapuaService; import org.eclipse.kapua.service.authorization.role.Role; import org.eclipse.kapua.service.authorization.role.RoleCreator; -import org.eclipse.kapua.service.authorization.role.RoleFactory; import org.eclipse.kapua.service.authorization.role.RoleListResult; import org.eclipse.kapua.service.authorization.role.RoleQuery; import org.eclipse.kapua.service.authorization.role.RoleService; import org.eclipse.kapua.service.user.User; -import org.eclipse.kapua.service.user.UserFactory; import org.eclipse.kapua.service.user.UserListResult; import org.eclipse.kapua.service.user.UserQuery; import org.eclipse.kapua.service.user.UserService; +import com.google.common.base.Strings; + @Path("{scopeId}/roles") public class Roles extends AbstractKapuaResource { @Inject public RoleService roleService; @Inject - public RoleFactory roleFactory; - @Inject public UserService userService; - @Inject - public UserFactory userFactory; /** * Gets the {@link Role} list in the scope. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param name The {@link Role} name in which to search results. - * @param offset The result set offset. - * @param limit The result set limit. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param name + * The {@link Role} name in which to search results. + * @param offset + * The result set offset. + * @param limit + * The result set limit. * @return The {@link RoleListResult} of all the roles associated to the current selected scope. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @GET - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public RoleListResult simpleQuery( @PathParam("scopeId") ScopeId scopeId, @QueryParam("name") String name, @@ -85,7 +86,7 @@ public RoleListResult simpleQuery( @QueryParam("sortDir") @DefaultValue("ASCENDING") SortOrder sortDir, @QueryParam("offset") @DefaultValue("0") int offset, @QueryParam("limit") @DefaultValue("50") int limit) throws KapuaException { - RoleQuery query = roleFactory.newQuery(scopeId); + RoleQuery query = new RoleQuery(scopeId); AndPredicate andPredicate = query.andPredicate(); if (!Strings.isNullOrEmpty(name)) { @@ -109,16 +110,19 @@ public RoleListResult simpleQuery( /** * Queries the results with the given {@link RoleQuery} parameter. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param query The {@link RoleQuery} to use to filter results. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param query + * The {@link RoleQuery} to use to filter results. * @return The {@link RoleListResult} of all the result matching the given {@link RoleQuery} parameter. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @POST @Path("_query") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public RoleListResult query( @PathParam("scopeId") ScopeId scopeId, RoleQuery query) throws KapuaException { @@ -130,16 +134,19 @@ public RoleListResult query( /** * Counts the results with the given {@link RoleQuery} parameter. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param query The {@link RoleQuery} to use to filter results. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param query + * The {@link RoleQuery} to use to filter results. * @return The count of all the result matching the given {@link RoleQuery} parameter. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @POST @Path("_count") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public CountResult count( @PathParam("scopeId") ScopeId scopeId, RoleQuery query) throws KapuaException { @@ -149,18 +156,20 @@ public CountResult count( } /** - * Creates a new Role based on the information provided in RoleCreator - * parameter. + * Creates a new Role based on the information provided in RoleCreator parameter. * - * @param scopeId The {@link ScopeId} in which to create the {@link Role} - * @param roleCreator Provides the information for the new {@link Role} to be created. + * @param scopeId + * The {@link ScopeId} in which to create the {@link Role} + * @param roleCreator + * Provides the information for the new {@link Role} to be created. * @return The newly created {@link Role} object. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @POST - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public Response create( @PathParam("scopeId") ScopeId scopeId, RoleCreator roleCreator) throws KapuaException { @@ -172,15 +181,18 @@ public Response create( /** * Returns the Role specified by the "roleId" path parameter. * - * @param scopeId The {@link ScopeId} of the requested {@link Role}. - * @param roleId The id of the requested {@link Role}. + * @param scopeId + * The {@link ScopeId} of the requested {@link Role}. + * @param roleId + * The id of the requested {@link Role}. * @return The requested {@link Role} object. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @GET @Path("{roleId}") - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public Role find( @PathParam("scopeId") ScopeId scopeId, @PathParam("roleId") EntityId roleId) throws KapuaException { @@ -192,17 +204,21 @@ public Role find( /** * Updates the Role based on the information provided in the Role parameter. * - * @param scopeId The ScopeId of the requested {@link Role}. - * @param roleId The id of the requested {@link Role} - * @param role The modified Role whose attributed need to be updated. + * @param scopeId + * The ScopeId of the requested {@link Role}. + * @param roleId + * The id of the requested {@link Role} + * @param role + * The modified Role whose attributed need to be updated. * @return The updated {@link Role}. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @PUT @Path("{roleId}") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public Role update( @PathParam("scopeId") ScopeId scopeId, @PathParam("roleId") EntityId roleId, @@ -216,10 +232,13 @@ public Role update( /** * Deletes the Role specified by the "roleId" path parameter. * - * @param scopeId The ScopeId of the requested {@link Role}. - * @param roleId The id of the Role to be deleted. + * @param scopeId + * The ScopeId of the requested {@link Role}. + * @param roleId + * The id of the Role to be deleted. * @return HTTP 200 if operation has completed successfully. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @DELETE @@ -235,14 +254,21 @@ public Response deleteRole( /** * Gets all the {@link User}s for a given {@link Role} * - * @param scopeId The ScopeId of the requested {@link Role}. - * @param roleId The id of the Role to be deleted. - * @param offset The result set offset. - * @param limit The result set limit. - * @param sortParam The name of the parameter that will be used as a sorting key for the users - * @param sortDir The sort direction. Can be ASCENDING (default), DESCENDING. Case-insensitive. + * @param scopeId + * The ScopeId of the requested {@link Role}. + * @param roleId + * The id of the Role to be deleted. + * @param offset + * The result set offset. + * @param limit + * The result set limit. + * @param sortParam + * The name of the parameter that will be used as a sorting key for the users + * @param sortDir + * The sort direction. Can be ASCENDING (default), DESCENDING. Case-insensitive. * @return An {@link UserListResult} containing the {@link User}s for the given {@link Role} - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.2.0 */ @GET @@ -256,7 +282,7 @@ public UserListResult usersForRole( @QueryParam("limit") @DefaultValue("50") int limit) throws KapuaException { List usersIds = roleService.userIdsByRoleId(scopeId, roleId); - UserQuery userQuery = userFactory.newQuery(scopeId); + UserQuery userQuery = new UserQuery(scopeId); userQuery.setPredicate(userQuery.attributePredicate(KapuaEntityAttributes.ENTITY_ID, usersIds)); userQuery.setLimit(limit); userQuery.setOffset(offset); diff --git a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/RolesPermissions.java b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/RolesPermissions.java index 04ad770ba77..af42c32c8bb 100644 --- a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/RolesPermissions.java +++ b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/RolesPermissions.java @@ -12,7 +12,19 @@ *******************************************************************************/ package org.eclipse.kapua.app.api.resources.v1.resources; -import com.google.common.base.Strings; +import javax.inject.Inject; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.DefaultValue; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.app.api.core.model.CountResult; import org.eclipse.kapua.app.api.core.model.EntityId; @@ -20,6 +32,7 @@ import org.eclipse.kapua.app.api.core.resources.AbstractKapuaResource; import org.eclipse.kapua.model.KapuaEntityAttributes; import org.eclipse.kapua.model.domain.Actions; +import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.model.query.SortOrder; import org.eclipse.kapua.model.query.predicate.AndPredicate; import org.eclipse.kapua.service.KapuaService; @@ -27,49 +40,43 @@ import org.eclipse.kapua.service.authorization.role.RolePermission; import org.eclipse.kapua.service.authorization.role.RolePermissionAttributes; import org.eclipse.kapua.service.authorization.role.RolePermissionCreator; -import org.eclipse.kapua.service.authorization.role.RolePermissionFactory; import org.eclipse.kapua.service.authorization.role.RolePermissionListResult; -import org.eclipse.kapua.service.authorization.role.RolePermissionQuery; import org.eclipse.kapua.service.authorization.role.RolePermissionService; -import javax.inject.Inject; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.DefaultValue; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; +import com.google.common.base.Strings; @Path("{scopeId}/roles/{roleId}/permissions") public class RolesPermissions extends AbstractKapuaResource { @Inject public RolePermissionService rolePermissionService; - @Inject - public RolePermissionFactory rolePermissionFactory; /** * Gets the {@link RolePermission} list in the scope. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param roleId The id of the {@link Role} in which to search results. - * @param domain The domain name to filter results. - * @param action The action to filter results. - * @param sortParam The name of the parameter that will be used as a sorting key - * @param sortDir The sort direction. Can be ASCENDING (default), DESCENDING. Case-insensitive. - * @param offset The result set offset. - * @param limit The result set limit. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param roleId + * The id of the {@link Role} in which to search results. + * @param domain + * The domain name to filter results. + * @param action + * The action to filter results. + * @param sortParam + * The name of the parameter that will be used as a sorting key + * @param sortDir + * The sort direction. Can be ASCENDING (default), DESCENDING. Case-insensitive. + * @param offset + * The result set offset. + * @param limit + * The result set limit. * @return The {@link RolePermissionListResult} of all the rolePermissions associated to the current selected scope. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @GET - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public RolePermissionListResult simpleQuery( @PathParam("scopeId") ScopeId scopeId, @PathParam("roleId") EntityId roleId, @@ -80,7 +87,7 @@ public RolePermissionListResult simpleQuery( @QueryParam("sortDir") @DefaultValue("ASCENDING") SortOrder sortDir, @QueryParam("offset") @DefaultValue("0") int offset, @QueryParam("limit") @DefaultValue("50") int limit) throws KapuaException { - RolePermissionQuery query = rolePermissionFactory.newQuery(scopeId); + KapuaQuery query = new KapuaQuery(scopeId); AndPredicate andPredicate = query.andPredicate(); query.setPredicate(query.attributePredicate(RolePermissionAttributes.ROLE_ID, roleId)); @@ -103,23 +110,27 @@ public RolePermissionListResult simpleQuery( } /** - * Queries the results with the given {@link RolePermissionQuery} parameter. + * Queries the results with the given {@link KapuaQuery} parameter. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param roleId The {@link Role} id in which to search results. - * @param query The {@link RolePermissionQuery} to use to filter results. - * @return The {@link RolePermissionListResult} of all the result matching the given {@link RolePermissionQuery} parameter. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param roleId + * The {@link Role} id in which to search results. + * @param query + * The {@link KapuaQuery} to use to filter results. + * @return The {@link RolePermissionListResult} of all the result matching the given {@link KapuaQuery} parameter. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @POST @Path("_query") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public RolePermissionListResult query( @PathParam("scopeId") ScopeId scopeId, @PathParam("roleId") EntityId roleId, - RolePermissionQuery query) throws KapuaException { + KapuaQuery query) throws KapuaException { query.setScopeId(scopeId); AndPredicate andPredicate = query.andPredicate(); @@ -133,23 +144,27 @@ public RolePermissionListResult query( } /** - * Counts the results with the given {@link RolePermissionQuery} parameter. + * Counts the results with the given {@link KapuaQuery} parameter. * - * @param scopeId The {@link ScopeId} in which to count results. - * @param roleId The {@link Role} id in which to count results. - * @param query The {@link RolePermissionQuery} to use to filter results. - * @return The count of all the result matching the given {@link RolePermissionQuery} parameter. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @param scopeId + * The {@link ScopeId} in which to count results. + * @param roleId + * The {@link Role} id in which to count results. + * @param query + * The {@link KapuaQuery} to use to filter results. + * @return The count of all the result matching the given {@link KapuaQuery} parameter. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @POST @Path("_count") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public CountResult count( @PathParam("scopeId") ScopeId scopeId, @PathParam("roleId") EntityId roleId, - RolePermissionQuery query) throws KapuaException { + KapuaQuery query) throws KapuaException { query.setScopeId(scopeId); query.setPredicate(query.attributePredicate(RolePermissionAttributes.ROLE_ID, roleId)); @@ -157,19 +172,22 @@ public CountResult count( } /** - * Creates a new RolePermission based on the information provided in RolePermissionCreator - * parameter. + * Creates a new RolePermission based on the information provided in RolePermissionCreator parameter. * - * @param scopeId The {@link ScopeId} in which to create the {@link RolePermission} - * @param roleId The {@link Role} id in which to create the RolePermission. - * @param rolePermissionCreator Provides the information for the new RolePermission to be created. + * @param scopeId + * The {@link ScopeId} in which to create the {@link RolePermission} + * @param roleId + * The {@link Role} id in which to create the RolePermission. + * @param rolePermissionCreator + * Provides the information for the new RolePermission to be created. * @return The newly created RolePermission object. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @POST - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public Response create( @PathParam("scopeId") ScopeId scopeId, @PathParam("roleId") EntityId roleId, @@ -183,21 +201,25 @@ public Response create( /** * Returns the RolePermission specified by the "rolePermissionId" path parameter. * - * @param scopeId The {@link ScopeId} of the requested {@link RolePermission}. - * @param roleId The {@link Role} id of the requested {@link RolePermission}. - * @param rolePermissionId The id of the requested RolePermission. + * @param scopeId + * The {@link ScopeId} of the requested {@link RolePermission}. + * @param roleId + * The {@link Role} id of the requested {@link RolePermission}. + * @param rolePermissionId + * The id of the requested RolePermission. * @return The requested RolePermission object. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @GET @Path("{rolePermissionId}") - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public RolePermission find( @PathParam("scopeId") ScopeId scopeId, @PathParam("roleId") EntityId roleId, @PathParam("rolePermissionId") EntityId rolePermissionId) throws KapuaException { - RolePermissionQuery query = rolePermissionFactory.newQuery(scopeId); + KapuaQuery query = new KapuaQuery(scopeId); AndPredicate andPredicate = query.andPredicate( query.attributePredicate(RolePermissionAttributes.ROLE_ID, roleId), @@ -216,11 +238,15 @@ public RolePermission find( /** * Deletes the RolePermission specified by the "rolePermissionId" path parameter. * - * @param scopeId The {@link ScopeId} of the {@link RolePermission} to delete. - * @param roleId The {@link Role} id of the {@link RolePermission} to delete. - * @param rolePermissionId The id of the RolePermission to be deleted. + * @param scopeId + * The {@link ScopeId} of the {@link RolePermission} to delete. + * @param roleId + * The {@link Role} id of the {@link RolePermission} to delete. + * @param rolePermissionId + * The id of the RolePermission to be deleted. * @return HTTP 200 if operation has completed successfully. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @DELETE diff --git a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/Tags.java b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/Tags.java index c09e9c34a17..bab1eb458f4 100644 --- a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/Tags.java +++ b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/Tags.java @@ -26,7 +26,6 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -import com.google.common.base.Strings; import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.app.api.core.model.CountResult; import org.eclipse.kapua.app.api.core.model.EntityId; @@ -38,33 +37,37 @@ import org.eclipse.kapua.service.KapuaService; import org.eclipse.kapua.service.tag.Tag; import org.eclipse.kapua.service.tag.TagCreator; -import org.eclipse.kapua.service.tag.TagFactory; import org.eclipse.kapua.service.tag.TagListResult; import org.eclipse.kapua.service.tag.TagQuery; import org.eclipse.kapua.service.tag.TagService; +import com.google.common.base.Strings; + @Path("{scopeId}/tags") public class Tags extends AbstractKapuaResource { @Inject public TagService tagService; - @Inject - public TagFactory tagFactory; /** * Gets the {@link Tag} list in the scope. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param name The {@link Tag} name to filter results - * @param offset The result set offset. - * @param limit The result set limit. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param name + * The {@link Tag} name to filter results + * @param offset + * The result set offset. + * @param limit + * The result set limit. * @return The {@link TagListResult} of all the tags associated to the current selected scope. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @GET - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public TagListResult simpleQuery( @PathParam("scopeId") ScopeId scopeId, @QueryParam("name") String name, @@ -74,7 +77,7 @@ public TagListResult simpleQuery( @QueryParam("sortDir") @DefaultValue("ASCENDING") SortOrder sortDir, @QueryParam("offset") @DefaultValue("0") int offset, @QueryParam("limit") @DefaultValue("50") int limit) throws KapuaException { - TagQuery query = tagFactory.newQuery(scopeId); + TagQuery query = new TagQuery(scopeId); AndPredicate andPredicate = query.andPredicate(); if (!Strings.isNullOrEmpty(name)) { @@ -98,17 +101,20 @@ public TagListResult simpleQuery( /** * Queries the results with the given {@link TagQuery} parameter. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param query The {@link TagQuery} to use to filter results. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param query + * The {@link TagQuery} to use to filter results. * @return The {@link TagListResult} of all the result matching the given {@link TagQuery} parameter. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @POST @Path("_query") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public TagListResult query( @PathParam("scopeId") ScopeId scopeId, TagQuery query) throws KapuaException { @@ -120,17 +126,20 @@ public TagListResult query( /** * Counts the results with the given {@link TagQuery} parameter. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param query The {@link TagQuery} to use to filter results. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param query + * The {@link TagQuery} to use to filter results. * @return The count of all the result matching the given {@link TagQuery} parameter. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @POST @Path("_count") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public CountResult count( @PathParam("scopeId") ScopeId scopeId, TagQuery query) throws KapuaException { @@ -140,19 +149,21 @@ public CountResult count( } /** - * Creates a new Tag based on the information provided in TagCreator - * parameter. + * Creates a new Tag based on the information provided in TagCreator parameter. * - * @param scopeId The {@link ScopeId} in which to create the {@link Tag} - * @param tagCreator Provides the information for the new {@link Tag} to be created. + * @param scopeId + * The {@link ScopeId} in which to create the {@link Tag} + * @param tagCreator + * Provides the information for the new {@link Tag} to be created. * @return The newly created {@link Tag} object. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @POST - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public Response create( @PathParam("scopeId") ScopeId scopeId, TagCreator tagCreator) throws KapuaException { @@ -164,39 +175,46 @@ public Response create( /** * Returns the Tag specified by the "tagId" path parameter. * - * @param scopeId The {@link ScopeId} of the requested {@link Tag}. - * @param tagId The id of the requested Tag. + * @param scopeId + * The {@link ScopeId} of the requested {@link Tag}. + * @param tagId + * The id of the requested Tag. * @return The requested Tag object. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @GET @Path("{tagId}") - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public Tag find( @PathParam("scopeId") ScopeId scopeId, @PathParam("tagId") EntityId tagId) throws KapuaException { Tag tag = tagService.find(scopeId, tagId); - return returnNotNullEntity(tag, Tag.TYPE, tagId); + return returnNotNullEntity(tag, "tag", tagId); } /** * Updates the Tag based on the information provided in the Tag parameter. * - * @param scopeId The ScopeId of the requested {@link Tag}. - * @param tagId The id of the requested {@link Tag} - * @param tag The modified Tag whose attributed need to be updated. + * @param scopeId + * The ScopeId of the requested {@link Tag}. + * @param tagId + * The id of the requested {@link Tag} + * @param tag + * The modified Tag whose attributed need to be updated. * @return The updated tag. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @PUT @Path("{tagId}") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public Tag update( @PathParam("scopeId") ScopeId scopeId, @PathParam("tagId") EntityId tagId, @@ -210,10 +228,13 @@ public Tag update( /** * Deletes the Tag specified by the "tagId" path parameter. * - * @param scopeId The ScopeId of the requested {@link Tag}. - * @param tagId The id of the Tag to be deleted. + * @param scopeId + * The ScopeId of the requested {@link Tag}. + * @param tagId + * The id of the Tag to be deleted. * @return HTTP 200 if operation has completed successfully. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ diff --git a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/UserMfa.java b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/UserMfa.java index 634d343fe61..e2d8090c5fd 100644 --- a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/UserMfa.java +++ b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/UserMfa.java @@ -12,16 +12,6 @@ *******************************************************************************/ package org.eclipse.kapua.app.api.resources.v1.resources; -import org.eclipse.kapua.KapuaEntityNotFoundException; -import org.eclipse.kapua.KapuaException; -import org.eclipse.kapua.app.api.core.resources.AbstractKapuaResource; -import org.eclipse.kapua.commons.security.KapuaSecurityUtils; -import org.eclipse.kapua.service.KapuaService; -import org.eclipse.kapua.service.authentication.credential.mfa.MfaOption; -import org.eclipse.kapua.service.authentication.credential.mfa.MfaOptionCreator; -import org.eclipse.kapua.service.authentication.credential.mfa.MfaOptionService; -import org.eclipse.kapua.service.authentication.credential.mfa.shiro.MfaOptionCreatorImpl; - import javax.inject.Inject; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; @@ -32,6 +22,15 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; +import org.eclipse.kapua.KapuaEntityNotFoundException; +import org.eclipse.kapua.KapuaException; +import org.eclipse.kapua.app.api.core.resources.AbstractKapuaResource; +import org.eclipse.kapua.commons.security.KapuaSecurityUtils; +import org.eclipse.kapua.service.KapuaService; +import org.eclipse.kapua.service.authentication.credential.mfa.MfaOption; +import org.eclipse.kapua.service.authentication.credential.mfa.MfaOptionCreator; +import org.eclipse.kapua.service.authentication.credential.mfa.MfaOptionService; + @Path("user") public class UserMfa extends AbstractKapuaResource { @@ -42,16 +41,17 @@ public class UserMfa extends AbstractKapuaResource { * Creates a new {@link MfaOption} for the user specified by the "userId" path parameter. * * @return The newly created {@link MfaOption} object. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 2.0.0 */ @POST @Path("mfa") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public Response activateMfa() throws KapuaException { - MfaOptionCreator mfaOptionCreator = new MfaOptionCreatorImpl(KapuaSecurityUtils.getSession().getScopeId()); + MfaOptionCreator mfaOptionCreator = new MfaOptionCreator(KapuaSecurityUtils.getSession().getScopeId()); mfaOptionCreator.setUserId(KapuaSecurityUtils.getSession().getUserId()); return returnCreated(KapuaSecurityUtils.doPrivileged(() -> mfaOptionService.create(mfaOptionCreator))); @@ -61,12 +61,13 @@ public Response activateMfa() throws KapuaException { * Returns the {@link MfaOption} of the user specified by the "userId" path parameter. * * @return The requested {@link MfaOption} object. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.4.0 */ @GET @Path("mfa") - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public MfaOption findMfa() throws KapuaException { MfaOption mfaOption = KapuaSecurityUtils.doPrivileged(() -> mfaOptionService.findByUserId(KapuaSecurityUtils.getSession().getScopeId(), KapuaSecurityUtils.getSession().getUserId())); if (mfaOption == null) { @@ -79,7 +80,8 @@ public MfaOption findMfa() throws KapuaException { * Deletes the {@link MfaOption} of the user specified by the "userId" path parameter. * * @return HTTP 200 if operation has completed successfully. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.4.0 */ @DELETE @@ -94,13 +96,14 @@ public Response deleteMfa() throws KapuaException { * Disable trusted machine for a given {@link MfaOption}. * * @return HTTP 200 if operation has completed successfully. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.4.0 */ @DELETE @Path("mfa/disableTrust") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public Response disableTrust() throws KapuaException { KapuaSecurityUtils.doPrivileged(() -> mfaOptionService.disableTrustByUserId(KapuaSecurityUtils.getSession().getScopeId(), KapuaSecurityUtils.getSession().getUserId())); return returnNoContent(); diff --git a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/Users.java b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/Users.java index 0da1215e9ce..597b6a0cdcd 100644 --- a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/Users.java +++ b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/Users.java @@ -12,7 +12,20 @@ *******************************************************************************/ package org.eclipse.kapua.app.api.resources.v1.resources; -import com.google.common.base.Strings; +import javax.inject.Inject; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.DefaultValue; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.app.api.core.model.CountResult; import org.eclipse.kapua.app.api.core.model.EntityId; @@ -29,19 +42,7 @@ import org.eclipse.kapua.service.user.UserQuery; import org.eclipse.kapua.service.user.UserService; -import javax.inject.Inject; -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.DefaultValue; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; +import com.google.common.base.Strings; @Path("{scopeId}/users") public class Users extends AbstractKapuaResource { @@ -54,20 +55,29 @@ public class Users extends AbstractKapuaResource { /** * Gets the {@link User} list in the scope. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param name The {@link User} name in which to search results. - * @param sortParam The name of the parameter that will be used as a sorting key - * @param sortDir The sort direction. Can be ASCENDING (default), DESCENDING. Case-insensitive. - * @param matchTerm A term to be matched in at least one of the configured fields of this entity - * @param askTotalCount Ask for the total count of the matched entities in the result - * @param offset The result set offset. - * @param limit The result set limit. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param name + * The {@link User} name in which to search results. + * @param sortParam + * The name of the parameter that will be used as a sorting key + * @param sortDir + * The sort direction. Can be ASCENDING (default), DESCENDING. Case-insensitive. + * @param matchTerm + * A term to be matched in at least one of the configured fields of this entity + * @param askTotalCount + * Ask for the total count of the matched entities in the result + * @param offset + * The result set offset. + * @param limit + * The result set limit. * @return The {@link UserListResult} of all the users associated to the current selected scope. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @GET - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public UserListResult simpleQuery( @PathParam("scopeId") ScopeId scopeId, @QueryParam("name") String name, @@ -77,7 +87,7 @@ public UserListResult simpleQuery( @QueryParam("askTotalCount") boolean askTotalCount, @QueryParam("offset") @DefaultValue("0") int offset, @QueryParam("limit") @DefaultValue("50") int limit) throws KapuaException { - UserQuery query = userFactory.newQuery(scopeId); + UserQuery query = new UserQuery(scopeId); AndPredicate andPredicate = query.andPredicate(); if (!Strings.isNullOrEmpty(name)) { @@ -102,16 +112,19 @@ public UserListResult simpleQuery( /** * Queries the results with the given {@link UserQuery} parameter. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param query The {@link UserQuery} to use to filter results. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param query + * The {@link UserQuery} to use to filter results. * @return The {@link UserListResult} of all the result matching the given {@link UserQuery} parameter. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @POST @Path("_query") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public UserListResult query( @PathParam("scopeId") ScopeId scopeId, UserQuery query) throws KapuaException { @@ -123,16 +136,19 @@ public UserListResult query( /** * Counts the results with the given {@link UserQuery} parameter. * - * @param scopeId The {@link ScopeId} in which to count results. - * @param query The {@link UserQuery} to use to filter results. + * @param scopeId + * The {@link ScopeId} in which to count results. + * @param query + * The {@link UserQuery} to use to filter results. * @return The count of all the result matching the given {@link UserQuery} parameter. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @POST @Path("_count") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public CountResult count( @PathParam("scopeId") ScopeId scopeId, UserQuery query) throws KapuaException { @@ -142,18 +158,20 @@ public CountResult count( } /** - * Creates a new User based on the information provided in UserCreator - * parameter. + * Creates a new User based on the information provided in UserCreator parameter. * - * @param scopeId The {@link ScopeId} in which to create the {@link User} - * @param userCreator Provides the information for the new User to be created. + * @param scopeId + * The {@link ScopeId} in which to create the {@link User} + * @param userCreator + * Provides the information for the new User to be created. * @return The newly created User object. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @POST - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public Response create( @PathParam("scopeId") ScopeId scopeId, UserCreator userCreator) throws KapuaException { @@ -165,15 +183,18 @@ public Response create( /** * Returns the User specified by the "userId" path parameter. * - * @param scopeId The {@link ScopeId} of the requested {@link User}. - * @param userId The id of the requested User. + * @param scopeId + * The {@link ScopeId} of the requested {@link User}. + * @param userId + * The id of the requested User. * @return The requested User object. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @GET @Path("{userId}") - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public User find( @PathParam("scopeId") ScopeId scopeId, @PathParam("userId") EntityId userId) throws KapuaException { @@ -185,17 +206,21 @@ public User find( /** * Updates the User based on the information provided in the User parameter. * - * @param scopeId The ScopeId of the requested {@link User}. - * @param userId The id of the requested {@link User} - * @param user The modified User whose attributed need to be updated. + * @param scopeId + * The ScopeId of the requested {@link User}. + * @param userId + * The id of the requested {@link User} + * @param user + * The modified User whose attributed need to be updated. * @return The updated user. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @PUT @Path("{userId}") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public User update( @PathParam("scopeId") ScopeId scopeId, @PathParam("userId") EntityId userId, @@ -209,10 +234,13 @@ public User update( /** * Deletes the User specified by the "userId" path parameter. * - * @param scopeId The ScopeId of the requested {@link User}. - * @param userId The id of the User to be deleted. + * @param scopeId + * The ScopeId of the requested {@link User}. + * @param userId + * The id of the User to be deleted. * @return HTTP 200 if operation has completed successfully. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @DELETE diff --git a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/UsersCredentials.java b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/UsersCredentials.java index 3b3bc9d3597..4537e7df5a9 100644 --- a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/UsersCredentials.java +++ b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/UsersCredentials.java @@ -12,11 +12,24 @@ *******************************************************************************/ package org.eclipse.kapua.app.api.resources.v1.resources; +import javax.inject.Inject; +import javax.ws.rs.Consumes; +import javax.ws.rs.DefaultValue; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.app.api.core.model.CountResult; import org.eclipse.kapua.app.api.core.model.EntityId; import org.eclipse.kapua.app.api.core.model.ScopeId; import org.eclipse.kapua.app.api.core.resources.AbstractKapuaResource; +import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.model.query.predicate.AndPredicate; import org.eclipse.kapua.service.KapuaService; import org.eclipse.kapua.service.authentication.credential.Credential; @@ -24,22 +37,9 @@ import org.eclipse.kapua.service.authentication.credential.CredentialCreator; import org.eclipse.kapua.service.authentication.credential.CredentialFactory; import org.eclipse.kapua.service.authentication.credential.CredentialListResult; -import org.eclipse.kapua.service.authentication.credential.CredentialQuery; import org.eclipse.kapua.service.authentication.credential.CredentialService; import org.eclipse.kapua.service.authentication.user.PasswordResetRequest; -import javax.inject.Inject; -import javax.ws.rs.Consumes; -import javax.ws.rs.DefaultValue; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - /* @deprecated accidentally exposed under: @@ -59,22 +59,27 @@ public class UsersCredentials extends AbstractKapuaResource { /** * Gets the {@link Credential} list in the scope. * - * @param scopeId The {@link ScopeId} in which to search results. - * @param userId The {@link EntityId} for which search results. - * @param offset The result set offset. - * @param limit The result set limit. + * @param scopeId + * The {@link ScopeId} in which to search results. + * @param userId + * The {@link EntityId} for which search results. + * @param offset + * The result set offset. + * @param limit + * The result set limit. * @return The {@link CredentialListResult} of all the credentials associated to the current selected scope. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @GET - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public CredentialListResult getAll( @PathParam("scopeId") ScopeId scopeId, @PathParam("userId") EntityId userId, @QueryParam("offset") @DefaultValue("0") int offset, @QueryParam("limit") @DefaultValue("50") int limit) throws KapuaException { - CredentialQuery query = credentialFactory.newQuery(scopeId); + KapuaQuery query = new KapuaQuery(scopeId); AndPredicate andPredicate = query.andPredicate(); andPredicate.and(query.attributePredicate(CredentialAttributes.USER_ID, userId)); @@ -86,25 +91,28 @@ public CredentialListResult getAll( return credentialService.query(query); } - /** - * Counts the results with the given {@link CredentialQuery} parameter. + * Counts the results with the given {@link KapuaQuery} parameter. * - * @param scopeId The {@link ScopeId} in which to count results. - * @param userId The {@link EntityId} for which count results. - * @param query The {@link CredentialQuery} to use to filter results. - * @return The count of all the result matching the given {@link CredentialQuery} parameter. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @param scopeId + * The {@link ScopeId} in which to count results. + * @param userId + * The {@link EntityId} for which count results. + * @param query + * The {@link KapuaQuery} to use to filter results. + * @return The count of all the result matching the given {@link KapuaQuery} parameter. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @POST @Path("_count") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public CountResult count( @PathParam("scopeId") ScopeId scopeId, @PathParam("userId") EntityId userId, - CredentialQuery query) throws KapuaException { + KapuaQuery query) throws KapuaException { AndPredicate andPredicate = query.andPredicate(); andPredicate.and(query.attributePredicate(CredentialAttributes.USER_ID, userId)); query.setPredicate(andPredicate); @@ -112,21 +120,23 @@ public CountResult count( return new CountResult(credentialService.count(query)); } - /** - * Creates a new Credential based on the information provided in CredentialCreator - * parameter. + * Creates a new Credential based on the information provided in CredentialCreator parameter. * - * @param scopeId The {@link ScopeId} in which to create the {@link Credential}. - * @param userId The {@link EntityId} for which create the {@link Credential}. - * @param credentialCreator Provides the information for the new Credential to be created. + * @param scopeId + * The {@link ScopeId} in which to create the {@link Credential}. + * @param userId + * The {@link EntityId} for which create the {@link Credential}. + * @param credentialCreator + * Provides the information for the new Credential to be created. * @return The newly created Credential object. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.0.0 */ @POST - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public Response create( @PathParam("scopeId") ScopeId scopeId, @PathParam("userId") EntityId userId, @@ -140,11 +150,15 @@ public Response create( /** * Reset the password for the specific user * - * @param scopeId The {@link ScopeId} of the {@link Credential} to reset. - * @param userId The {@link EntityId} for which to reset the password credential. - * @param passwordResetRequest Request for resetting credential password + * @param scopeId + * The {@link ScopeId} of the {@link Credential} to reset. + * @param userId + * The {@link EntityId} for which to reset the password credential. + * @param passwordResetRequest + * Request for resetting credential password * @return The updated credential. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 2.0.0 * @deprecated since 2.0.0 - use POST POST /{scopeId}/users/{userId}/password/_reset instead (see {@link UsersCredentials}) */ diff --git a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/UsersMfa.java b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/UsersMfa.java index 2129f3da467..51fe584d0ba 100644 --- a/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/UsersMfa.java +++ b/rest-api/resources/src/main/java/org/eclipse/kapua/app/api/resources/v1/resources/UsersMfa.java @@ -12,16 +12,6 @@ *******************************************************************************/ package org.eclipse.kapua.app.api.resources.v1.resources; -import org.eclipse.kapua.KapuaEntityNotFoundException; -import org.eclipse.kapua.KapuaException; -import org.eclipse.kapua.app.api.core.model.EntityId; -import org.eclipse.kapua.app.api.core.model.ScopeId; -import org.eclipse.kapua.app.api.core.resources.AbstractKapuaResource; -import org.eclipse.kapua.service.KapuaService; -import org.eclipse.kapua.service.authentication.credential.mfa.MfaOption; -import org.eclipse.kapua.service.authentication.credential.mfa.MfaOptionService; -import org.eclipse.kapua.service.authentication.credential.mfa.shiro.MfaOptionCreatorImpl; - import javax.inject.Inject; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; @@ -33,6 +23,16 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; +import org.eclipse.kapua.KapuaEntityNotFoundException; +import org.eclipse.kapua.KapuaException; +import org.eclipse.kapua.app.api.core.model.EntityId; +import org.eclipse.kapua.app.api.core.model.ScopeId; +import org.eclipse.kapua.app.api.core.resources.AbstractKapuaResource; +import org.eclipse.kapua.service.KapuaService; +import org.eclipse.kapua.service.authentication.credential.mfa.MfaOption; +import org.eclipse.kapua.service.authentication.credential.mfa.MfaOptionCreator; +import org.eclipse.kapua.service.authentication.credential.mfa.MfaOptionService; + @Path("{scopeId}/users") public class UsersMfa extends AbstractKapuaResource { @@ -42,36 +42,42 @@ public class UsersMfa extends AbstractKapuaResource { /** * Creates a new {@link MfaOption} for the user specified by the "userId" path parameter. * - * @param scopeId The {@link ScopeId} in which to create the {@link MfaOption} - * @param userId The {@link EntityId} of the User to which the {@link MfaOption} belongs + * @param scopeId + * The {@link ScopeId} in which to create the {@link MfaOption} + * @param userId + * The {@link EntityId} of the User to which the {@link MfaOption} belongs * @return The newly created {@link MfaOption} object. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.4.0 * @deprecated since 2.0.0 - use POST {scopeId}/user/mfa instead (see {@link UserMfa}) */ @POST @Path("{userId}/mfa") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) @Deprecated public Response createMfa( @PathParam("scopeId") ScopeId scopeId, @PathParam("userId") EntityId userId) throws KapuaException { - return returnCreated(mfaOptionService.create(new MfaOptionCreatorImpl(scopeId, userId))); + return returnCreated(mfaOptionService.create(new MfaOptionCreator(scopeId, userId))); } /** * Returns the {@link MfaOption} of the user specified by the "userId" path parameter. * - * @param scopeId The {@link ScopeId} of the requested {@link MfaOption} - * @param userId The {@link EntityId} of the User to which the {@link MfaOption} belongs + * @param scopeId + * The {@link ScopeId} of the requested {@link MfaOption} + * @param userId + * The {@link EntityId} of the User to which the {@link MfaOption} belongs * @return The requested {@link MfaOption} object. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.4.0 */ @GET @Path("{userId}/mfa") - @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) + @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) public MfaOption findMfa( @PathParam("scopeId") ScopeId scopeId, @PathParam("userId") EntityId userId) throws KapuaException { @@ -86,10 +92,13 @@ public MfaOption findMfa( /** * Deletes the {@link MfaOption} of the user specified by the "userId" path parameter. * - * @param scopeId The {@link ScopeId} of the requested {@link MfaOption} - * @param userId The {@link EntityId} of the User to which the {@link MfaOption} belongs + * @param scopeId + * The {@link ScopeId} of the requested {@link MfaOption} + * @param userId + * The {@link EntityId} of the User to which the {@link MfaOption} belongs * @return HTTP 200 if operation has completed successfully. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.4.0 */ @DELETE @@ -105,16 +114,19 @@ public Response deleteMfa( /** * Disable trusted machine for a given {@link MfaOption}. * - * @param scopeId The ScopeId of the requested {@link MfaOption}. - * @param userId The {@link EntityId} of the User to which the {@link MfaOption} belongs + * @param scopeId + * The ScopeId of the requested {@link MfaOption}. + * @param userId + * The {@link EntityId} of the User to which the {@link MfaOption} belongs * @return HTTP 200 if operation has completed successfully. - * @throws KapuaException Whenever something bad happens. See specific {@link KapuaService} exceptions. + * @throws KapuaException + * Whenever something bad happens. See specific {@link KapuaService} exceptions. * @since 1.4.0 */ @DELETE @Path("{userId}/mfa/disableTrust") - @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) - @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) + @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) + @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public Response disableTrust( @PathParam("scopeId") ScopeId scopeId, @PathParam("userId") EntityId userId) throws KapuaException { diff --git a/rest-api/resources/src/main/resources/openapi/openapi.yaml b/rest-api/resources/src/main/resources/openapi/openapi.yaml index d45ca00e92b..148e9fd289b 100644 --- a/rest-api/resources/src/main/resources/openapi/openapi.yaml +++ b/rest-api/resources/src/main/resources/openapi/openapi.yaml @@ -2,7 +2,7 @@ openapi: 3.0.3 info: title: Eclipse Kapua REST API - version: '2.1.0-SNAPSHOT' + version: '2.1.0-FALSE_EXTENSIONS-SNAPSHOT' contact: name: Eclipse Kapua Dev Team url: https://eclipse.org/kapua diff --git a/rest-api/web/pom.xml b/rest-api/web/pom.xml index d7a5ca98888..9760c5859b8 100644 --- a/rest-api/web/pom.xml +++ b/rest-api/web/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-rest-api - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-rest-api-web diff --git a/rest-api/web/src/main/java/org/eclipse/kapua/app/api/web/AppModule.java b/rest-api/web/src/main/java/org/eclipse/kapua/app/api/web/AppModule.java index 37b459293ca..a6e556309ee 100644 --- a/rest-api/web/src/main/java/org/eclipse/kapua/app/api/web/AppModule.java +++ b/rest-api/web/src/main/java/org/eclipse/kapua/app/api/web/AppModule.java @@ -36,11 +36,10 @@ import org.eclipse.kapua.locator.LocatorConfig; import org.eclipse.kapua.service.account.AccountService; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; +import org.eclipse.kapua.service.scheduler.trigger.definition.quartz.TriggerDefinitionAligner; import com.google.inject.Provides; import com.google.inject.multibindings.ProvidesIntoSet; -import org.eclipse.kapua.service.scheduler.trigger.definition.quartz.TriggerDefinitionAligner; public class AppModule extends AbstractKapuaModule { @@ -60,8 +59,8 @@ protected void configureModule() { @Singleton ServiceConfigurationsFacade serviceConfigurationsFacade( Map, ServiceConfigurationManager> serviceConfigurationManagersByServiceClass, AuthorizationService authorizationService, - PermissionFactory permissionFactory, AccountService accountService) { - return new ServiceConfigurationsFacadeImpl(serviceConfigurationManagersByServiceClass, authorizationService, permissionFactory, accountService); + AccountService accountService) { + return new ServiceConfigurationsFacadeImpl(serviceConfigurationManagersByServiceClass, authorizationService, accountService); } @ProvidesIntoSet diff --git a/rest-api/web/src/main/java/org/eclipse/kapua/app/api/web/RestApiJAXBContextProvider.java b/rest-api/web/src/main/java/org/eclipse/kapua/app/api/web/RestApiJAXBContextProvider.java index 2bcc3851d41..7cded9b0004 100644 --- a/rest-api/web/src/main/java/org/eclipse/kapua/app/api/web/RestApiJAXBContextProvider.java +++ b/rest-api/web/src/main/java/org/eclipse/kapua/app/api/web/RestApiJAXBContextProvider.java @@ -64,15 +64,12 @@ import org.eclipse.kapua.commons.service.event.store.api.EventStoreRecordCreator; import org.eclipse.kapua.commons.service.event.store.api.EventStoreRecordListResult; import org.eclipse.kapua.commons.service.event.store.api.EventStoreRecordQuery; -import org.eclipse.kapua.commons.service.event.store.api.EventStoreXmlRegistry; import org.eclipse.kapua.commons.util.xml.JAXBContextProvider; import org.eclipse.kapua.event.ServiceEvent; -import org.eclipse.kapua.job.engine.JobEngineXmlRegistry; import org.eclipse.kapua.job.engine.JobStartOptions; import org.eclipse.kapua.message.device.data.KapuaDataChannel; import org.eclipse.kapua.message.device.data.KapuaDataMessage; import org.eclipse.kapua.message.device.data.KapuaDataPayload; -import org.eclipse.kapua.message.xml.MessageXmlRegistry; import org.eclipse.kapua.model.config.metatype.KapuaTad; import org.eclipse.kapua.model.config.metatype.KapuaTicon; import org.eclipse.kapua.model.config.metatype.KapuaTmetadata; @@ -81,60 +78,42 @@ import org.eclipse.kapua.service.account.Account; import org.eclipse.kapua.service.account.AccountCreator; import org.eclipse.kapua.service.account.AccountListResult; -import org.eclipse.kapua.service.account.AccountQuery; import org.eclipse.kapua.service.account.AccountUpdateRequest; import org.eclipse.kapua.service.account.CurrentAccountUpdateRequest; import org.eclipse.kapua.service.account.xml.AccountParentPathXmlAdapter; -import org.eclipse.kapua.service.account.xml.AccountXmlRegistry; import org.eclipse.kapua.service.authentication.ApiKeyCredentials; import org.eclipse.kapua.service.authentication.AuthenticationCredentials; -import org.eclipse.kapua.service.authentication.AuthenticationXmlRegistry; import org.eclipse.kapua.service.authentication.JwtCredentials; import org.eclipse.kapua.service.authentication.RefreshTokenCredentials; import org.eclipse.kapua.service.authentication.UsernamePasswordCredentials; import org.eclipse.kapua.service.authentication.credential.Credential; import org.eclipse.kapua.service.authentication.credential.CredentialCreator; import org.eclipse.kapua.service.authentication.credential.CredentialListResult; -import org.eclipse.kapua.service.authentication.credential.CredentialQuery; import org.eclipse.kapua.service.authentication.credential.CredentialType; -import org.eclipse.kapua.service.authentication.credential.CredentialXmlRegistry; import org.eclipse.kapua.service.authentication.credential.mfa.MfaOption; import org.eclipse.kapua.service.authentication.credential.mfa.MfaOptionCreator; import org.eclipse.kapua.service.authentication.credential.mfa.MfaOptionListResult; -import org.eclipse.kapua.service.authentication.credential.mfa.MfaOptionQuery; -import org.eclipse.kapua.service.authentication.credential.mfa.MfaOptionXmlRegistry; import org.eclipse.kapua.service.authentication.credential.mfa.ScratchCode; import org.eclipse.kapua.service.authentication.credential.mfa.ScratchCodeListResult; -import org.eclipse.kapua.service.authentication.credential.mfa.ScratchCodeXmlRegistry; import org.eclipse.kapua.service.authentication.token.AccessToken; import org.eclipse.kapua.service.authentication.token.LoginInfo; import org.eclipse.kapua.service.authentication.user.PasswordChangeRequest; import org.eclipse.kapua.service.authentication.user.PasswordResetRequest; -import org.eclipse.kapua.service.authentication.user.UserCredentialsXmlRegistry; import org.eclipse.kapua.service.authorization.access.AccessInfo; import org.eclipse.kapua.service.authorization.access.AccessInfoCreator; import org.eclipse.kapua.service.authorization.access.AccessInfoListResult; -import org.eclipse.kapua.service.authorization.access.AccessInfoQuery; -import org.eclipse.kapua.service.authorization.access.AccessInfoXmlRegistry; import org.eclipse.kapua.service.authorization.access.AccessPermission; import org.eclipse.kapua.service.authorization.access.AccessPermissionCreator; import org.eclipse.kapua.service.authorization.access.AccessPermissionListResult; -import org.eclipse.kapua.service.authorization.access.AccessPermissionQuery; -import org.eclipse.kapua.service.authorization.access.AccessPermissionXmlRegistry; import org.eclipse.kapua.service.authorization.access.AccessRole; import org.eclipse.kapua.service.authorization.access.AccessRoleCreator; import org.eclipse.kapua.service.authorization.access.AccessRoleListResult; -import org.eclipse.kapua.service.authorization.access.AccessRoleQuery; -import org.eclipse.kapua.service.authorization.access.AccessRoleXmlRegistry; import org.eclipse.kapua.service.authorization.domain.Domain; import org.eclipse.kapua.service.authorization.domain.DomainListResult; -import org.eclipse.kapua.service.authorization.domain.DomainQuery; -import org.eclipse.kapua.service.authorization.domain.DomainXmlRegistry; import org.eclipse.kapua.service.authorization.group.Group; import org.eclipse.kapua.service.authorization.group.GroupCreator; import org.eclipse.kapua.service.authorization.group.GroupListResult; import org.eclipse.kapua.service.authorization.group.GroupQuery; -import org.eclipse.kapua.service.authorization.group.GroupXmlRegistry; import org.eclipse.kapua.service.authorization.permission.Permission; import org.eclipse.kapua.service.authorization.role.Role; import org.eclipse.kapua.service.authorization.role.RoleCreator; @@ -142,10 +121,7 @@ import org.eclipse.kapua.service.authorization.role.RolePermission; import org.eclipse.kapua.service.authorization.role.RolePermissionCreator; import org.eclipse.kapua.service.authorization.role.RolePermissionListResult; -import org.eclipse.kapua.service.authorization.role.RolePermissionQuery; -import org.eclipse.kapua.service.authorization.role.RolePermissionXmlRegistry; import org.eclipse.kapua.service.authorization.role.RoleQuery; -import org.eclipse.kapua.service.authorization.role.RoleXmlRegistry; import org.eclipse.kapua.service.config.ServiceComponentConfiguration; import org.eclipse.kapua.service.config.ServiceConfiguration; import org.eclipse.kapua.service.datastore.model.ChannelInfo; @@ -160,10 +136,6 @@ import org.eclipse.kapua.service.datastore.model.query.ClientInfoQuery; import org.eclipse.kapua.service.datastore.model.query.MessageQuery; import org.eclipse.kapua.service.datastore.model.query.MetricInfoQuery; -import org.eclipse.kapua.service.datastore.model.xml.ChannelInfoXmlRegistry; -import org.eclipse.kapua.service.datastore.model.xml.ClientInfoXmlRegistry; -import org.eclipse.kapua.service.datastore.model.xml.DatastoreMessageXmlRegistry; -import org.eclipse.kapua.service.datastore.model.xml.MetricInfoXmlRegistry; import org.eclipse.kapua.service.device.call.kura.model.bundle.KuraBundles; import org.eclipse.kapua.service.device.call.kura.model.configuration.KuraDeviceConfiguration; import org.eclipse.kapua.service.device.call.kura.model.deploy.KuraDeploymentPackage; @@ -179,18 +151,14 @@ import org.eclipse.kapua.service.device.call.kura.model.inventory.system.KuraInventorySystemPackage; import org.eclipse.kapua.service.device.call.kura.model.inventory.system.KuraInventorySystemPackages; import org.eclipse.kapua.service.device.call.kura.model.snapshot.KuraSnapshotIds; -import org.eclipse.kapua.service.device.management.asset.DeviceAssetXmlRegistry; import org.eclipse.kapua.service.device.management.asset.DeviceAssets; import org.eclipse.kapua.service.device.management.asset.store.settings.DeviceAssetStoreSettings; import org.eclipse.kapua.service.device.management.bundle.DeviceBundle; -import org.eclipse.kapua.service.device.management.bundle.DeviceBundleXmlRegistry; import org.eclipse.kapua.service.device.management.bundle.DeviceBundles; import org.eclipse.kapua.service.device.management.command.DeviceCommandInput; import org.eclipse.kapua.service.device.management.command.DeviceCommandOutput; -import org.eclipse.kapua.service.device.management.command.DeviceCommandXmlRegistry; import org.eclipse.kapua.service.device.management.configuration.DeviceComponentConfiguration; import org.eclipse.kapua.service.device.management.configuration.DeviceConfiguration; -import org.eclipse.kapua.service.device.management.configuration.DeviceConfigurationXmlRegistry; import org.eclipse.kapua.service.device.management.configuration.store.settings.DeviceConfigurationStoreSettings; import org.eclipse.kapua.service.device.management.inventory.model.bundle.DeviceInventoryBundle; import org.eclipse.kapua.service.device.management.inventory.model.bundle.DeviceInventoryBundles; @@ -198,7 +166,6 @@ import org.eclipse.kapua.service.device.management.inventory.model.container.DeviceInventoryContainers; import org.eclipse.kapua.service.device.management.inventory.model.inventory.DeviceInventory; import org.eclipse.kapua.service.device.management.inventory.model.inventory.DeviceInventoryItem; -import org.eclipse.kapua.service.device.management.inventory.model.inventory.DeviceInventoryXmlRegistry; import org.eclipse.kapua.service.device.management.inventory.model.packages.DeviceInventoryPackage; import org.eclipse.kapua.service.device.management.inventory.model.packages.DeviceInventoryPackages; import org.eclipse.kapua.service.device.management.inventory.model.system.DeviceInventorySystemPackage; @@ -211,19 +178,16 @@ import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystoreItemQuery; import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystoreItems; import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystoreKeypair; -import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystoreXmlRegistry; import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystores; import org.eclipse.kapua.service.device.management.message.notification.NotifyStatus; import org.eclipse.kapua.service.device.management.message.request.KapuaRequestChannel; import org.eclipse.kapua.service.device.management.message.request.KapuaRequestMessage; import org.eclipse.kapua.service.device.management.message.request.KapuaRequestPayload; -import org.eclipse.kapua.service.device.management.message.request.xml.RequestMessageXmlRegistry; import org.eclipse.kapua.service.device.management.message.response.KapuaResponseChannel; import org.eclipse.kapua.service.device.management.message.response.KapuaResponseMessage; import org.eclipse.kapua.service.device.management.packages.model.DevicePackage; import org.eclipse.kapua.service.device.management.packages.model.DevicePackageBundleInfo; import org.eclipse.kapua.service.device.management.packages.model.DevicePackageBundleInfos; -import org.eclipse.kapua.service.device.management.packages.model.DevicePackageXmlRegistry; import org.eclipse.kapua.service.device.management.packages.model.DevicePackages; import org.eclipse.kapua.service.device.management.packages.model.download.DevicePackageDownloadOperation; import org.eclipse.kapua.service.device.management.packages.model.download.DevicePackageDownloadRequest; @@ -235,13 +199,10 @@ import org.eclipse.kapua.service.device.management.registry.operation.DeviceManagementOperationCreator; import org.eclipse.kapua.service.device.management.registry.operation.DeviceManagementOperationListResult; import org.eclipse.kapua.service.device.management.registry.operation.DeviceManagementOperationQuery; -import org.eclipse.kapua.service.device.management.registry.operation.DeviceManagementOperationXmlRegistry; import org.eclipse.kapua.service.device.management.registry.operation.notification.ManagementOperationNotification; import org.eclipse.kapua.service.device.management.registry.operation.notification.ManagementOperationNotificationCreator; import org.eclipse.kapua.service.device.management.registry.operation.notification.ManagementOperationNotificationListResult; import org.eclipse.kapua.service.device.management.registry.operation.notification.ManagementOperationNotificationQuery; -import org.eclipse.kapua.service.device.management.registry.operation.notification.ManagementOperationNotificationXmlRegistry; -import org.eclipse.kapua.service.device.management.request.GenericRequestXmlRegistry; import org.eclipse.kapua.service.device.management.request.message.request.GenericRequestChannel; import org.eclipse.kapua.service.device.management.request.message.request.GenericRequestMessage; import org.eclipse.kapua.service.device.management.request.message.request.GenericRequestPayload; @@ -249,43 +210,33 @@ import org.eclipse.kapua.service.device.management.request.message.response.GenericResponseMessage; import org.eclipse.kapua.service.device.management.request.message.response.GenericResponsePayload; import org.eclipse.kapua.service.device.management.snapshot.DeviceSnapshot; -import org.eclipse.kapua.service.device.management.snapshot.DeviceSnapshotXmlRegistry; import org.eclipse.kapua.service.device.management.snapshot.DeviceSnapshots; import org.eclipse.kapua.service.device.registry.Device; import org.eclipse.kapua.service.device.registry.DeviceCreator; import org.eclipse.kapua.service.device.registry.DeviceListResult; import org.eclipse.kapua.service.device.registry.DeviceQuery; -import org.eclipse.kapua.service.device.registry.DeviceXmlRegistry; import org.eclipse.kapua.service.device.registry.connection.DeviceConnection; import org.eclipse.kapua.service.device.registry.connection.DeviceConnectionListResult; import org.eclipse.kapua.service.device.registry.connection.DeviceConnectionQuery; -import org.eclipse.kapua.service.device.registry.connection.DeviceConnectionXmlRegistry; import org.eclipse.kapua.service.device.registry.connection.option.DeviceConnectionOption; -import org.eclipse.kapua.service.device.registry.connection.option.DeviceConnectionOptionXmlRegistry; import org.eclipse.kapua.service.device.registry.event.DeviceEvent; import org.eclipse.kapua.service.device.registry.event.DeviceEventListResult; import org.eclipse.kapua.service.device.registry.event.DeviceEventQuery; -import org.eclipse.kapua.service.device.registry.event.DeviceEventXmlRegistry; import org.eclipse.kapua.service.endpoint.EndpointInfo; import org.eclipse.kapua.service.endpoint.EndpointInfoCreator; import org.eclipse.kapua.service.endpoint.EndpointInfoListResult; import org.eclipse.kapua.service.endpoint.EndpointInfoQuery; -import org.eclipse.kapua.service.endpoint.EndpointInfoXmlRegistry; import org.eclipse.kapua.service.endpoint.EndpointUsage; import org.eclipse.kapua.service.job.Job; import org.eclipse.kapua.service.job.JobCreator; import org.eclipse.kapua.service.job.JobListResult; import org.eclipse.kapua.service.job.JobQuery; -import org.eclipse.kapua.service.job.JobXmlRegistry; import org.eclipse.kapua.service.job.execution.JobExecution; import org.eclipse.kapua.service.job.execution.JobExecutionListResult; import org.eclipse.kapua.service.job.execution.JobExecutionQuery; -import org.eclipse.kapua.service.job.execution.JobExecutionXmlRegistry; import org.eclipse.kapua.service.job.step.JobStep; import org.eclipse.kapua.service.job.step.JobStepCreator; import org.eclipse.kapua.service.job.step.JobStepListResult; -import org.eclipse.kapua.service.job.step.JobStepQuery; -import org.eclipse.kapua.service.job.step.JobStepXmlRegistry; import org.eclipse.kapua.service.job.step.definition.JobStepDefinition; import org.eclipse.kapua.service.job.step.definition.JobStepDefinitionListResult; import org.eclipse.kapua.service.job.step.definition.JobStepDefinitionQuery; @@ -294,40 +245,30 @@ import org.eclipse.kapua.service.job.targets.JobTarget; import org.eclipse.kapua.service.job.targets.JobTargetCreator; import org.eclipse.kapua.service.job.targets.JobTargetListResult; -import org.eclipse.kapua.service.job.targets.JobTargetQuery; import org.eclipse.kapua.service.scheduler.trigger.Trigger; import org.eclipse.kapua.service.scheduler.trigger.TriggerCreator; import org.eclipse.kapua.service.scheduler.trigger.TriggerListResult; -import org.eclipse.kapua.service.scheduler.trigger.TriggerQuery; -import org.eclipse.kapua.service.scheduler.trigger.TriggerXmlRegistry; import org.eclipse.kapua.service.scheduler.trigger.definition.TriggerDefinition; import org.eclipse.kapua.service.scheduler.trigger.definition.TriggerDefinitionListResult; import org.eclipse.kapua.service.scheduler.trigger.definition.TriggerDefinitionQuery; -import org.eclipse.kapua.service.scheduler.trigger.definition.TriggerDefinitionXmlRegistry; import org.eclipse.kapua.service.scheduler.trigger.definition.TriggerProperty; import org.eclipse.kapua.service.scheduler.trigger.fired.FiredTrigger; import org.eclipse.kapua.service.scheduler.trigger.fired.FiredTriggerListResult; -import org.eclipse.kapua.service.scheduler.trigger.fired.FiredTriggerQuery; -import org.eclipse.kapua.service.scheduler.trigger.fired.FiredTriggerXmlRegistry; import org.eclipse.kapua.service.storable.model.id.StorableId; import org.eclipse.kapua.service.storable.model.query.SortField; import org.eclipse.kapua.service.storable.model.query.SortFieldXmlAdapter; import org.eclipse.kapua.service.storable.model.query.XmlAdaptedSortField; import org.eclipse.kapua.service.storable.model.query.XmlAdaptedSortFields; import org.eclipse.kapua.service.systeminfo.SystemInfo; -import org.eclipse.kapua.service.systeminfo.SystemInfoXmlRegistry; import org.eclipse.kapua.service.tag.Tag; import org.eclipse.kapua.service.tag.TagCreator; import org.eclipse.kapua.service.tag.TagListResult; import org.eclipse.kapua.service.tag.TagQuery; -import org.eclipse.kapua.service.tag.TagXmlRegistry; import org.eclipse.kapua.service.user.User; import org.eclipse.kapua.service.user.UserCreator; import org.eclipse.kapua.service.user.UserListResult; import org.eclipse.kapua.service.user.UserQuery; -import org.eclipse.kapua.service.user.UserXmlRegistry; import org.eclipse.kapua.service.user.profile.UserProfile; -import org.eclipse.kapua.service.user.profile.UserProfileXmlRegistry; import org.eclipse.persistence.jaxb.JAXBContextFactory; import org.eclipse.persistence.jaxb.MarshallerProperties; @@ -409,27 +350,22 @@ public JAXBContext getJAXBContext() throws KapuaException { Account.class, AccountCreator.class, AccountListResult.class, - AccountQuery.class, AccountParentPathXmlAdapter.class, - AccountXmlRegistry.class, // Data Channel Info ChannelInfo.class, ChannelInfoListResult.class, ChannelInfoQuery.class, - ChannelInfoXmlRegistry.class, // Data Client Info ClientInfo.class, ClientInfoListResult.class, ClientInfoQuery.class, - ClientInfoXmlRegistry.class, // Data Metric Info MetricInfo.class, MetricInfoListResult.class, MetricInfoQuery.class, - MetricInfoXmlRegistry.class, // Data Messages KapuaDataMessage.class, @@ -438,13 +374,11 @@ public JAXBContext getJAXBContext() throws KapuaException { MessageListResult.class, MessageQuery.class, - MessageXmlRegistry.class, JsonKapuaPayload.class, JsonDatastoreMessage.class, DatastoreMessage.class, - DatastoreMessageXmlRegistry.class, StorableEntityId.class, StorableId.class, SortField.class, @@ -458,46 +392,38 @@ public JAXBContext getJAXBContext() throws KapuaException { DeviceCreator.class, DeviceListResult.class, DeviceQuery.class, - DeviceXmlRegistry.class, // Device Connection DeviceConnection.class, DeviceConnectionListResult.class, DeviceConnectionQuery.class, - DeviceConnectionXmlRegistry.class, // Device Connection Options DeviceConnectionOption.class, - DeviceConnectionOptionXmlRegistry.class, // Device Event DeviceEvent.class, DeviceEventListResult.class, DeviceEventQuery.class, - DeviceEventXmlRegistry.class, // Device Management Assets DeviceAssets.class, DeviceAssetStoreSettings.class, - DeviceAssetXmlRegistry.class, // Device Management Bundles KuraBundles.class, DeviceBundle.class, DeviceBundles.class, - DeviceBundleXmlRegistry.class, // Device Management Command DeviceCommandInput.class, DeviceCommandOutput.class, - DeviceCommandXmlRegistry.class, // Device Management Configuration KuraDeviceConfiguration.class, DeviceConfiguration.class, DeviceComponentConfiguration.class, DeviceConfigurationStoreSettings.class, - DeviceConfigurationXmlRegistry.class, // Device Management Inventory DeviceInventory.class, @@ -520,7 +446,6 @@ public JAXBContext getJAXBContext() throws KapuaException { DeviceInventorySystemPackage.class, KuraInventorySystemPackages.class, KuraInventorySystemPackage.class, - DeviceInventoryXmlRegistry.class, // Device Management Keystore DeviceKeystores.class, @@ -534,13 +459,11 @@ public JAXBContext getJAXBContext() throws KapuaException { DeviceKeystoreKeypair.class, DeviceKeystoreCSRInfo.class, DeviceKeystoreCSR.class, - DeviceKeystoreXmlRegistry.class, // Device Management Snapshots KuraSnapshotIds.class, DeviceSnapshot.class, DeviceSnapshots.class, - DeviceSnapshotXmlRegistry.class, // Device Management Packages KuraDeploymentPackages.class, @@ -555,7 +478,6 @@ public JAXBContext getJAXBContext() throws KapuaException { DevicePackageInstallOperation.class, DevicePackageUninstallRequest.class, DevicePackageUninstallOperation.class, - DevicePackageXmlRegistry.class, // Device Management Requests KapuaRequestMessage.class, @@ -563,14 +485,12 @@ public JAXBContext getJAXBContext() throws KapuaException { KapuaRequestChannel.class, KapuaResponseChannel.class, KapuaRequestPayload.class, - RequestMessageXmlRegistry.class, // Device Management Registry DeviceManagementOperation.class, DeviceManagementOperationCreator.class, DeviceManagementOperationListResult.class, DeviceManagementOperationQuery.class, - DeviceManagementOperationXmlRegistry.class, NotifyStatus.class, // Device Management Registry Notification @@ -578,7 +498,6 @@ public JAXBContext getJAXBContext() throws KapuaException { ManagementOperationNotificationCreator.class, ManagementOperationNotificationListResult.class, ManagementOperationNotificationQuery.class, - ManagementOperationNotificationXmlRegistry.class, // Device Management Generic Request GenericRequestChannel.class, @@ -587,14 +506,12 @@ public JAXBContext getJAXBContext() throws KapuaException { GenericResponseChannel.class, GenericResponsePayload.class, GenericResponseMessage.class, - GenericRequestXmlRegistry.class, JsonGenericRequestMessage.class, JsonGenericResponseMessage.class, // Authentication AuthenticationCredentials.class, - AuthenticationXmlRegistry.class, AccessToken.class, LoginInfo.class, ApiKeyCredentials.class, @@ -607,18 +524,13 @@ public JAXBContext getJAXBContext() throws KapuaException { CredentialListResult.class, CredentialCreator.class, CredentialType.class, - CredentialQuery.class, - CredentialXmlRegistry.class, // Multi Factor Authentication MfaOption.class, MfaOptionListResult.class, MfaOptionCreator.class, - MfaOptionQuery.class, - MfaOptionXmlRegistry.class, ScratchCode.class, ScratchCodeListResult.class, - ScratchCodeXmlRegistry.class, // Permission Permission.class, @@ -629,89 +541,70 @@ public JAXBContext getJAXBContext() throws KapuaException { EndpointInfoListResult.class, EndpointInfoCreator.class, EndpointInfoQuery.class, - EndpointInfoXmlRegistry.class, // Roles Role.class, RoleListResult.class, RoleCreator.class, RoleQuery.class, - RoleXmlRegistry.class, // Role Permissions RolePermission.class, RolePermissionListResult.class, RolePermissionCreator.class, - RolePermissionQuery.class, - RolePermissionXmlRegistry.class, // Domains Domain.class, DomainListResult.class, - DomainQuery.class, - DomainXmlRegistry.class, // Groups Group.class, GroupListResult.class, GroupCreator.class, GroupQuery.class, - GroupXmlRegistry.class, // Access Info AccessInfo.class, AccessInfoListResult.class, AccessInfoCreator.class, - AccessInfoQuery.class, - AccessInfoXmlRegistry.class, // Access Permissions AccessPermission.class, AccessPermissionListResult.class, AccessPermissionCreator.class, - AccessPermissionQuery.class, - AccessPermissionXmlRegistry.class, // Access Roles AccessRole.class, AccessRoleListResult.class, AccessRoleCreator.class, - AccessRoleQuery.class, - AccessRoleXmlRegistry.class, // System Info SystemInfo.class, - SystemInfoXmlRegistry.class, // Tag Tag.class, TagListResult.class, TagCreator.class, TagQuery.class, - TagXmlRegistry.class, // User User.class, UserCreator.class, UserListResult.class, UserQuery.class, - UserXmlRegistry.class, // User Credentials PasswordChangeRequest.class, PasswordResetRequest.class, - UserCredentialsXmlRegistry.class, // User Profile UserProfile.class, - UserProfileXmlRegistry.class, // KapuaEvent ServiceEvent.class, EventStoreRecordCreator.class, EventStoreRecordListResult.class, EventStoreRecordQuery.class, - EventStoreXmlRegistry.class, // Service Config ServiceConfiguration.class, @@ -726,44 +619,32 @@ public JAXBContext getJAXBContext() throws KapuaException { JobCreator.class, JobListResult.class, JobQuery.class, - JobXmlRegistry.class, - JobEngineXmlRegistry.class, JobStep.class, JobStepCreator.class, JobStepListResult.class, - JobStepQuery.class, - JobStepXmlRegistry.class, JobStepProperty.class, JobExecution.class, JobExecutionListResult.class, JobExecutionQuery.class, - JobExecutionXmlRegistry.class, JobTarget.class, JobTargetCreator.class, JobTargetListResult.class, - JobTargetQuery.class, - JobExecutionXmlRegistry.class, // Trigger Trigger.class, TriggerCreator.class, TriggerListResult.class, - TriggerQuery.class, TriggerProperty.class, - TriggerXmlRegistry.class, TriggerDefinition.class, TriggerDefinitionListResult.class, TriggerDefinitionQuery.class, - TriggerDefinitionXmlRegistry.class, FiredTrigger.class, FiredTriggerListResult.class, - FiredTriggerQuery.class, - FiredTriggerXmlRegistry.class, JobStepDefinition.class, JobStepDefinitionListResult.class, diff --git a/service/account/api/pom.xml b/service/account/api/pom.xml index 3874824bb9c..facef182fda 100644 --- a/service/account/api/pom.xml +++ b/service/account/api/pom.xml @@ -17,7 +17,7 @@ org.eclipse.kapua kapua-account - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-account-api diff --git a/service/account/api/src/main/java/org/eclipse/kapua/service/account/AccountCreator.java b/service/account/api/src/main/java/org/eclipse/kapua/service/account/AccountCreator.java index 2d410b5ba83..d044db23644 100644 --- a/service/account/api/src/main/java/org/eclipse/kapua/service/account/AccountCreator.java +++ b/service/account/api/src/main/java/org/eclipse/kapua/service/account/AccountCreator.java @@ -12,10 +12,7 @@ *******************************************************************************/ package org.eclipse.kapua.service.account; -import org.eclipse.kapua.model.KapuaEntityCreator; -import org.eclipse.kapua.model.KapuaNamedEntityCreator; -import org.eclipse.kapua.model.xml.DateXmlAdapter; -import org.eclipse.kapua.service.account.xml.AccountXmlRegistry; +import java.util.Date; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; @@ -23,7 +20,11 @@ import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; -import java.util.Date; + +import org.eclipse.kapua.model.KapuaEntityCreator; +import org.eclipse.kapua.model.KapuaNamedEntityCreator; +import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.xml.DateXmlAdapter; /** * {@link Account} {@link KapuaEntityCreator} definition. @@ -46,9 +47,44 @@ "organizationStateProvinceCounty", "organizationCountry", "expirationDate" - }, - factoryClass = AccountXmlRegistry.class, factoryMethod = "newAccountCreator") -public interface AccountCreator extends KapuaNamedEntityCreator { + }) +public class AccountCreator extends KapuaNamedEntityCreator { + + private static final long serialVersionUID = -2460883485294616032L; + + private String organizationName; + private String organizationPersonName; + private String organizationEmail; + private String organizationPhoneNumber; + private String organizationAddressLine1; + private String organizationAddressLine2; + private String organizationAddressLine3; + private String organizationCity; + private String organizationZipPostCode; + private String organizationStateProvinceCounty; + private String organizationCountry; + + private Date expirationDate; + + public AccountCreator() { + } + + public AccountCreator(KapuaId scopeId) { + super(scopeId); + } + + /** + * Constructor. + * + * @param scopeId + * The {@link AccountCreator#getScopeId()}. + * @param name + * The {@link AccountCreator#getName()}. + * @since 1.0.0 + */ + public AccountCreator(KapuaId scopeId, String name) { + super(scopeId, name); + } /** * Gets the {@link Organization#getName()}. @@ -57,15 +93,20 @@ public interface AccountCreator extends KapuaNamedEntityCreator { * @since 1.0.0 */ @XmlElement(name = "organizationName") - String getOrganizationName(); + public String getOrganizationName() { + return organizationName; + } /** * Sets the {@link Organization#getName()}. * - * @param organizationName The {@link Organization#getName()}. + * @param organizationName + * The {@link Organization#getName()}. * @since 1.0.0 */ - void setOrganizationName(String organizationName); + public void setOrganizationName(String organizationName) { + this.organizationName = organizationName; + } /** * Gets the {@link Organization#getPersonName()}. @@ -74,15 +115,20 @@ public interface AccountCreator extends KapuaNamedEntityCreator { * @since 1.0.0 */ @XmlElement(name = "organizationPersonName") - String getOrganizationPersonName(); + public String getOrganizationPersonName() { + return organizationPersonName; + } /** * Sets the {@link Organization#getPersonName()}. * - * @param organizationPersonName The {@link Organization#getPersonName()}. + * @param organizationPersonName + * The {@link Organization#getPersonName()}. * @since 1.0.0 */ - void setOrganizationPersonName(String organizationPersonName); + public void setOrganizationPersonName(String organizationPersonName) { + this.organizationPersonName = organizationPersonName; + } /** * Gets the {@link Organization#getEmail()}. @@ -91,15 +137,20 @@ public interface AccountCreator extends KapuaNamedEntityCreator { * @since 1.0.0 */ @XmlElement(name = "organizationEmail") - String getOrganizationEmail(); + public String getOrganizationEmail() { + return organizationEmail; + } /** * Sets the {@link Organization#getEmail()}. * - * @param organizationEmail The {@link Organization#getEmail()}. + * @param organizationEmail + * The {@link Organization#getEmail()}. * @since 1.0.0 */ - void setOrganizationEmail(String organizationEmail); + public void setOrganizationEmail(String organizationEmail) { + this.organizationEmail = organizationEmail; + } /** * Gets the {@link Organization#getPhoneNumber()}. @@ -108,15 +159,20 @@ public interface AccountCreator extends KapuaNamedEntityCreator { * @since 1.0.0 */ @XmlElement(name = "organizationPhoneNumber") - String getOrganizationPhoneNumber(); + public String getOrganizationPhoneNumber() { + return organizationPhoneNumber; + } /** * Sets the {@link Organization#getPhoneNumber()}. * - * @param organizationPhoneNumber The {@link Organization#getPhoneNumber()}. + * @param organizationPhoneNumber + * The {@link Organization#getPhoneNumber()}. * @since 1.0.0 */ - void setOrganizationPhoneNumber(String organizationPhoneNumber); + public void setOrganizationPhoneNumber(String organizationPhoneNumber) { + this.organizationPhoneNumber = organizationPhoneNumber; + } /** * Gets the {@link Organization#getAddressLine1()}. @@ -125,15 +181,20 @@ public interface AccountCreator extends KapuaNamedEntityCreator { * @since 1.0.0 */ @XmlElement(name = "organizationAddressLine1") - String getOrganizationAddressLine1(); + public String getOrganizationAddressLine1() { + return organizationAddressLine1; + } /** * Sets the {@link Organization#getAddressLine1()}. * - * @param organizationAddressLine1 The {@link Organization#getAddressLine1()}. + * @param organizationAddressLine1 + * The {@link Organization#getAddressLine1()}. * @since 1.0.0 */ - void setOrganizationAddressLine1(String organizationAddressLine1); + public void setOrganizationAddressLine1(String organizationAddressLine1) { + this.organizationAddressLine1 = organizationAddressLine1; + } /** * Gets the {@link Organization#getAddressLine2()}. @@ -142,32 +203,42 @@ public interface AccountCreator extends KapuaNamedEntityCreator { * @since 1.0.0 */ @XmlElement(name = "organizationAddressLine2") - String getOrganizationAddressLine2(); + public String getOrganizationAddressLine2() { + return organizationAddressLine2; + } /** * Sets the {@link Organization#getAddressLine2()}. * - * @param organizationAddressLine2 The {@link Organization#getAddressLine2()}. + * @param organizationAddressLine2 + * The {@link Organization#getAddressLine2()}. * @since 1.0.0 */ - void setOrganizationAddressLine2(String organizationAddressLine2); + public void setOrganizationAddressLine2(String organizationAddressLine2) { + this.organizationAddressLine2 = organizationAddressLine2; + } - /*3 + /** * Gets the {@link Organization#getAddressLine3()}. * * @return The {@link Organization#getAddressLine3()}. * @since 1.0.0 */ @XmlElement(name = "organizationAddressLine3") - String getOrganizationAddressLine3(); + public String getOrganizationAddressLine3() { + return organizationAddressLine3; + } /** * Sets the {@link Organization#getAddressLine3()}. * - * @param organizationAddressLine3 The {@link Organization#getAddressLine3()}. + * @param organizationAddressLine3 + * The {@link Organization#getAddressLine3()}. * @since 1.0.0 */ - void setOrganizationAddressLine3(String organizationAddressLine3); + public void setOrganizationAddressLine3(String organizationAddressLine3) { + this.organizationAddressLine3 = organizationAddressLine3; + } /** * Gets the {@link Organization#getCity()}. @@ -176,15 +247,20 @@ public interface AccountCreator extends KapuaNamedEntityCreator { * @since 1.0.0 */ @XmlElement(name = "organizationCity") - String getOrganizationCity(); + public String getOrganizationCity() { + return organizationCity; + } /** * Sets the {@link Organization#getCity()}. * - * @param organizationCity The {@link Organization#getCity()}. + * @param organizationCity + * The {@link Organization#getCity()}. * @since 1.0.0 */ - void setOrganizationCity(String organizationCity); + public void setOrganizationCity(String organizationCity) { + this.organizationCity = organizationCity; + } /** * Gets the {@link Organization#getZipPostCode()}. @@ -193,15 +269,20 @@ public interface AccountCreator extends KapuaNamedEntityCreator { * @since 1.0.0 */ @XmlElement(name = "organizationZipPostCode") - String getOrganizationZipPostCode(); + public String getOrganizationZipPostCode() { + return organizationZipPostCode; + } /** * Sets the {@link Organization#getZipPostCode()}. * - * @param organizationZipPostCode The {@link Organization#getZipPostCode()}. + * @param organizationZipPostCode + * The {@link Organization#getZipPostCode()}. * @since 1.0.0 */ - void setOrganizationZipPostCode(String organizationZipPostCode); + public void setOrganizationZipPostCode(String organizationZipPostCode) { + this.organizationZipPostCode = organizationZipPostCode; + } /** * Gets the {@link Organization#getStateProvinceCounty()}. @@ -210,15 +291,20 @@ public interface AccountCreator extends KapuaNamedEntityCreator { * @since 1.0.0 */ @XmlElement(name = "organizationStateProvinceCounty") - String getOrganizationStateProvinceCounty(); + public String getOrganizationStateProvinceCounty() { + return this.organizationStateProvinceCounty; + } /** * Sets the {@link Organization#getStateProvinceCounty()}. * - * @param organizationStateProvinceCounty The {@link Organization#getStateProvinceCounty()}. + * @param organizationStateProvinceCounty + * The {@link Organization#getStateProvinceCounty()}. * @since 1.0.0 */ - void setOrganizationStateProvinceCounty(String organizationStateProvinceCounty); + public void setOrganizationStateProvinceCounty(String organizationStateProvinceCounty) { + this.organizationStateProvinceCounty = organizationStateProvinceCounty; + } /** * Gets the {@link Organization#getCountry()}. @@ -227,15 +313,20 @@ public interface AccountCreator extends KapuaNamedEntityCreator { * @since 1.0.0 */ @XmlElement(name = "organizationCountry") - String getOrganizationCountry(); + public String getOrganizationCountry() { + return organizationCountry; + } /** * Sets the {@link Organization#getCountry()}. * - * @param organizationCountry The {@link Organization#getCountry()}. + * @param organizationCountry + * The {@link Organization#getCountry()}. * @since 1.0.0 */ - void setOrganizationCountry(String organizationCountry); + public void setOrganizationCountry(String organizationCountry) { + this.organizationCountry = organizationCountry; + } /** * Gets the expiration date. @@ -245,13 +336,18 @@ public interface AccountCreator extends KapuaNamedEntityCreator { */ @XmlElement(name = "expirationDate") @XmlJavaTypeAdapter(DateXmlAdapter.class) - Date getExpirationDate(); + public Date getExpirationDate() { + return expirationDate; + } /** * Sets the expiration date. * - * @param expirationDate The expiration date. + * @param expirationDate + * The expiration date. * @since 1.0.0 */ - void setExpirationDate(Date expirationDate); + public void setExpirationDate(Date expirationDate) { + this.expirationDate = expirationDate; + } } diff --git a/service/account/api/src/main/java/org/eclipse/kapua/service/account/AccountFactory.java b/service/account/api/src/main/java/org/eclipse/kapua/service/account/AccountFactory.java index 81ee1ba3ba5..fed0b991b40 100644 --- a/service/account/api/src/main/java/org/eclipse/kapua/service/account/AccountFactory.java +++ b/service/account/api/src/main/java/org/eclipse/kapua/service/account/AccountFactory.java @@ -13,7 +13,6 @@ package org.eclipse.kapua.service.account; import org.eclipse.kapua.model.KapuaEntityFactory; -import org.eclipse.kapua.model.id.KapuaId; /** * {@link Account} {@link KapuaEntityFactory} definition. @@ -21,19 +20,7 @@ * @see KapuaEntityFactory * @since 1.0.0 */ -public interface AccountFactory extends KapuaEntityFactory { - - /** - * Instantiates a new {@link AccountCreator} with the given name. - * - * @param scopeId The scope {@link KapuaId} to set in the {@link AccountCreator} - * @param name The name to set in the {@link AccountCreator} - * @return The newly instantiated {@link AccountCreator} - * @since 1.0.0 - * @deprecated Since 1.6.0. Please make use of {@link #newCreator(KapuaId)} and then use {@link AccountCreator#setName(String)}. - */ - @Deprecated - AccountCreator newCreator(KapuaId scopeId, String name); +public interface AccountFactory extends KapuaEntityFactory { /** * Instantiates a new {@link Organization}. diff --git a/service/account/api/src/main/java/org/eclipse/kapua/service/account/AccountListResult.java b/service/account/api/src/main/java/org/eclipse/kapua/service/account/AccountListResult.java index 2a722a816d7..e6802552b7c 100644 --- a/service/account/api/src/main/java/org/eclipse/kapua/service/account/AccountListResult.java +++ b/service/account/api/src/main/java/org/eclipse/kapua/service/account/AccountListResult.java @@ -12,14 +12,13 @@ *******************************************************************************/ package org.eclipse.kapua.service.account; -import org.eclipse.kapua.model.query.KapuaListResult; -import org.eclipse.kapua.service.account.xml.AccountXmlRegistry; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; +import org.eclipse.kapua.model.query.KapuaListResult; + /** * {@link Account} {@link KapuaListResult} definition. * @@ -28,7 +27,9 @@ */ @XmlRootElement(name = "accountListResult") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = AccountXmlRegistry.class, factoryMethod = "newAccountListResult") -public interface AccountListResult extends KapuaListResult { +@XmlType +public class AccountListResult extends KapuaListResult { + + private static final long serialVersionUID = -5118004898345748297L; } diff --git a/service/account/api/src/main/java/org/eclipse/kapua/service/account/AccountQuery.java b/service/account/api/src/main/java/org/eclipse/kapua/service/account/AccountQuery.java deleted file mode 100644 index 5e320976b3d..00000000000 --- a/service/account/api/src/main/java/org/eclipse/kapua/service/account/AccountQuery.java +++ /dev/null @@ -1,33 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.account; - -import org.eclipse.kapua.model.query.KapuaQuery; -import org.eclipse.kapua.service.account.xml.AccountXmlRegistry; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlType; - -/** - * {@link Account} {@link KapuaQuery} definition. - * - * @see KapuaQuery - * @since 1.0.0 - */ -@XmlRootElement(name = "query") -@XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = AccountXmlRegistry.class, factoryMethod = "newQuery") -public interface AccountQuery extends KapuaQuery { -} diff --git a/service/account/api/src/main/java/org/eclipse/kapua/service/account/xml/AccountXmlRegistry.java b/service/account/api/src/main/java/org/eclipse/kapua/service/account/xml/AccountXmlRegistry.java index c18879dfbeb..1b673ec9133 100644 --- a/service/account/api/src/main/java/org/eclipse/kapua/service/account/xml/AccountXmlRegistry.java +++ b/service/account/api/src/main/java/org/eclipse/kapua/service/account/xml/AccountXmlRegistry.java @@ -12,16 +12,13 @@ *******************************************************************************/ package org.eclipse.kapua.service.account.xml; +import javax.xml.bind.annotation.XmlRegistry; + import org.eclipse.kapua.locator.KapuaLocator; import org.eclipse.kapua.service.account.Account; -import org.eclipse.kapua.service.account.AccountCreator; import org.eclipse.kapua.service.account.AccountFactory; -import org.eclipse.kapua.service.account.AccountListResult; -import org.eclipse.kapua.service.account.AccountQuery; import org.eclipse.kapua.service.account.Organization; -import javax.xml.bind.annotation.XmlRegistry; - /** * {@link Account} xml factory class * @@ -43,36 +40,6 @@ public Account newAccount() { return factory.newEntity(null); } - /** - * Instantiates a new {@link AccountCreator}. - * - * @return The newly instantiated {@link AccountCreator}. - * @since 1.0.0 - */ - public AccountCreator newAccountCreator() { - return factory.newCreator(null); - } - - /** - * Instantiates a new {@link AccountListResult}. - * - * @return The newly instantiated {@link AccountListResult}. - * @since 1.0.0 - */ - public AccountListResult newAccountListResult() { - return factory.newListResult(); - } - - /** - * Instantiates a new {@link AccountQuery}. - * - * @return The newly instantiated {@link AccountQuery}. - * @since 1.0.0 - */ - public AccountQuery newQuery() { - return factory.newQuery(null); - } - /** * Instantiates a new {@link Organization}. * diff --git a/service/account/internal/pom.xml b/service/account/internal/pom.xml index d774ec36bf1..a80fdba2918 100644 --- a/service/account/internal/pom.xml +++ b/service/account/internal/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-account - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-account-internal diff --git a/service/account/internal/src/main/java/org/eclipse/kapua/service/account/internal/AccountCreatorImpl.java b/service/account/internal/src/main/java/org/eclipse/kapua/service/account/internal/AccountCreatorImpl.java deleted file mode 100644 index a5217b68426..00000000000 --- a/service/account/internal/src/main/java/org/eclipse/kapua/service/account/internal/AccountCreatorImpl.java +++ /dev/null @@ -1,175 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.account.internal; - -import org.eclipse.kapua.commons.model.AbstractKapuaNamedEntityCreator; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.account.Account; -import org.eclipse.kapua.service.account.AccountCreator; - -import java.util.Date; - -/** - * {@link AccountCreator} implementation. - * - * @since 1.0.0 - */ -public class AccountCreatorImpl extends AbstractKapuaNamedEntityCreator implements AccountCreator { - - private static final long serialVersionUID = -2460883485294616032L; - - private String organizationName; - private String organizationPersonName; - private String organizationEmail; - private String organizationPhoneNumber; - private String organizationAddressLine1; - private String organizationAddressLine2; - private String organizationAddressLine3; - private String organizationCity; - private String organizationZipPostCode; - private String organizationStateProvinceCounty; - private String organizationCountry; - - private Date expirationDate; - - /** - * Constructor. - * - * @param scopeId The {@link AccountCreator#getScopeId()}. - * @param name The {@link AccountCreator#getName()}. - * @since 1.0.0 - */ - public AccountCreatorImpl(KapuaId scopeId, String name) { - super(scopeId, name); - } - - @Override - public String getOrganizationName() { - return organizationName; - } - - @Override - public void setOrganizationName(String organizationName) { - this.organizationName = organizationName; - } - - @Override - public String getOrganizationPersonName() { - return organizationPersonName; - } - - @Override - public void setOrganizationPersonName(String organizationPersonName) { - this.organizationPersonName = organizationPersonName; - } - - @Override - public String getOrganizationEmail() { - return organizationEmail; - } - - @Override - public void setOrganizationEmail(String organizationEmail) { - this.organizationEmail = organizationEmail; - } - - @Override - public String getOrganizationPhoneNumber() { - return organizationPhoneNumber; - } - - @Override - public void setOrganizationPhoneNumber(String organizationPhoneNumber) { - this.organizationPhoneNumber = organizationPhoneNumber; - } - - @Override - public String getOrganizationAddressLine1() { - return organizationAddressLine1; - } - - @Override - public void setOrganizationAddressLine1(String organizationAddressLine1) { - this.organizationAddressLine1 = organizationAddressLine1; - } - - @Override - public String getOrganizationAddressLine2() { - return organizationAddressLine2; - } - - @Override - public void setOrganizationAddressLine2(String organizationAddressLine2) { - this.organizationAddressLine2 = organizationAddressLine2; - } - - @Override - public String getOrganizationAddressLine3() { - return organizationAddressLine3; - } - - @Override - public void setOrganizationAddressLine3(String organizationAddressLine3) { - this.organizationAddressLine3 = organizationAddressLine3; - } - - @Override - public String getOrganizationCity() { - return organizationCity; - } - - @Override - public void setOrganizationCity(String organizationCity) { - this.organizationCity = organizationCity; - } - - @Override - public String getOrganizationZipPostCode() { - return organizationZipPostCode; - } - - @Override - public void setOrganizationZipPostCode(String organizationZipPostCode) { - this.organizationZipPostCode = organizationZipPostCode; - } - - @Override - public String getOrganizationStateProvinceCounty() { - return organizationStateProvinceCounty; - } - - @Override - public void setOrganizationStateProvinceCounty(String organizationStateProvinceCounty) { - this.organizationStateProvinceCounty = organizationStateProvinceCounty; - } - - @Override - public String getOrganizationCountry() { - return organizationCountry; - } - - @Override - public void setOrganizationCountry(String organizationCountry) { - this.organizationCountry = organizationCountry; - } - - @Override - public Date getExpirationDate() { - return expirationDate; - } - - @Override - public void setExpirationDate(Date expirationDate) { - this.expirationDate = expirationDate; - } -} diff --git a/service/account/internal/src/main/java/org/eclipse/kapua/service/account/internal/AccountFactoryImpl.java b/service/account/internal/src/main/java/org/eclipse/kapua/service/account/internal/AccountFactoryImpl.java index 947da2ca339..f8adaa25a1c 100644 --- a/service/account/internal/src/main/java/org/eclipse/kapua/service/account/internal/AccountFactoryImpl.java +++ b/service/account/internal/src/main/java/org/eclipse/kapua/service/account/internal/AccountFactoryImpl.java @@ -12,17 +12,14 @@ *******************************************************************************/ package org.eclipse.kapua.service.account.internal; +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaEntityCloneException; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.account.Account; -import org.eclipse.kapua.service.account.AccountCreator; import org.eclipse.kapua.service.account.AccountFactory; -import org.eclipse.kapua.service.account.AccountListResult; -import org.eclipse.kapua.service.account.AccountQuery; import org.eclipse.kapua.service.account.Organization; -import javax.inject.Singleton; - /** * {@link AccountFactory} implementation. * @@ -31,18 +28,6 @@ @Singleton public class AccountFactoryImpl implements AccountFactory { - @Override - public AccountCreator newCreator(KapuaId scopeId) { - return new AccountCreatorImpl(scopeId, null); - } - - @Override - public AccountCreator newCreator(KapuaId scopeId, String name) { - AccountCreator creator = newCreator(scopeId); - creator.setName(name); - return creator; - } - @Override public Account newEntity(KapuaId scopeId) { return new AccountImpl(scopeId); @@ -53,16 +38,6 @@ public Organization newOrganization() { return new OrganizationImpl(); } - @Override - public AccountQuery newQuery(KapuaId scopeId) { - return new AccountQueryImpl(scopeId); - } - - @Override - public AccountListResult newListResult() { - return new AccountListResultImpl(); - } - @Override public Account clone(Account account) { try { diff --git a/service/account/internal/src/main/java/org/eclipse/kapua/service/account/internal/AccountImplJpaRepository.java b/service/account/internal/src/main/java/org/eclipse/kapua/service/account/internal/AccountImplJpaRepository.java index 123d2691720..40eaad6d959 100644 --- a/service/account/internal/src/main/java/org/eclipse/kapua/service/account/internal/AccountImplJpaRepository.java +++ b/service/account/internal/src/main/java/org/eclipse/kapua/service/account/internal/AccountImplJpaRepository.java @@ -12,6 +12,9 @@ *******************************************************************************/ package org.eclipse.kapua.service.account.internal; +import javax.persistence.EntityManager; +import javax.persistence.TypedQuery; + import org.eclipse.kapua.commons.jpa.JpaAwareTxContext; import org.eclipse.kapua.commons.jpa.KapuaJpaRepositoryConfiguration; import org.eclipse.kapua.commons.jpa.KapuaNamedEntityJpaRepository; @@ -20,15 +23,12 @@ import org.eclipse.kapua.service.account.AccountRepository; import org.eclipse.kapua.storage.TxContext; -import javax.persistence.EntityManager; -import javax.persistence.TypedQuery; - public class AccountImplJpaRepository extends KapuaNamedEntityJpaRepository implements AccountRepository { public AccountImplJpaRepository(KapuaJpaRepositoryConfiguration jpaRepoConfig) { - super(AccountImpl.class, Account.TYPE, () -> new AccountListResultImpl(), jpaRepoConfig); + super(AccountImpl.class, Account.TYPE, () -> new AccountListResult(), jpaRepoConfig); } @Override diff --git a/service/account/internal/src/main/java/org/eclipse/kapua/service/account/internal/AccountListResultImpl.java b/service/account/internal/src/main/java/org/eclipse/kapua/service/account/internal/AccountListResultImpl.java deleted file mode 100644 index 34d05856e03..00000000000 --- a/service/account/internal/src/main/java/org/eclipse/kapua/service/account/internal/AccountListResultImpl.java +++ /dev/null @@ -1,27 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.account.internal; - -import org.eclipse.kapua.commons.model.query.KapuaListResultImpl; -import org.eclipse.kapua.service.account.Account; -import org.eclipse.kapua.service.account.AccountListResult; - -/** - * {@link AccountListResult} implementation. - * - * @since 1.0.0 - */ -public class AccountListResultImpl extends KapuaListResultImpl implements AccountListResult { - - private static final long serialVersionUID = -5118004898345748297L; -} diff --git a/service/account/internal/src/main/java/org/eclipse/kapua/service/account/internal/AccountMapper.java b/service/account/internal/src/main/java/org/eclipse/kapua/service/account/internal/AccountMapper.java index 570b37fc29f..640db26346d 100644 --- a/service/account/internal/src/main/java/org/eclipse/kapua/service/account/internal/AccountMapper.java +++ b/service/account/internal/src/main/java/org/eclipse/kapua/service/account/internal/AccountMapper.java @@ -50,7 +50,11 @@ default Organization createOrganisation() { void merge(@MappingTarget Organization account, Organization request); //For backward compatibility only + @Mapping(target = "entityAttributes", ignore = true) + @Mapping(target = "entityProperties", ignore = true) AccountUpdateRequest mapChildUpdate(Account account); + @Mapping(target = "entityAttributes", ignore = true) + @Mapping(target = "entityProperties", ignore = true) CurrentAccountUpdateRequest mapCurrentUpdate(Account account); } diff --git a/service/account/internal/src/main/java/org/eclipse/kapua/service/account/internal/AccountModule.java b/service/account/internal/src/main/java/org/eclipse/kapua/service/account/internal/AccountModule.java index 53c2710e204..661bf42a7a7 100644 --- a/service/account/internal/src/main/java/org/eclipse/kapua/service/account/internal/AccountModule.java +++ b/service/account/internal/src/main/java/org/eclipse/kapua/service/account/internal/AccountModule.java @@ -27,7 +27,6 @@ import org.eclipse.kapua.commons.jpa.KapuaJpaTxManagerFactory; import org.eclipse.kapua.commons.jpa.NamedCacheFactory; import org.eclipse.kapua.commons.model.domains.Domains; -import org.eclipse.kapua.commons.service.event.store.api.EventStoreFactory; import org.eclipse.kapua.commons.service.event.store.api.EventStoreRecordRepository; import org.eclipse.kapua.commons.service.event.store.internal.EventStoreServiceImpl; import org.eclipse.kapua.commons.service.internal.cache.NamedEntityCache; @@ -41,7 +40,6 @@ import org.eclipse.kapua.service.account.AccountService; import org.eclipse.kapua.service.account.internal.setting.KapuaAccountSetting; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; import com.google.inject.Module; import com.google.inject.Provides; @@ -70,19 +68,15 @@ public Domain accountDomain() { @Provides @Singleton AccountRelativeFinder accountRelativeFinder( - AccountFactory accountFactory, AccountService accountService) { return new AccountRelativeFinderImpl( - accountFactory, accountService); } @ProvidesIntoSet ServiceModule accountServiceModule(AccountService accountService, AuthorizationService authorizationService, - PermissionFactory permissionFactory, KapuaJpaTxManagerFactory txManagerFactory, - EventStoreFactory eventStoreFactory, EventStoreRecordRepository eventStoreRecordRepository, ServiceEventBus serviceEventBus, KapuaAccountSetting kapuaAccountSetting, @@ -94,9 +88,7 @@ ServiceModule accountServiceModule(AccountService accountService, new ServiceEventHouseKeeperFactoryImpl( new EventStoreServiceImpl( authorizationService, - permissionFactory, txManagerFactory.create("kapua-account"), - eventStoreFactory, eventStoreRecordRepository ), txManagerFactory.create("kapua-account"), @@ -109,8 +101,6 @@ ServiceModule accountServiceModule(AccountService accountService, @Provides @Singleton AccountService accountService(AccountRepository accountRepository, - AccountFactory accountFactory, - PermissionFactory permissionFactory, AuthorizationService authorizationService, Map, ServiceConfigurationManager> serviceConfigurationManagersByServiceClass, EventStorer eventStorer, @@ -119,7 +109,6 @@ AccountService accountService(AccountRepository accountRepository, return new AccountServiceImpl( jpaTxManagerFactory.create("kapua-account"), accountRepository, - permissionFactory, authorizationService, serviceConfigurationManagersByServiceClass.get(AccountService.class), eventStorer, diff --git a/service/account/internal/src/main/java/org/eclipse/kapua/service/account/internal/AccountQueryImpl.java b/service/account/internal/src/main/java/org/eclipse/kapua/service/account/internal/AccountQueryImpl.java deleted file mode 100644 index 1c4531a6d2d..00000000000 --- a/service/account/internal/src/main/java/org/eclipse/kapua/service/account/internal/AccountQueryImpl.java +++ /dev/null @@ -1,46 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.account.internal; - -import org.eclipse.kapua.commons.model.query.AbstractKapuaNamedQuery; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.account.AccountQuery; - -/** - * {@link AccountQuery} implementation. - * - * @since 1.0.0 - */ -public class AccountQueryImpl extends AbstractKapuaNamedQuery implements AccountQuery { - - /** - * Constructor. - * - * @since 1.0.0 - */ - private AccountQueryImpl() { - super(); - } - - /** - * Constructor. - * - * @param scopeId The {@link AccountQuery#getScopeId()}. - * @since 1.0.0 - */ - public AccountQueryImpl(KapuaId scopeId) { - this(); - - setScopeId(scopeId); - } -} diff --git a/service/account/internal/src/main/java/org/eclipse/kapua/service/account/internal/AccountRelativeFinderImpl.java b/service/account/internal/src/main/java/org/eclipse/kapua/service/account/internal/AccountRelativeFinderImpl.java index 842e739b52d..7c25269b5d1 100644 --- a/service/account/internal/src/main/java/org/eclipse/kapua/service/account/internal/AccountRelativeFinderImpl.java +++ b/service/account/internal/src/main/java/org/eclipse/kapua/service/account/internal/AccountRelativeFinderImpl.java @@ -27,28 +27,25 @@ import org.eclipse.kapua.commons.security.KapuaSecurityUtils; import org.eclipse.kapua.model.KapuaEntityAttributes; import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.model.query.predicate.AttributePredicate; import org.eclipse.kapua.service.KapuaService; import org.eclipse.kapua.service.account.Account; -import org.eclipse.kapua.service.account.AccountFactory; import org.eclipse.kapua.service.account.AccountListResult; -import org.eclipse.kapua.service.account.AccountQuery; import org.eclipse.kapua.service.account.AccountService; public class AccountRelativeFinderImpl implements AccountRelativeFinder, KapuaService { - private final AccountFactory accountFactory; private final AccountService accountService; @Inject - public AccountRelativeFinderImpl(AccountFactory accountFactory, AccountService accountService) { - this.accountFactory = accountFactory; + public AccountRelativeFinderImpl(AccountService accountService) { this.accountService = accountService; } @Override public AccountListResult findChildren(KapuaId scopeId, Optional excludeTargetScopeId) throws KapuaException { - final AccountQuery childAccountsQuery = accountFactory.newQuery(scopeId); + final KapuaQuery childAccountsQuery = new KapuaQuery(scopeId); // Exclude the scope that is under config update if (excludeTargetScopeId.isPresent()) { childAccountsQuery.setPredicate( @@ -66,7 +63,7 @@ public AccountListResult findChildren(KapuaId scopeId, Optional exclude public List findParentIds(KapuaId accountId) throws KapuaException { Account account = KapuaSecurityUtils.doPrivileged(() -> accountService.find(accountId)); - if(account == null || account.getParentAccountPath() == null) { + if (account == null || account.getParentAccountPath() == null) { return Collections.emptyList(); } @@ -76,10 +73,10 @@ public List findParentIds(KapuaId accountId) throws KapuaException { String accountIdStr = accountId.getId().toString(); // Iterate in reverse order to get parent first, then grandparent, etc - for(int i = splitIds.length - 1; i >= 0; i--) { + for (int i = splitIds.length - 1; i >= 0; i--) { String id = splitIds[i]; - if(id != null && !id.isEmpty() && !id.equals(accountIdStr)) { + if (id != null && !id.isEmpty() && !id.equals(accountIdStr)) { parentAccountIds.add(new KapuaEid(new BigInteger(id))); } } diff --git a/service/account/internal/src/main/java/org/eclipse/kapua/service/account/internal/AccountServiceConfigurationManagerModule.java b/service/account/internal/src/main/java/org/eclipse/kapua/service/account/internal/AccountServiceConfigurationManagerModule.java index 871e0ffb6b9..d4aebff7d7b 100644 --- a/service/account/internal/src/main/java/org/eclipse/kapua/service/account/internal/AccountServiceConfigurationManagerModule.java +++ b/service/account/internal/src/main/java/org/eclipse/kapua/service/account/internal/AccountServiceConfigurationManagerModule.java @@ -29,7 +29,6 @@ import org.eclipse.kapua.commons.jpa.KapuaJpaTxManagerFactory; import org.eclipse.kapua.commons.model.domains.Domains; import org.eclipse.kapua.commons.util.xml.XmlUtil; -import org.eclipse.kapua.service.account.AccountFactory; import org.eclipse.kapua.service.account.AccountRepository; import org.eclipse.kapua.service.account.AccountService; @@ -54,7 +53,6 @@ protected void configureModule() { @Singleton ServiceConfigurationManager accountServiceConfigurationManager( KapuaJpaTxManagerFactory txManagerFactory, - AccountFactory factory, RootUserTester rootUserTester, AccountRelativeFinder accountRelativeFinder, AccountRepository accountRepository, @@ -74,7 +72,6 @@ ServiceConfigurationManager accountServiceConfigurationManager( rootUserTester, accountRelativeFinder, new UsedEntitiesCounterImpl( - factory, accountRepository), new ResourceBasedServiceConfigurationMetadataProvider(xmlUtil) )); diff --git a/service/account/internal/src/main/java/org/eclipse/kapua/service/account/internal/AccountServiceImpl.java b/service/account/internal/src/main/java/org/eclipse/kapua/service/account/internal/AccountServiceImpl.java index bac7692c02f..29eab6308c4 100644 --- a/service/account/internal/src/main/java/org/eclipse/kapua/service/account/internal/AccountServiceImpl.java +++ b/service/account/internal/src/main/java/org/eclipse/kapua/service/account/internal/AccountServiceImpl.java @@ -49,7 +49,7 @@ import org.eclipse.kapua.service.account.AccountUpdateRequest; import org.eclipse.kapua.service.account.CurrentAccountUpdateRequest; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; +import org.eclipse.kapua.service.authorization.permission.Permission; import org.eclipse.kapua.storage.TxContext; import org.eclipse.kapua.storage.TxManager; @@ -73,8 +73,6 @@ public class AccountServiceImpl * * @param accountRepository * The {@link AccountRepository} instance - * @param permissionFactory - * The {@link PermissionFactory} instance * @param authorizationService * The {@link AuthorizationService} instance * @param serviceConfigurationManager @@ -86,12 +84,11 @@ public class AccountServiceImpl public AccountServiceImpl( TxManager txManager, AccountRepository accountRepository, - PermissionFactory permissionFactory, AuthorizationService authorizationService, ServiceConfigurationManager serviceConfigurationManager, EventStorer eventStorer, AccountMapper accountMapper) { - super(txManager, serviceConfigurationManager, Domains.ACCOUNT, authorizationService, permissionFactory); + super(txManager, serviceConfigurationManager, Domains.ACCOUNT, authorizationService); this.accountRepository = accountRepository; this.eventStorer = eventStorer; this.accountMapper = accountMapper; @@ -109,7 +106,7 @@ public Account create(AccountCreator accountCreator) throws KapuaException { ArgumentValidator.match(accountCreator.getOrganizationEmail(), CommonsValidationRegex.EMAIL_REGEXP, "accountCreator.organizationEmail"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.ACCOUNT, Actions.write, accountCreator.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.ACCOUNT, Actions.write, accountCreator.getScopeId())); return txManager.execute(tx -> { // Check entity limit @@ -194,7 +191,7 @@ private Account doUpdateCurrentAccount(CurrentAccountUpdateRequest request) thro ArgumentValidator.match(request.organization.getEmail(), CommonsValidationRegex.EMAIL_REGEXP, "account.organization.email"); final KapuaId accountId = KapuaSecurityUtils.getSession().getScopeId(); - authorizationService.checkPermission(permissionFactory.newPermission(Domains.ACCOUNT, Actions.write, accountId)); + authorizationService.checkPermission(new Permission(Domains.ACCOUNT, Actions.write, accountId)); return txManager.execute(tx -> { // Check existence @@ -220,7 +217,7 @@ private Account doUpdateChildAccount(KapuaId accountId, AccountUpdateRequest req .orElseThrow(() -> new KapuaEntityNotFoundException(Account.TYPE, accountId)); // Editing child - authorizationService.checkPermission(permissionFactory.newPermission(Domains.ACCOUNT, Actions.write, account.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.ACCOUNT, Actions.write, account.getScopeId())); validateExpirationDate(tx, account, request); @@ -278,7 +275,7 @@ public void delete(KapuaId scopeId, KapuaId accountId) throws KapuaException { ArgumentValidator.notNull(scopeId, KapuaEntityAttributes.SCOPE_ID); ArgumentValidator.notNull(accountId, KapuaEntityAttributes.ENTITY_ID); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.ACCOUNT, Actions.delete, scopeId)); + authorizationService.checkPermission(new Permission(Domains.ACCOUNT, Actions.delete, scopeId)); // Check if it has children if (!findChildAccountsTrusted(accountId).isEmpty()) { throw new KapuaException(KapuaRuntimeErrorCodes.SERVICE_OPERATION_NOT_SUPPORTED, null, "This account cannot be deleted. Delete its child first."); @@ -390,7 +387,7 @@ public AccountListResult query(KapuaQuery query) throws KapuaException { ArgumentValidator.notNull(query, "query"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.ACCOUNT, Actions.read, query.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.ACCOUNT, Actions.read, query.getScopeId())); // Do query return txManager.execute(tx -> accountRepository.query(tx, query)); @@ -401,7 +398,7 @@ public long count(KapuaQuery query) throws KapuaException { // Argument validation ArgumentValidator.notNull(query, "query"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.ACCOUNT, Actions.read, query.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.ACCOUNT, Actions.read, query.getScopeId())); // Do count return txManager.execute(tx -> accountRepository.count(tx, query)); } @@ -412,7 +409,7 @@ private AccountListResult findChildAccountsTrusted(KapuaId accountId) ArgumentValidator.notNull(accountId, KapuaEntityAttributes.ENTITY_ID); ArgumentValidator.notNull(accountId.getId(), "accountId.id"); // Do find - return txManager.execute(tx -> accountRepository.query(tx, new AccountQueryImpl(accountId))); + return txManager.execute(tx -> accountRepository.query(tx, new KapuaQuery(accountId))); } private void checkAccountPermission(KapuaId scopeId, KapuaId accountId, Actions action) throws KapuaException { @@ -428,10 +425,10 @@ private void checkAccountPermission(KapuaId scopeId, KapuaId accountId, Actions private void checkAccountPermission(KapuaId scopeId, KapuaId accountId, Actions action, boolean forwardable) throws KapuaException { if (KapuaSecurityUtils.getSession().getScopeId().equals(accountId)) { // I'm looking for myself, so let's check if I have the correct permission - authorizationService.checkPermission(permissionFactory.newPermission(Domains.ACCOUNT, action, accountId, null, forwardable)); + authorizationService.checkPermission(new Permission(Domains.ACCOUNT, action, accountId, null, forwardable)); } else { // I'm looking for another account, so I need to check the permission on the account scope - authorizationService.checkPermission(permissionFactory.newPermission(Domains.ACCOUNT, action, scopeId, null, forwardable)); + authorizationService.checkPermission(new Permission(Domains.ACCOUNT, action, scopeId, null, forwardable)); } } } diff --git a/service/account/pom.xml b/service/account/pom.xml index 3405811d8c3..3c1a8c3884f 100644 --- a/service/account/pom.xml +++ b/service/account/pom.xml @@ -19,7 +19,7 @@ org.eclipse.kapua kapua-service - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT pom diff --git a/service/account/test-steps/pom.xml b/service/account/test-steps/pom.xml index a9134a3c77c..7a36f0c6cd9 100644 --- a/service/account/test-steps/pom.xml +++ b/service/account/test-steps/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-account - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-account-test-steps diff --git a/service/account/test-steps/src/main/java/org/eclipse/kapua/service/account/steps/AccountServiceSteps.java b/service/account/test-steps/src/main/java/org/eclipse/kapua/service/account/steps/AccountServiceSteps.java index 29b66908557..332f102504b 100755 --- a/service/account/test-steps/src/main/java/org/eclipse/kapua/service/account/steps/AccountServiceSteps.java +++ b/service/account/test-steps/src/main/java/org/eclipse/kapua/service/account/steps/AccountServiceSteps.java @@ -21,7 +21,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Properties; import javax.inject.Inject; @@ -45,16 +44,13 @@ import org.eclipse.kapua.service.account.Account; import org.eclipse.kapua.service.account.AccountAttributes; import org.eclipse.kapua.service.account.AccountCreator; -import org.eclipse.kapua.service.account.AccountFactory; import org.eclipse.kapua.service.account.AccountListResult; -import org.eclipse.kapua.service.account.AccountQuery; import org.eclipse.kapua.service.account.AccountService; import org.eclipse.kapua.service.account.Organization; import org.junit.Assert; import com.google.inject.Singleton; -import io.cucumber.datatable.DataTable; import io.cucumber.java.After; import io.cucumber.java.Before; import io.cucumber.java.Scenario; @@ -82,7 +78,6 @@ public class AccountServiceSteps extends TestBase { // Account creator object used for creating new accounts. private AccountService accountService; - private AccountFactory accountFactory; // Default constructor @Inject @@ -93,7 +88,6 @@ public AccountServiceSteps(StepData stepData) { @After(value = "@setup") public void setServices() { locator = KapuaLocator.getInstance(); - accountFactory = locator.getFactory(AccountFactory.class); accountService = locator.getService(AccountService.class); } @@ -462,26 +456,6 @@ public void findRandomAccountId() throws Exception { } } - @When("I set the following parameters") - public void setAccountParameters(DataTable dataTable) throws Exception { - Assert.assertEquals("Wrong test setup. Bad parameters size!", 2, dataTable.width()); - Account account = (Account) stepData.get(LAST_ACCOUNT); - Properties accProps = account.getEntityProperties(); - - for (List row : dataTable.asLists()) { - accProps.setProperty(row.get(0), row.get(1)); - } - account.setEntityProperties(accProps); - - try { - primeException(); - account = accountService.update(account); - stepData.put(LAST_ACCOUNT, account); - } catch (KapuaException ex) { - verifyException(ex); - } - } - @When("I configure {string} item {string} to {string}") public void setConfigurationValue(String type, String name, String value) throws Exception { Map valueMap = new HashMap<>(); @@ -523,7 +497,7 @@ public void addUnknownIntegerConfigurationValue(String name, int value) throws E @When("I query for all accounts that have the system account as parent") public void queryForNumberOfTopLevelAccounts() throws Exception { - AccountQuery query = accountFactory.newQuery(SYS_SCOPE_ID); + KapuaQuery query = new KapuaQuery(SYS_SCOPE_ID); stepData.remove(INT_VALUE); try { primeException(); @@ -593,7 +567,7 @@ public void checkForAccountModifications(String name) throws KapuaException { @Then("The account with name {string} has {int} subaccount(s)") public void checkNumberOfAccounts(String accountName, int num) throws KapuaException { - KapuaQuery query = accountFactory.newQuery(getCurrentScopeId()); + final KapuaQuery query = new KapuaQuery(getCurrentScopeId()); Account account = accountService.find(getCurrentScopeId()); Assert.assertEquals(accountName, account.getName()); @@ -606,7 +580,7 @@ public void checkNumberOfChildrenForNamedAccount(String name, int num) throws Ex try { primeException(); Account tmpAcc = accountService.findByName(name); - KapuaQuery query = accountFactory.newQuery(tmpAcc.getId()); + final KapuaQuery query = new KapuaQuery(tmpAcc.getId()); long accountCnt = accountService.count(query); Assert.assertEquals(num, accountCnt); @@ -628,17 +602,6 @@ public void findSystemAccount() throws KapuaException { Assert.assertNotNull(tmpAcc); } - @Then("The account has the following parameters") - public void checkAccountParameters(DataTable dataTable) throws KapuaException { - Assert.assertEquals("Wrong test setup. Bad parameters size!", 2, dataTable.width()); - Account account = (Account) stepData.get(LAST_ACCOUNT); - Properties accProps = account.getEntityProperties(); - - for (List row : dataTable.asLists()) { - Assert.assertEquals(row.get(1), accProps.getProperty(row.get(0))); - } - } - @Then("The account has metadata") public void checkMetadataExistence() throws KapuaException { KapuaId accountId = (KapuaId) stepData.get(LAST_ACCOUNT_ID); @@ -715,7 +678,7 @@ public void setAccountServiceConfig(List cucConfigs) throws Exception * @return The newly created account creator object. */ private AccountCreator prepareRegularAccountCreator(KapuaId parentId, String name) { - AccountCreator tmpAccCreator = accountFactory.newCreator(parentId); + AccountCreator tmpAccCreator = new AccountCreator(parentId); tmpAccCreator.setName(name); tmpAccCreator.setOrganizationName("org_" + name); @@ -769,7 +732,7 @@ private Account createAccount(CucAccount cucAccount) throws Exception { */ private AccountCreator accountCreatorCreator(String name, BigInteger scopeId, Date expiration) { - AccountCreator accountCreator = accountFactory.newCreator(new KapuaEid(scopeId)); + AccountCreator accountCreator = new AccountCreator(new KapuaEid(scopeId)); accountCreator.setName(name); accountCreator.setOrganizationName("ACME Inc."); accountCreator.setOrganizationEmail("some@one.com"); @@ -783,7 +746,7 @@ private AccountCreator accountCreatorCreator(String name, BigInteger scopeId, Da @And("I find account with name {string}") public void iFindAccountWithName(String accountName) throws Exception { - AccountQuery accountQuery = accountFactory.newQuery(getCurrentScopeId()); + final KapuaQuery accountQuery = new KapuaQuery(getCurrentScopeId()); accountQuery.setPredicate(accountQuery.attributePredicate(AccountAttributes.NAME, accountName)); AccountListResult accountListResult = accountService.query(accountQuery); Assert.assertTrue(accountListResult.getSize() > 0); @@ -804,7 +767,7 @@ public void iTryToEditAccountWithName(String description) throws Exception { @And("I create an account with name {string}, organization name {string} and email address {string}") public void iCreateAAccountWithNameOrganizationNameAndEmailaddress(String accountName, String organizationName, String email) throws Exception { - AccountCreator accountCreator = accountFactory.newCreator(getCurrentScopeId()); + AccountCreator accountCreator = new AccountCreator(getCurrentScopeId()); accountCreator.setName(accountName); accountCreator.setOrganizationName(organizationName); accountCreator.setOrganizationEmail(email); @@ -851,7 +814,7 @@ public void verifySelfAccount() throws Exception { public void iCreateAccountWithNameOrganizationNameAndEmailaddressAndChildAccount(String accountName, String organizationName, String email) throws Exception { Account lastAccount = (Account) stepData.get(LAST_ACCOUNT); - AccountCreator accountCreator = accountFactory.newCreator(lastAccount.getId()); + AccountCreator accountCreator = new AccountCreator(lastAccount.getId()); accountCreator.setName(accountName); accountCreator.setOrganizationName(organizationName); accountCreator.setOrganizationEmail(email); @@ -869,7 +832,7 @@ public void iCreateAccountWithNameOrganizationNameAndEmailaddressAndChildAccount @When("I query for all sub-accounts in {string}") public void queryForAllAccountsInCurrentScopeId(String accountName) throws Exception { Account tmpAccount = accountService.findByName(accountName); - AccountQuery query = accountFactory.newQuery(tmpAccount.getId()); + final KapuaQuery query = new KapuaQuery(tmpAccount.getId()); try { primeException(); AccountListResult accList = accountService.query(query); diff --git a/service/account/test/pom.xml b/service/account/test/pom.xml index 15ba53d53b1..5a6062c6691 100644 --- a/service/account/test/pom.xml +++ b/service/account/test/pom.xml @@ -20,7 +20,7 @@ org.eclipse.kapua kapua-account - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-account-test diff --git a/service/account/test/src/test/java/org/eclipse/kapua/service/account/test/AccountLocatorConfiguration.java b/service/account/test/src/test/java/org/eclipse/kapua/service/account/test/AccountLocatorConfiguration.java index ae892f2e608..25615319df4 100644 --- a/service/account/test/src/test/java/org/eclipse/kapua/service/account/test/AccountLocatorConfiguration.java +++ b/service/account/test/src/test/java/org/eclipse/kapua/service/account/test/AccountLocatorConfiguration.java @@ -30,13 +30,11 @@ import org.eclipse.kapua.commons.metric.MetricsServiceImpl; import org.eclipse.kapua.commons.model.domains.Domains; import org.eclipse.kapua.commons.model.mappers.KapuaBaseMapperImpl; -import org.eclipse.kapua.commons.model.query.QueryFactoryImpl; import org.eclipse.kapua.commons.service.event.store.internal.EventStoreRecordImplJpaRepository; import org.eclipse.kapua.commons.service.internal.cache.CacheManagerProvider; import org.eclipse.kapua.commons.setting.system.SystemSetting; import org.eclipse.kapua.commons.util.xml.XmlUtil; import org.eclipse.kapua.locator.KapuaLocator; -import org.eclipse.kapua.model.query.QueryFactory; import org.eclipse.kapua.qa.common.MockedLocator; import org.eclipse.kapua.qa.common.TestJAXBContextProvider; import org.eclipse.kapua.service.account.AccountFactory; @@ -52,7 +50,6 @@ import org.eclipse.kapua.service.authorization.AuthorizationService; import org.eclipse.kapua.service.authorization.domain.DomainRegistryService; import org.eclipse.kapua.service.authorization.permission.Permission; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; import org.eclipse.kapua.storage.TxManager; import org.mockito.Matchers; import org.mockito.Mockito; @@ -99,19 +96,15 @@ protected void configure() { } catch (KapuaException e) { // skip } + try { + Mockito.when(mockedAuthorization.isPermitted(Matchers.any(Permission.class))).thenReturn(true); + } catch (KapuaException e) { + // skip + } - bind(QueryFactory.class).toInstance(new QueryFactoryImpl()); bind(KapuaJpaRepositoryConfiguration.class).toInstance(new KapuaJpaRepositoryConfiguration()); bind(AuthorizationService.class).toInstance(mockedAuthorization); - // Inject mocked Permission Factory - final PermissionFactory mockPermissionFactory = Mockito.mock(PermissionFactory.class); - try { - Mockito.when(mockedAuthorization.isPermitted(Mockito.any(Permission.class))).thenReturn(true); - } catch (KapuaException e) { - throw new RuntimeException(e); - } - bind(PermissionFactory.class).toInstance(mockPermissionFactory); // Inject actual account related services // final AccountEntityManagerFactory entityManagerFactory = AccountEntityManagerFactory.getInstance(); // bind(AccountEntityManagerFactory.class).toInstance(entityManagerFactory); @@ -125,7 +118,6 @@ protected void configure() { bind(AccountService.class).toInstance(new AccountServiceImpl( txManager, new AccountImplJpaRepository(jpaRepoConfig), - mockPermissionFactory, mockedAuthorization, new ResourceLimitedServiceConfigurationManagerImpl( AccountService.class.getName(), @@ -135,7 +127,6 @@ protected void configure() { Mockito.mock(RootUserTester.class), Mockito.mock(AccountRelativeFinder.class), new UsedEntitiesCounterImpl( - accountFactory, accountRepository), new ResourceBasedServiceConfigurationMetadataProvider(new XmlUtil(new TestJAXBContextProvider())) ), diff --git a/service/account/test/src/test/resources/features/AccountService.feature b/service/account/test/src/test/resources/features/AccountService.feature index e16faf11154..a7dc2131154 100644 --- a/service/account/test/src/test/resources/features/AccountService.feature +++ b/service/account/test/src/test/resources/features/AccountService.feature @@ -125,21 +125,6 @@ Feature: User Account Service When I delete a random account Then An exception was thrown - Scenario: Check account properties - It must be possible to set arbitrary account properties. - - Given I create a generic account with name "test_acc_11" - When I set the following parameters - | name | value | - | key1 | value1 | - | key2 | value2 | - | key3 | value3 | - Then The account has the following parameters - | name | value | - | key1 | value1 | - | key2 | value2 | - | key3 | value3 | - Scenario: Every account must have the default configuration items Create a new account and check whether it has the default configuration items set. diff --git a/service/api/pom.xml b/service/api/pom.xml index a22320ea2fc..445f79d5e8f 100644 --- a/service/api/pom.xml +++ b/service/api/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-service - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-service-api diff --git a/commons/src/main/java/org/eclipse/kapua/commons/util/PropertiesUtils.java b/service/api/src/main/java/org/eclipse/kapua/PropertiesUtils.java similarity index 76% rename from commons/src/main/java/org/eclipse/kapua/commons/util/PropertiesUtils.java rename to service/api/src/main/java/org/eclipse/kapua/PropertiesUtils.java index 7c96c21ff24..ef9d1efcde3 100644 --- a/commons/src/main/java/org/eclipse/kapua/commons/util/PropertiesUtils.java +++ b/service/api/src/main/java/org/eclipse/kapua/PropertiesUtils.java @@ -10,10 +10,7 @@ * Contributors: * Eurotech - initial API and implementation *******************************************************************************/ -package org.eclipse.kapua.commons.util; - -import com.google.common.base.Strings; -import org.checkerframework.checker.nullness.qual.Nullable; +package org.eclipse.kapua; import java.io.IOException; import java.io.Reader; @@ -22,6 +19,8 @@ import java.io.Writer; import java.util.Properties; +import com.google.common.base.Strings; + /** * Utilities around the Java {@link Properties} class. * @@ -35,13 +34,15 @@ private PropertiesUtils() { /** * Reads the given {@link String} and loads it into the returned {@link Properties}. * - * @param stringProperties The source {@link String} + * @param stringProperties + * The source {@link String} * @return The loaded {@link Properties} - * @throws IOException If the {@link String} is not properly formatted. + * @throws IOException + * If the {@link String} is not properly formatted. * @see Properties#load(Reader) * @since 1.1.0 */ - public static Properties readPropertiesFromString(@Nullable String stringProperties) throws IOException { + public static Properties readPropertiesFromString(String stringProperties) throws IOException { Properties props = new Properties(); if (!Strings.isNullOrEmpty(stringProperties)) { try (Reader reader = new StringReader(stringProperties)) { @@ -54,13 +55,15 @@ public static Properties readPropertiesFromString(@Nullable String stringPropert /** * Writes the given {@link Properties} into the returned {@link String} * - * @param properties The source {@link Properties} + * @param properties + * The source {@link Properties} * @return The written {@link Properties}. - * @throws IOException if error occurs while writing properties. + * @throws IOException + * if error occurs while writing properties. * @see Properties#store(Writer, String) * @since 1.1.0 */ - public static String writePropertiesToString(@Nullable Properties properties) throws IOException { + public static String writePropertiesToString(Properties properties) throws IOException { String stringProperties = null; if (properties != null) { try (Writer writer = new StringWriter()) { diff --git a/service/api/src/main/java/org/eclipse/kapua/model/KapuaEntityBase.java b/service/api/src/main/java/org/eclipse/kapua/model/KapuaEntityBase.java new file mode 100644 index 00000000000..6f9c00ed52e --- /dev/null +++ b/service/api/src/main/java/org/eclipse/kapua/model/KapuaEntityBase.java @@ -0,0 +1,114 @@ +/******************************************************************************* + * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Eurotech - initial API and implementation + *******************************************************************************/ +package org.eclipse.kapua.model; + +import java.util.Date; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; + +import org.eclipse.kapua.KapuaSerializable; +import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.id.KapuaIdAdapter; +import org.eclipse.kapua.model.xml.DateXmlAdapter; + +/** + * {@link KapuaEntityBase} definition. + *

    + * All the {@link KapuaEntityBase}s will be an extension of this entity. + * + * @since 1.0.0 + */ +@XmlType(propOrder = { + "id", + "scopeId", + "createdOn", + "createdBy" }) +public abstract class KapuaEntityBase implements KapuaSerializable { + + private KapuaId id; + private KapuaId scopeId; + private Date createdOn; + private KapuaId createdBy; + + /** + * Gets the unique {@link KapuaId} + * + * @return the unique {@link KapuaId} + * @since 1.0.0 + */ + @XmlElement(name = "id") + @XmlJavaTypeAdapter(KapuaIdAdapter.class) + public KapuaId getId() { + return id; + } + + /** + * Sets the unique {@link KapuaId} + * + * @param id + * the unique {@link KapuaId} + * @since 1.0.0 + */ + public void setId(KapuaId id) { + this.id = id; + } + + /** + * Gets the scope {@link KapuaId} + * + * @return the scope {@link KapuaId} + * @since 1.0.0 + */ + @XmlElement(name = "scopeId") + @XmlJavaTypeAdapter(KapuaIdAdapter.class) + public KapuaId getScopeId() { + return this.scopeId; + } + + /** + * Sets the scope {@link KapuaId} + * + * @param scopeId + * the scope {@link KapuaId} + * @since 1.0.0 + */ + public void setScopeId(KapuaId scopeId) { + this.scopeId = scopeId; + } + + /** + * Gets the creation date. + * + * @return the creation date. + * @since 1.0.0 + */ + @XmlElement(name = "createdOn") + @XmlJavaTypeAdapter(DateXmlAdapter.class) + public Date getCreatedOn() { + return this.createdOn; + } + + /** + * Gets the identity {@link KapuaId} who has created this {@link KapuaEntityBase} + * + * @return the identity {@link KapuaId} who has created this {@link KapuaEntityBase} + * @since 1.0.0 + */ + @XmlElement(name = "createdBy") + @XmlJavaTypeAdapter(KapuaIdAdapter.class) + public KapuaId getCreatedBy() { + return this.createdBy; + } +} diff --git a/service/api/src/main/java/org/eclipse/kapua/model/KapuaEntityCreator.java b/service/api/src/main/java/org/eclipse/kapua/model/KapuaEntityCreator.java index 82603baa642..ec1a1c80c2e 100644 --- a/service/api/src/main/java/org/eclipse/kapua/model/KapuaEntityCreator.java +++ b/service/api/src/main/java/org/eclipse/kapua/model/KapuaEntityCreator.java @@ -12,21 +12,33 @@ *******************************************************************************/ package org.eclipse.kapua.model; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.model.id.KapuaIdAdapter; - import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; +import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.id.KapuaIdAdapter; + /** * {@link KapuaEntityCreator} definition *

    * All the {@link KapuaEntityCreator} will be an extension of this. * - * @param entity type * @since 1.0.0 */ -public interface KapuaEntityCreator { +public abstract class KapuaEntityCreator { + + protected KapuaId scopeId; + + public KapuaEntityCreator() { + } + + public KapuaEntityCreator(KapuaId scopeId) { + this.scopeId = scopeId; + } + + protected KapuaEntityCreator(KapuaEntityCreator entityCreator) { + this(entityCreator.getScopeId()); + } /** * Gets the scope {@link KapuaId} @@ -36,13 +48,19 @@ public interface KapuaEntityCreator { */ @XmlElement(name = "scopeId") @XmlJavaTypeAdapter(KapuaIdAdapter.class) - KapuaId getScopeId(); + public KapuaId getScopeId() { + return scopeId; + } /** * Sets the scope {@link KapuaId} * - * @param scopeId the scope {@link KapuaId} + * @param scopeId + * the scope {@link KapuaId} * @since 1.0.0 */ - void setScopeId(KapuaId scopeId); + public void setScopeId(KapuaId scopeId) { + + this.scopeId = scopeId; + } } diff --git a/service/api/src/main/java/org/eclipse/kapua/model/KapuaEntityFactory.java b/service/api/src/main/java/org/eclipse/kapua/model/KapuaEntityFactory.java index 9ff2033129b..fceb7841a8a 100644 --- a/service/api/src/main/java/org/eclipse/kapua/model/KapuaEntityFactory.java +++ b/service/api/src/main/java/org/eclipse/kapua/model/KapuaEntityFactory.java @@ -14,61 +14,34 @@ import org.eclipse.kapua.KapuaEntityCloneException; import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.model.query.KapuaListResult; -import org.eclipse.kapua.model.query.KapuaQuery; /** * {@link KapuaEntityFactory} definition. * - * @param The {@link KapuaEntity} for which this {@link KapuaEntityFactory} is for. - * @param The {@link KapuaEntityCreator} for which this {@link KapuaEntityFactory} is for. - * @param The {@link KapuaQuery} for which this {@link KapuaEntityFactory} is for. - * @param The {@link KapuaListResult} for which this {@link KapuaEntityFactory} is for. + * @param + * The {@link KapuaEntity} for which this {@link KapuaEntityFactory} is for. * @since 1.0.0 */ -public interface KapuaEntityFactory, Q extends KapuaQuery, L extends KapuaListResult> extends KapuaObjectFactory { +public interface KapuaEntityFactory extends KapuaObjectFactory { /** * Instantiates a new {@link KapuaEntity}. * - * @param scopeId The scope {@link KapuaId} to be set in the {@link KapuaEntity} + * @param scopeId + * The scope {@link KapuaId} to be set in the {@link KapuaEntity} * @return The newly instantiated {@link KapuaEntity} * @since 1.0.0 */ E newEntity(KapuaId scopeId); - /** - * Instantiates a new {@link KapuaEntityCreator}. - * - * @param scopeId The scope {@link KapuaId} to be set in the {@link KapuaEntityCreator} - * @return The newly instantiated {@link KapuaEntityCreator} - * @since 1.0.0 - */ - C newCreator(KapuaId scopeId); - - /** - * Instantiates a new {@link KapuaQuery}. - * - * @param scopeId The scope {@link KapuaId} to be set in the {@link KapuaQuery} - * @return The newly instantiated {@link KapuaQuery} - * @since 1.0.0 - */ - Q newQuery(KapuaId scopeId); - - /** - * Instantiates a new {@link KapuaListResult}. - * - * @return The newly instantiated {@link KapuaListResult} - * @since 1.0.0 - */ - L newListResult(); - /** * Deeply clones the given {@link KapuaEntity}. * - * @param entity The {@link KapuaEntity} to be cloned. + * @param entity + * The {@link KapuaEntity} to be cloned. * @return A deep clone of the {@link KapuaEntity} - * @throws KapuaEntityCloneException When error occurs while cloning the {@link KapuaEntity} + * @throws KapuaEntityCloneException + * When error occurs while cloning the {@link KapuaEntity} * @since 1.1.0 */ E clone(E entity) throws KapuaEntityCloneException; diff --git a/service/api/src/main/java/org/eclipse/kapua/model/KapuaNamedEntityBase.java b/service/api/src/main/java/org/eclipse/kapua/model/KapuaNamedEntityBase.java new file mode 100644 index 00000000000..2d16742f123 --- /dev/null +++ b/service/api/src/main/java/org/eclipse/kapua/model/KapuaNamedEntityBase.java @@ -0,0 +1,81 @@ +/******************************************************************************* + * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Eurotech - initial API and implementation + *******************************************************************************/ +package org.eclipse.kapua.model; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlType; + +/** + * {@link KapuaNamedEntityBase} definition. + *

    + * The {@link KapuaNamedEntityBase} adds on top of the {@link KapuaUpdatableEntity} the following properties: + * + *

      + *
    • name
    • + *
    • description
    • + *
    + * + *
    + * + *

    + * Name + *

    + *

    + * The Name property is the unique name of the {@link KapuaEntity} in the scope. + *

    + * + *

    + * Description + *

    + *

    + * The Description property is the optional description of the {@link KapuaEntity}. + *

    + *
    + * + * @since 1.0.0 + */ +@XmlType(propOrder = { "name", "description" }) +public abstract class KapuaNamedEntityBase extends KapuaUpdatableEntityBase { + + private String name; + private String description; + + /** + * Gets the name of the {@link KapuaEntity} + * + * @return the name of the {@link KapuaEntity} + * @since 1.0.0 + */ + @XmlElement(name = "name") + public String getName() { + return this.name; + } + + /** + * Gets the description for the {@link KapuaEntity} + * + * @return the description of this {@link KapuaEntity} + * @since 1.1.0 + */ + public String getDescription() { + return this.description; + } + + public void setName(String name) { + this.name = name; + } + + public void setDescription(String description) { + this.description = description; + } +} diff --git a/service/api/src/main/java/org/eclipse/kapua/model/KapuaNamedEntityCreator.java b/service/api/src/main/java/org/eclipse/kapua/model/KapuaNamedEntityCreator.java index 841d83170ac..49b0aab1e6b 100644 --- a/service/api/src/main/java/org/eclipse/kapua/model/KapuaNamedEntityCreator.java +++ b/service/api/src/main/java/org/eclipse/kapua/model/KapuaNamedEntityCreator.java @@ -15,6 +15,8 @@ import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; +import org.eclipse.kapua.model.id.KapuaId; + /** * {@link KapuaNamedEntityCreator} definition. *

    @@ -41,11 +43,34 @@ *

    * * - * @param {@link KapuaEntity} which this {@link KapuaEntityCreator} is for * @since 1.0.0 */ -@XmlType(propOrder = {"name", "description"}) -public interface KapuaNamedEntityCreator extends KapuaUpdatableEntityCreator { +@XmlType(propOrder = { "name", "description" }) +public abstract class KapuaNamedEntityCreator extends KapuaUpdatableEntityCreator { + + protected String name; + protected String description; + + public KapuaNamedEntityCreator() { + } + + public KapuaNamedEntityCreator(KapuaId scopeId) { + super(scopeId); + } + + /** + * Constructor + * + * @param scopeId + * the scope {@link KapuaId} + * @param name + * the name + * @since 1.0.0 + */ + public KapuaNamedEntityCreator(KapuaId scopeId, String name) { + super(scopeId); + this.name = name; + } /** * Gets the name @@ -54,15 +79,20 @@ public interface KapuaNamedEntityCreator extends KapuaUpd * @since 1.0.0 */ @XmlElement(name = "name") - String getName(); + public String getName() { + return name; + } /** * Sets the name * - * @param name the name + * @param name + * the name * @since 1.0.0 */ - void setName(String name); + public void setName(String name) { + this.name = name; + } /** * Gets the description @@ -70,13 +100,18 @@ public interface KapuaNamedEntityCreator extends KapuaUpd * @return the description * @since 1.0.0 */ - String getDescription(); + public String getDescription() { + return description; + } /** * Sets the description * - * @param description the description + * @param description + * the description * @since 1.0.0 */ - void setDescription(String description); + public void setDescription(String description) { + this.description = description; + } } diff --git a/service/api/src/main/java/org/eclipse/kapua/model/KapuaUpdatableEntity.java b/service/api/src/main/java/org/eclipse/kapua/model/KapuaUpdatableEntity.java index 71007d9903b..e69e29cb365 100644 --- a/service/api/src/main/java/org/eclipse/kapua/model/KapuaUpdatableEntity.java +++ b/service/api/src/main/java/org/eclipse/kapua/model/KapuaUpdatableEntity.java @@ -12,18 +12,19 @@ *******************************************************************************/ package org.eclipse.kapua.model; -import org.eclipse.kapua.entity.EntityPropertiesReadException; -import org.eclipse.kapua.entity.EntityPropertiesWriteException; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.model.id.KapuaIdAdapter; -import org.eclipse.kapua.model.xml.DateXmlAdapter; +import java.util.Date; +import java.util.Properties; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlTransient; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; -import java.util.Date; -import java.util.Properties; + +import org.eclipse.kapua.entity.EntityPropertiesReadException; +import org.eclipse.kapua.entity.EntityPropertiesWriteException; +import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.id.KapuaIdAdapter; +import org.eclipse.kapua.model.xml.DateXmlAdapter; /** * {@link KapuaUpdatableEntity} definition. @@ -69,7 +70,8 @@ public interface KapuaUpdatableEntity extends KapuaEntity { /** * Sets the optlock * - * @param optlock the optlock + * @param optlock + * the optlock * @since 1.0.0 */ void setOptlock(int optlock); @@ -78,7 +80,8 @@ public interface KapuaUpdatableEntity extends KapuaEntity { * Gets the attributes * * @return the attributes - * @throws EntityPropertiesReadException If there are error while reading {@link Properties} + * @throws EntityPropertiesReadException + * If there are error while reading {@link Properties} */ @XmlTransient Properties getEntityAttributes() throws EntityPropertiesReadException; @@ -86,8 +89,10 @@ public interface KapuaUpdatableEntity extends KapuaEntity { /** * Sets the attributes * - * @param props the attributes - * @throws EntityPropertiesWriteException If there are error while writing {@link Properties} + * @param props + * the attributes + * @throws EntityPropertiesWriteException + * If there are error while writing {@link Properties} * @since 1.0.0 */ void setEntityAttributes(Properties props) throws EntityPropertiesWriteException; @@ -96,7 +101,8 @@ public interface KapuaUpdatableEntity extends KapuaEntity { * Gets the property entities * * @return the property entities - * @throws EntityPropertiesReadException If there are error while reading {@link Properties} + * @throws EntityPropertiesReadException + * If there are error while reading {@link Properties} * @since 1.0.0 */ @XmlTransient @@ -105,8 +111,10 @@ public interface KapuaUpdatableEntity extends KapuaEntity { /** * Sets the property entities * - * @param props the property entities - * @throws EntityPropertiesWriteException If there are error while writing {@link Properties} + * @param props + * the property entities + * @throws EntityPropertiesWriteException + * If there are error while writing {@link Properties} * @since 1.0.0 */ void setEntityProperties(Properties props) throws EntityPropertiesWriteException; diff --git a/service/api/src/main/java/org/eclipse/kapua/model/KapuaUpdatableEntityBase.java b/service/api/src/main/java/org/eclipse/kapua/model/KapuaUpdatableEntityBase.java new file mode 100644 index 00000000000..d324b6c6969 --- /dev/null +++ b/service/api/src/main/java/org/eclipse/kapua/model/KapuaUpdatableEntityBase.java @@ -0,0 +1,87 @@ +/******************************************************************************* + * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Eurotech - initial API and implementation + *******************************************************************************/ +package org.eclipse.kapua.model; + +import java.util.Date; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; + +import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.id.KapuaIdAdapter; +import org.eclipse.kapua.model.xml.DateXmlAdapter; + +/** + * {@link KapuaUpdatableEntityBase} definition. + * + * @since 1.0.0 + */ +@XmlType(propOrder = { + "modifiedOn", + "modifiedBy", + "optlock" +}) +public abstract class KapuaUpdatableEntityBase extends KapuaEntityBase { + + private Date modifiedOn; + private KapuaId modifiedBy; + private int optLock; + + /** + * Gets the last date that this {@link KapuaEntity} has been updated. + * + * @return the last date that this {@link KapuaEntity} has been updated. + * @since 1.0.0 + */ + @XmlElement(name = "modifiedOn") + @XmlJavaTypeAdapter(DateXmlAdapter.class) + public Date getModifiedOn() { + return this.modifiedOn; + } + + /** + * Get the last identity {@link KapuaId} that has updated this {@link KapuaEntity} + * + * @return the last identity {@link KapuaId} that has updated this {@link KapuaEntity} + * @since 1.0.0 + */ + @XmlElement(name = "modifiedBy") + @XmlJavaTypeAdapter(KapuaIdAdapter.class) + public KapuaId getModifiedBy() { + return this.modifiedBy; + } + + /** + * Gets the optlock + * + * @return the optlock + * @since 1.0.0 + */ + @XmlElement(name = "optlock") + public int getOptlock() { + return this.optLock; + } + + public void setModifiedOn(Date modifiedOn) { + this.modifiedOn = modifiedOn; + } + + public void setModifiedBy(KapuaId modifiedBy) { + this.modifiedBy = modifiedBy; + } + + public void setOptlock(int optLock) { + this.optLock = optLock; + } +} diff --git a/service/api/src/main/java/org/eclipse/kapua/model/KapuaUpdatableEntityCreator.java b/service/api/src/main/java/org/eclipse/kapua/model/KapuaUpdatableEntityCreator.java index 8d2fa3c5335..a73a3b0e08f 100644 --- a/service/api/src/main/java/org/eclipse/kapua/model/KapuaUpdatableEntityCreator.java +++ b/service/api/src/main/java/org/eclipse/kapua/model/KapuaUpdatableEntityCreator.java @@ -12,21 +12,50 @@ *******************************************************************************/ package org.eclipse.kapua.model; -import org.eclipse.kapua.KapuaException; +import java.io.IOException; +import java.util.Properties; import javax.xml.bind.annotation.XmlTransient; -import java.util.Properties; + +import org.eclipse.kapua.PropertiesUtils; +import org.eclipse.kapua.entity.EntityPropertiesReadException; +import org.eclipse.kapua.entity.EntityPropertiesWriteException; +import org.eclipse.kapua.model.id.KapuaId; /** * {@link KapuaUpdatableEntityCreator} definition. * - * @param entity type * @since 1.0.0 */ -public interface KapuaUpdatableEntityCreator extends KapuaEntityCreator { +public abstract class KapuaUpdatableEntityCreator extends KapuaEntityCreator { + + protected String attributes; + + public KapuaUpdatableEntityCreator() { + } + + public KapuaUpdatableEntityCreator(KapuaId scopeId) { + super(scopeId); + } + + protected KapuaUpdatableEntityCreator(KapuaEntityCreator entityCreator) { + super(entityCreator); + } @XmlTransient - Properties getEntityAttributes() throws KapuaException; + public Properties getEntityAttributes() { + try { + return PropertiesUtils.readPropertiesFromString(attributes); + } catch (IOException e) { + throw new EntityPropertiesReadException(e, "attributes", attributes); + } + } - void setEntityAttributes(Properties entityAttributes) throws KapuaException; + public void setEntityAttributes(Properties attributes) { + try { + this.attributes = PropertiesUtils.writePropertiesToString(attributes); + } catch (IOException e) { + throw new EntityPropertiesWriteException(e, "attributes", attributes); + } + } } diff --git a/service/api/src/main/java/org/eclipse/kapua/model/config/metatype/EmptyTocd.java b/service/api/src/main/java/org/eclipse/kapua/model/config/metatype/EmptyTocd.java deleted file mode 100644 index d403fafee0d..00000000000 --- a/service/api/src/main/java/org/eclipse/kapua/model/config/metatype/EmptyTocd.java +++ /dev/null @@ -1,103 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2019, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.model.config.metatype; - -import java.util.Collections; -import java.util.List; -import java.util.Map; - -import javax.xml.namespace.QName; - -public class EmptyTocd extends KapuaTocd { - - private String id; - private String name; - - public EmptyTocd() { - } - - public EmptyTocd(String id, String name) { - this.id = id; - this.name = name; - } - - @Override - public void setOtherAttributes(Map otherAttributes) { - // No OP implementation - } - - @Override - public void setName(String name) { - this.name = name; - } - - @Override - public void setId(String id) { - this.id = id; - } - - @Override - public void setIcon(List icon) { - // No OP implementation - } - - @Override - public void setDescription(String value) { - // No OP implementation - } - - @Override - public void setAny(List any) { - // No OP implementation - } - - @Override - public void setAD(List icon) { - // No OP implementation - } - - @Override - public Map getOtherAttributes() { - return Collections.emptyMap(); - } - - @Override - public String getName() { - return name; - } - - @Override - public String getId() { - return id; - } - - @Override - public List getIcon() { - return Collections.emptyList(); - } - - @Override - public String getDescription() { - return null; - } - - @Override - public List getAny() { - return Collections.emptyList(); - } - - @Override - public List getAD() { - return Collections.emptyList(); - } -} diff --git a/service/api/src/main/java/org/eclipse/kapua/model/config/metatype/KapuaTad.java b/service/api/src/main/java/org/eclipse/kapua/model/config/metatype/KapuaTad.java index 097f0ac1d26..7118a71bb28 100644 --- a/service/api/src/main/java/org/eclipse/kapua/model/config/metatype/KapuaTad.java +++ b/service/api/src/main/java/org/eclipse/kapua/model/config/metatype/KapuaTad.java @@ -20,6 +20,7 @@ import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAnyAttribute; +import javax.xml.bind.annotation.XmlAnyElement; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @@ -60,9 +61,13 @@ */ @XmlRootElement(name = "AD", namespace = "http://www.osgi.org/xmlns/metatype/v1.2.0") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(name = "Tad", propOrder = { +@XmlType(name = "Tad" + , propOrder = { + "id", + "type", "option", - "any" + "any", + "required" }) public class KapuaTad { @@ -133,6 +138,7 @@ public void setOption(List option) { * *

    */ + @XmlAnyElement(lax = true) public List getAny() { if (any == null) { any = new ArrayList(); @@ -351,5 +357,4 @@ public void putOtherAttribute(QName key, String value) { getOtherAttributes().put(key, value); } - } diff --git a/service/api/src/main/java/org/eclipse/kapua/model/config/metatype/KapuaTobject.java b/service/api/src/main/java/org/eclipse/kapua/model/config/metatype/KapuaTobject.java index 316add12964..68121d319a4 100644 --- a/service/api/src/main/java/org/eclipse/kapua/model/config/metatype/KapuaTobject.java +++ b/service/api/src/main/java/org/eclipse/kapua/model/config/metatype/KapuaTobject.java @@ -135,5 +135,4 @@ public void setOcdref(String value) { public Map getOtherAttributes() { return otherAttributes; } - } diff --git a/service/api/src/main/java/org/eclipse/kapua/model/config/metatype/KapuaTocd.java b/service/api/src/main/java/org/eclipse/kapua/model/config/metatype/KapuaTocd.java index 908d912a5c0..f887ada54b9 100644 --- a/service/api/src/main/java/org/eclipse/kapua/model/config/metatype/KapuaTocd.java +++ b/service/api/src/main/java/org/eclipse/kapua/model/config/metatype/KapuaTocd.java @@ -57,16 +57,47 @@ */ @XmlRootElement(name = "OCD", namespace = "http://www.osgi.org/xmlns/metatype/v1.2.0") @XmlAccessorType(XmlAccessType.PROPERTY) + @XmlType public class KapuaTocd { + private String id; + private String name; protected List ad; protected List icon; protected List any; - protected String name; protected String description; - protected String id; private Map otherAttributes = new HashMap<>(); + private boolean empty; + + public KapuaTocd() { + this.empty = false; + } + + public static KapuaTocd empty(String id, String name) { + KapuaTocd toc = new KapuaTocd(); + toc.empty = true; + toc.id = id; + toc.name = name; + return toc; + } + + public static KapuaTocd empty() { + KapuaTocd toc = new KapuaTocd(); + toc.empty = true; + toc.id = null; + toc.name = null; + return toc; + } + + public boolean isEmpty() { + return empty; + } + + public KapuaTocd setEmpty(boolean empty) { + this.empty = empty; + return this; + } /** * Gets the value of the ad property. @@ -87,7 +118,6 @@ public class KapuaTocd { * Objects of the following type(s) are allowed in the list {@link KapuaTad } */ @XmlElement(name = "AD", namespace = "http://www.osgi.org/xmlns/metatype/v1.2.0", required = true) - public List getAD() { if (ad == null) { ad = new ArrayList<>(); @@ -100,37 +130,31 @@ public void setAD(List ad) { } /** - * Gets the value of the icon property. - *

    - * This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you make to the returned list will be present inside the JAXB object. This is why there is - * not a set method for the icon property. - *

    - * For example, to add a new item, do as follows: + * Add Tad to the internal list * - *

    -     * getIcon().add(newItem);
    -     * 
    + * @param ad */ - @XmlElement(name = "Icon", namespace = "http://www.osgi.org/xmlns/metatype/v1.2.0") + public void addAD(KapuaTad ad) { + if (this.ad == null) { + this.ad = new ArrayList<>(); + } + + this.ad.add(ad); + } /** * Gets the value of the icon property. *

    - *

    * This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you make to the returned list will be present inside the JAXB object. This is why there is * not a set method for the icon property. *

    - *

    * For example, to add a new item, do as follows: - *

    + * *

          * getIcon().add(newItem);
          * 
    - *

    - *

    - *

    - * Objects of the following type(s) are allowed in the list {@link TiconImpl } */ + @XmlElement(name = "Icon", namespace = "http://www.osgi.org/xmlns/metatype/v1.2.0") public List getIcon() { if (icon == null) { icon = new ArrayList<>(); @@ -157,19 +181,15 @@ public void addIcon(KapuaTicon icon) { /** * Gets the value of the any property. *

    - *

    * This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you make to the returned list will be present inside the JAXB object. This is why there is * not a set method for the any property. *

    - *

    * For example, to add a new item, do as follows: *

    *

          * getAny().add(newItem);
          * 
    *

    - *

    - *

    * Objects of the following type(s) are allowed in the list {@link Element } {@link Object } */ @XmlAnyElement(lax = true) @@ -181,9 +201,21 @@ public List getAny() { } public void setAny(List any) { + if (this.empty) { + return; + } this.any = any; } + /** + * Add a generic object to the internal list + * + * @param object + */ + public void addAny(Object object) { + getAny().add(object); + } + /** * Gets the value of the name property. * @@ -221,6 +253,9 @@ public String getDescription() { * allowed object is {@link String } */ public void setDescription(String value) { + if (this.empty) { + return; + } this.description = value; } @@ -255,11 +290,10 @@ public void setId(String value) { */ @XmlAnyAttribute public Map getOtherAttributes() { - return otherAttributes; - } - - public void setOtherAttributes(Map otherAttributes) { - this.otherAttributes = otherAttributes; + if (this.otherAttributes == null) { + this.otherAttributes = new HashMap<>(); + } + return this.otherAttributes; } /** @@ -273,26 +307,8 @@ public void putOtherAttribute(QName key, String value) { value); } - /** - * Add Tad to the internal list - * - * @param ad - */ - public void addAD(KapuaTad ad) { - if (this.ad == null) { - this.ad = new ArrayList<>(); - } - - this.ad.add(ad); - } - - /** - * Add a generic object to the internal list - * - * @param object - */ - public void addAny(Object object) { - getAny().add(object); + public void setOtherAttributes(Map otherAttributes) { + this.otherAttributes = otherAttributes; } } diff --git a/service/api/src/main/java/org/eclipse/kapua/model/config/metatype/KapuaTscalar.java b/service/api/src/main/java/org/eclipse/kapua/model/config/metatype/KapuaTscalar.java index 8e6d1b5b09b..64145991635 100644 --- a/service/api/src/main/java/org/eclipse/kapua/model/config/metatype/KapuaTscalar.java +++ b/service/api/src/main/java/org/eclipse/kapua/model/config/metatype/KapuaTscalar.java @@ -85,6 +85,7 @@ public enum KapuaTscalar { * * @return possible object is {@link String } with restricted values */ + public String value() { return value; } diff --git a/service/api/src/main/java/org/eclipse/kapua/model/domain/Actions.java b/service/api/src/main/java/org/eclipse/kapua/model/domain/Actions.java index 480fb8ea560..ba95d84737d 100644 --- a/service/api/src/main/java/org/eclipse/kapua/model/domain/Actions.java +++ b/service/api/src/main/java/org/eclipse/kapua/model/domain/Actions.java @@ -13,7 +13,6 @@ package org.eclipse.kapua.model.domain; import org.eclipse.kapua.model.KapuaEntityCreator; -import org.eclipse.kapua.model.KapuaUpdatableEntity; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.service.KapuaEntityService; @@ -21,8 +20,7 @@ import org.eclipse.kapua.service.KapuaUpdatableEntityService; /** - * {@link Actions} implementation {@code enum}.
    - * Available actions defined are: + * {@link Actions} implementation {@code enum}.
    Available actions defined are: *
      *
    • {@link Actions#read}: Represent any type of fetching data from the system.
    • *
    • {@link Actions#write}: Represent any type of writing data into the system.
    • @@ -35,8 +33,7 @@ */ public enum Actions { /** - * Represent any type of fetching data from the system.
      - * Common usage is on: + * Represent any type of fetching data from the system.
      Common usage is on: *
        *
      • {@link KapuaEntityService#find(KapuaId, KapuaId)}
      • *
      • {@link KapuaEntityService#query(KapuaQuery)}
      • @@ -49,11 +46,10 @@ public enum Actions { read, /** - * Represent any type of writing data into the system. - * Common usage is on: + * Represent any type of writing data into the system. Common usage is on: *
          *
        • {@link KapuaEntityService#create(KapuaEntityCreator)}
        • - *
        • {@link KapuaUpdatableEntityService#update(KapuaUpdatableEntity)}
        • + *
        • {@link KapuaUpdatableEntityService#update(Object)}
        • *
        * * @since 1.0.0 @@ -61,8 +57,7 @@ public enum Actions { write, /** - * Represent any type of deleting data from the system.
        - * Common usage is on: + * Represent any type of deleting data from the system.
        Common usage is on: *
          *
        • {@link KapuaEntityService#delete(KapuaId, KapuaId)}
        • *
        @@ -72,8 +67,7 @@ public enum Actions { delete, /** - * Represent any type of connect to resources of the system.
        - * Examples are: + * Represent any type of connect to resources of the system.
        Examples are: *
          *
        • Connecting to the message broker.
        • *
        diff --git a/commons/src/main/java/org/eclipse/kapua/commons/model/query/AbstractKapuaNamedQuery.java b/service/api/src/main/java/org/eclipse/kapua/model/query/AbstractKapuaNamedQuery.java similarity index 78% rename from commons/src/main/java/org/eclipse/kapua/commons/model/query/AbstractKapuaNamedQuery.java rename to service/api/src/main/java/org/eclipse/kapua/model/query/AbstractKapuaNamedQuery.java index 28e7625a6c6..a4b09504c85 100644 --- a/commons/src/main/java/org/eclipse/kapua/commons/model/query/AbstractKapuaNamedQuery.java +++ b/service/api/src/main/java/org/eclipse/kapua/model/query/AbstractKapuaNamedQuery.java @@ -10,14 +10,11 @@ * Contributors: * Eurotech - initial API and implementation *******************************************************************************/ -package org.eclipse.kapua.commons.model.query; +package org.eclipse.kapua.model.query; import org.eclipse.kapua.model.KapuaNamedEntity; import org.eclipse.kapua.model.KapuaNamedEntityAttributes; import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.model.query.KapuaQuery; -import org.eclipse.kapua.model.query.KapuaSortCriteria; -import org.eclipse.kapua.model.query.SortOrder; /** * {@link KapuaQuery} {@code abstract} implementation for {@link KapuaNamedEntity}. @@ -26,7 +23,7 @@ * * @since 1.5.0 */ -public abstract class AbstractKapuaNamedQuery extends AbstractKapuaQuery implements KapuaQuery { +public abstract class AbstractKapuaNamedQuery extends KapuaQuery { /** * Constructor. @@ -40,7 +37,8 @@ public AbstractKapuaNamedQuery() { /** * Constructor. * - * @param scopeId The {@link #getScopeId()}. + * @param scopeId + * The {@link #getScopeId()}. * @since 1.5.0 */ public AbstractKapuaNamedQuery(KapuaId scopeId) { @@ -50,7 +48,8 @@ public AbstractKapuaNamedQuery(KapuaId scopeId) { /** * Clone constructor. * - * @param query The {@link KapuaQuery} to clone. + * @param query + * The {@link KapuaQuery} to clone. * @since 1.5.0 */ public AbstractKapuaNamedQuery(KapuaQuery query) { diff --git a/service/api/src/main/java/org/eclipse/kapua/model/query/FieldSortCriteria.java b/service/api/src/main/java/org/eclipse/kapua/model/query/FieldSortCriteria.java index 1568189ac3a..be8c7a5cdec 100644 --- a/service/api/src/main/java/org/eclipse/kapua/model/query/FieldSortCriteria.java +++ b/service/api/src/main/java/org/eclipse/kapua/model/query/FieldSortCriteria.java @@ -12,18 +12,44 @@ *******************************************************************************/ package org.eclipse.kapua.model.query; -public interface FieldSortCriteria extends KapuaSortCriteria{ +public class FieldSortCriteria implements KapuaSortCriteria { + + /** + * Field attribute name + */ + private String attributeName; + + /** + * Field sort order + */ + private SortOrder sortOrder; + + /** + * Constructor + * + * @param attributeName + * @param sortOrder + */ + public FieldSortCriteria(String attributeName, SortOrder sortOrder) { + this.attributeName = attributeName; + this.sortOrder = sortOrder; + } + /** * Get the sort attribute name * * @return */ - public String getAttributeName(); + public String getAttributeName() { + return attributeName; + } /** * Get the sort attribute order * * @return */ - public SortOrder getSortOrder(); + public SortOrder getSortOrder() { + return sortOrder; + } } diff --git a/service/api/src/main/java/org/eclipse/kapua/model/query/KapuaForwardableEntityQuery.java b/service/api/src/main/java/org/eclipse/kapua/model/query/KapuaForwardableEntityQuery.java index 7208cacb780..60803198d63 100644 --- a/service/api/src/main/java/org/eclipse/kapua/model/query/KapuaForwardableEntityQuery.java +++ b/service/api/src/main/java/org/eclipse/kapua/model/query/KapuaForwardableEntityQuery.java @@ -14,7 +14,42 @@ import javax.xml.bind.annotation.XmlElement; -public interface KapuaForwardableEntityQuery extends KapuaQuery { +import org.eclipse.kapua.model.id.KapuaId; + +public class KapuaForwardableEntityQuery extends KapuaQuery { + + protected Boolean includeInherited = Boolean.FALSE; + + /** + * Constructor. + */ + public KapuaForwardableEntityQuery() { + super(); + } + + /** + * Constructor. + * + * @param scopeId + * The {@link #getScopeId()}. + */ + public KapuaForwardableEntityQuery(KapuaId scopeId) { + super(scopeId); + } + + /** + * Clone constructor. + * + * @param query + * The {@link KapuaForwardableEntityQuery} to clone. + */ + public KapuaForwardableEntityQuery(KapuaQuery query) { + super(query); + if (query instanceof KapuaForwardableEntityQuery) { + this.includeInherited = ((KapuaForwardableEntityQuery) query).getIncludeInherited(); + } + } + /** * Gets whether to query for inherited entities * @@ -22,14 +57,18 @@ public interface KapuaForwardableEntityQuery extends KapuaQuery { * @since 2.0.0 */ @XmlElement(name = "includeInherited") - Boolean getIncludeInherited(); + public Boolean getIncludeInherited() { + return includeInherited; + } /** * Sets whether to query for inherited entities * - * @param includeInherited {@code true} to query for inherited entities, {@code false} otherwise. + * @param includeInherited + * {@code true} to query for inherited entities, {@code false} otherwise. * @since 2.0.0 */ - void setIncludeInherited(Boolean includeInherited); - + public void setIncludeInherited(Boolean includeInherited) { + this.includeInherited = includeInherited; + } } diff --git a/service/api/src/main/java/org/eclipse/kapua/model/query/KapuaListResult.java b/service/api/src/main/java/org/eclipse/kapua/model/query/KapuaListResult.java index c014ef1da7f..d7ae78aa007 100644 --- a/service/api/src/main/java/org/eclipse/kapua/model/query/KapuaListResult.java +++ b/service/api/src/main/java/org/eclipse/kapua/model/query/KapuaListResult.java @@ -12,55 +12,78 @@ *******************************************************************************/ package org.eclipse.kapua.model.query; -import org.eclipse.kapua.KapuaSerializable; -import org.eclipse.kapua.model.KapuaEntity; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.stream.Collectors; -import javax.validation.constraints.NotNull; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; -import java.util.Collection; -import java.util.Comparator; -import java.util.List; -import java.util.Map; -import java.util.function.Function; -import java.util.function.Predicate; + +import org.eclipse.kapua.KapuaSerializable; +import org.eclipse.kapua.model.KapuaEntity; /** * {@link KapuaListResult} definition. * - * @param {@link KapuaEntity} type. + * @param + * {@link KapuaEntity} type. * @since 1.0.0 */ @XmlRootElement(name = "result") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(propOrder = {"limitExceeded", "size", "items", "totalCount"}) -public interface KapuaListResult extends KapuaSerializable { +@XmlType(propOrder = { "limitExceeded", "size", "items", "totalCount" }) +public class KapuaListResult implements KapuaSerializable { + + private static final long serialVersionUID = 8939666089540269261L; + + protected ArrayList items; + protected boolean limitExceeded; + protected Long totalCount; + + /** + * Constructor. + * + * @since 1.0.0 + */ + public KapuaListResult() { + limitExceeded = false; + } /** * Gets the limit exceeded flag. *

        - * This flag is {@code true} if there are more results that exceded the {@link KapuaQuery#getLimit()}. - * Increasing the {@link KapuaQuery#getLimit()} or moving the {@link KapuaQuery#getOffset()} will return more results + * This flag is {@code true} if there are more results that exceded the {@link KapuaQuery#getLimit()}. Increasing the {@link KapuaQuery#getLimit()} or moving the {@link KapuaQuery#getOffset()} + * will return more results * * @return The limit exceeded flag * @since 1.0.0 */ @XmlElement(name = "limitExceeded") - boolean isLimitExceeded(); + public boolean isLimitExceeded() { + return limitExceeded; + } /** * Sets the limit exceeded flag. *

        * To be set to {@code true} if the {@link KapuaQuery} matching elements are more than {@link KapuaQuery#getLimit()}. * - * @param limitExceeded The limit exceeded flag. + * @param limitExceeded + * The limit exceeded flag. * @since 1.0.0 */ - void setLimitExceeded(boolean limitExceeded); + public void setLimitExceeded(boolean limitExceeded) { + this.limitExceeded = limitExceeded; + } /** * Gets the {@link KapuaEntity}s that matched the {@link KapuaQuery#getPredicate()}. @@ -72,55 +95,77 @@ public interface KapuaListResult extends KapuaSerializabl */ @XmlElementWrapper(name = "items") @XmlElement(name = "item") - List getItems(); + public List getItems() { + if (items == null) { + items = new ArrayList<>(); + } + + return items; + } /** * Gets the {@link KapuaEntity}s that matched the {@link KapuaQuery#getPredicate()} and applies even more filtering. *

        * This is meant to be used to filter result when is not possible to do so with {@link KapuaQuery#getPredicate()}s. * - * @param filter The filter to apply to select results. + * @param filter + * The filter to apply to select results. * @return The filtered {@link KapuaEntity}s that matched the {@link KapuaQuery#getPredicate()}. * @since 2.0.0 */ - List getItems(@NotNull Predicate filter); + public List getItems(Predicate filter) { + return getItems().stream().filter(filter).collect(Collectors.toList()); + } /** - * Gets a {@link Map} whose {@link Map#keySet()} are generated from the given {@link Map.Entry#getKey()} mapper {@link Function}. - * The {@link Map#values()} are the {@link KapuaEntity}s themself. + * Gets a {@link Map} whose {@link Map#keySet()} are generated from the given {@link Map.Entry#getKey()} mapper {@link Function}. The {@link Map#values()} are the {@link KapuaEntity}s themself. *

        * This is like invoking {@link #getItemsAsMap(Function, Function)} whose value mapper returns the {@link KapuaEntity} itself. * - * @param keyMapper The {@link Function} which defines the {@link Map.Entry#getKey()} for each {@link Map.Entry} - * @param The type of the {@link Map.Entry#getKey()} + * @param keyMapper + * The {@link Function} which defines the {@link Map.Entry#getKey()} for each {@link Map.Entry} + * @param + * The type of the {@link Map.Entry#getKey()} * @return The {@link Map} generated according to the mapping {@link Map.Entry#getKey()} {@link Function}. * @since 2.0.0 */ - Map getItemsAsMap(@NotNull Function keyMapper); + public Map getItemsAsMap(Function keyMapper) { + return getItems().stream().collect(Collectors.toMap(keyMapper, e -> e)); + } /** - * Gets a {@link Map} whose {@link Map#keySet()} are generated from the given {@link Map.Entry#getKey()} mapper {@link Function}. - * The {@link Map#values()} are generated from the given {@link Map.Entry#getValue()} mapper {@link Function}. + * Gets a {@link Map} whose {@link Map#keySet()} are generated from the given {@link Map.Entry#getKey()} mapper {@link Function}. The {@link Map#values()} are generated from the given + * {@link Map.Entry#getValue()} mapper {@link Function}. * - * @param keyMapper The {@link Function} which defines the {@link Map.Entry#getKey()} for each {@link Map.Entry} - * @param valueMapper The {@link Function} which defines the {@link Map.Entry#getValue()} for each {@link Map.Entry} - * @param The type of the {@link Map.Entry#getKey()} - * @param The type of the {@link Map.Entry#getValue()} + * @param keyMapper + * The {@link Function} which defines the {@link Map.Entry#getKey()} for each {@link Map.Entry} + * @param valueMapper + * The {@link Function} which defines the {@link Map.Entry#getValue()} for each {@link Map.Entry} + * @param + * The type of the {@link Map.Entry#getKey()} + * @param + * The type of the {@link Map.Entry#getValue()} * @return The {@link Map} generated according to the mapping {@link Function}s. * @since 2.0.0 */ - Map getItemsAsMap(@NotNull Function keyMapper, @NotNull Function valueMapper); + public Map getItemsAsMap(Function keyMapper, Function valueMapper) { + return getItems().stream().collect(Collectors.toMap(keyMapper, valueMapper)); + } /** * Gets the {@link KapuaEntity} at the given position in the {@link KapuaListResult}. * - * @param i The position in the {@link KapuaListResult} + * @param index + * The position in the {@link KapuaListResult} * @return The {@link KapuaEntity} at the position - * @throws IndexOutOfBoundsException If position is not available. + * @throws IndexOutOfBoundsException + * If position is not available. * @see List#get(int) * @since 1.0.0 */ - E getItem(int i); + public E getItem(int index) { + return getItems().get(index); + } /** * Gets the first {@link KapuaEntity} in the {@link KapuaListResult}. @@ -130,7 +175,9 @@ public interface KapuaListResult extends KapuaSerializabl * @return The first element in the {@link KapuaListResult} or {@code null} if not present. * @since 1.0.0 */ - E getFirstItem(); + public E getFirstItem() { + return this.isEmpty() ? null : getItem(0); + } /** * Gets the result {@link KapuaListResult} size @@ -140,7 +187,9 @@ public interface KapuaListResult extends KapuaSerializabl * @since 1.0.0 */ @XmlElement(name = "size") - int getSize(); + public int getSize() { + return getItems().size(); + } /** * Checks if the result {@link KapuaListResult} is empty @@ -149,23 +198,31 @@ public interface KapuaListResult extends KapuaSerializabl * @see List#isEmpty() * @since 1.0.0 */ - boolean isEmpty(); + public boolean isEmpty() { + return getItems().isEmpty(); + } /** * Adds {@link KapuaEntity}s to the result {@link KapuaListResult} * - * @param items The {@link KapuaEntity}s to add. + * @param items + * The {@link KapuaEntity}s to add. * @see List#addAll(Collection) * @since 1.0.0 */ - void addItems(@NotNull Collection items); + public void addItems(Collection items) { + getItems().addAll(items); + } /** * Adds a {@link KapuaEntity} to the {@link KapuaListResult}. * - * @param item The {@link KapuaEntity} to add. + * @param item + * The {@link KapuaEntity} to add. */ - void addItem(@NotNull E item); + public void addItem(E item) { + getItems().add(item); + } /** * Clears {@link KapuaEntity} result {@link KapuaListResult} @@ -173,17 +230,22 @@ public interface KapuaListResult extends KapuaSerializabl * @see List#clear() * @since 1.0.0 */ - void clearItems(); + public void clearItems() { + getItems().clear(); + } /** * Sorts the result {@link List} according to the given {@link Comparator}. * - * @param comparator The {@link Comparator} used to compare items. + * @param comparator + * The {@link Comparator} used to compare items. * @see List#sort(Comparator) * @see Comparator * @since 1.0.0 */ - void sort(@NotNull Comparator comparator); + public void sort(Comparator comparator) { + getItems().sort(comparator); + } /** * Gets the total count of entries that match the {@link KapuaQuery#getPredicate()}s regardless of {@link KapuaQuery#getLimit()} and {@link KapuaQuery#getOffset()} @@ -191,12 +253,16 @@ public interface KapuaListResult extends KapuaSerializabl * @return The total count * @since 1.2.0 */ - Long getTotalCount(); + public Long getTotalCount() { + return totalCount; + } /** * Sets the total count of entries that match the {@link KapuaQuery#getPredicate()}s regardless of {@link KapuaQuery#getLimit()} and {@link KapuaQuery#getOffset()}. * * @since 1.2.0 */ - void setTotalCount(Long totalCount); + public void setTotalCount(Long totalCount) { + this.totalCount = totalCount; + } } diff --git a/service/api/src/main/java/org/eclipse/kapua/model/query/KapuaQuery.java b/service/api/src/main/java/org/eclipse/kapua/model/query/KapuaQuery.java index 5b97ce8c7eb..5bbd1dc2bb5 100644 --- a/service/api/src/main/java/org/eclipse/kapua/model/query/KapuaQuery.java +++ b/service/api/src/main/java/org/eclipse/kapua/model/query/KapuaQuery.java @@ -12,7 +12,17 @@ *******************************************************************************/ package org.eclipse.kapua.model.query; +import java.util.ArrayList; +import java.util.List; + +import javax.validation.constraints.NotNull; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import javax.xml.bind.annotation.XmlTransient; +import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; + import org.eclipse.kapua.model.KapuaEntity; +import org.eclipse.kapua.model.KapuaEntityAttributes; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.model.id.KapuaIdAdapter; import org.eclipse.kapua.model.query.predicate.AndPredicate; @@ -20,17 +30,58 @@ import org.eclipse.kapua.model.query.predicate.OrPredicate; import org.eclipse.kapua.model.query.predicate.QueryPredicate; -import javax.validation.constraints.NotNull; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlElementWrapper; -import javax.xml.bind.annotation.XmlTransient; -import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; -import java.util.List; - /** * {@link KapuaQuery} definition. */ -public interface KapuaQuery { +public class KapuaQuery { + + private KapuaId scopeId; + + private QueryPredicate predicate; + private KapuaSortCriteria sortCriteria; + private List fetchAttributes; + + private Integer offset; + private Integer limit; + private Boolean askTotalCount; + + /** + * Constructor. + * + * @since 1.0.0 + */ + public KapuaQuery() { + } + + /** + * Constructor. + * + * @param scopeId + * The scope {@link KapuaId} of the {@link KapuaQuery} + * @since 1.0.0 + */ + public KapuaQuery(KapuaId scopeId) { + this(); + + setScopeId(scopeId); + } + + /** + * Constructor. + *

        + * It deeply clones the given {@link KapuaQuery} + * + * @param query + * the query to clone. + */ + public KapuaQuery(@NotNull KapuaQuery query) { + setFetchAttributes(query.getFetchAttributes()); + setPredicate(query.getPredicate()); + setLimit(query.getLimit()); + setOffset(query.getOffset()); + setSortCriteria(query.getSortCriteria()); + setAskTotalCount(query.getAskTotalCount()); + } /** * Gets the fetch attribute names list. @@ -40,24 +91,35 @@ public interface KapuaQuery { */ @XmlElementWrapper(name = "fetchAttributeName") @XmlElement(name = "fetchAttributeName") - List getFetchAttributes(); + public List getFetchAttributes() { + if (fetchAttributes == null) { + fetchAttributes = new ArrayList<>(); + } + + return fetchAttributes; + } /** * Adds an attribute to the fetch attribute names list * - * @param fetchAttribute The fetch attribute to add to the list. + * @param fetchAttribute + * The fetch attribute to add to the list. * @since 1.0.0 */ - void addFetchAttributes(@NotNull String fetchAttribute); + public void addFetchAttributes(String fetchAttribute) { + getFetchAttributes().add(fetchAttribute); + } /** - * Sets the fetch attribute names list.
        - * This list is a list of optional attributes of a {@link KapuaEntity} that can be fetched when querying. + * Sets the fetch attribute names list.
        This list is a list of optional attributes of a {@link KapuaEntity} that can be fetched when querying. * - * @param fetchAttributeNames The fetch attribute names list. + * @param fetchAttributeNames + * The fetch attribute names list. * @since 1.0.0 */ - void setFetchAttributes(@NotNull List fetchAttributeNames); + public void setFetchAttributes(List fetchAttributeNames) { + this.fetchAttributes = fetchAttributeNames; + } /** * Get the scope {@link KapuaId} in which to query. @@ -67,15 +129,20 @@ public interface KapuaQuery { */ @XmlElement(name = "scopeId") @XmlJavaTypeAdapter(KapuaIdAdapter.class) - KapuaId getScopeId(); + public KapuaId getScopeId() { + return scopeId; + } /** * Set the scope {@link KapuaId} in which to query. * - * @param scopeId The scope {@link KapuaId} in which to query. + * @param scopeId + * The scope {@link KapuaId} in which to query. * @since 1.0.0 */ - void setScopeId(KapuaId scopeId); + public void setScopeId(KapuaId scopeId) { + this.scopeId = scopeId; + } /** * Gets the {@link KapuaQuery} {@link QueryPredicate}s. @@ -84,17 +151,20 @@ public interface KapuaQuery { * @since 1.0.0 */ @XmlTransient - QueryPredicate getPredicate(); + public QueryPredicate getPredicate() { + return this.predicate; + } /** - * Sets the {@link KapuaQuery} {@link QueryPredicate}s.
        - * The {@link QueryPredicate} can be a simple {@link AttributePredicate} or a combination - * of them by using the {@link AndPredicate} + * Sets the {@link KapuaQuery} {@link QueryPredicate}s.
        The {@link QueryPredicate} can be a simple {@link AttributePredicate} or a combination of them by using the {@link AndPredicate} * - * @param queryPredicate The {@link KapuaQuery} {@link QueryPredicate}s. + * @param queryPredicate + * The {@link KapuaQuery} {@link QueryPredicate}s. * @since 1.0.0 */ - void setPredicate(@NotNull QueryPredicate queryPredicate); + public void setPredicate(QueryPredicate queryPredicate) { + this.predicate = queryPredicate; + } /** * Gets the {@link KapuaQuery} {@link KapuaSortCriteria} @@ -103,7 +173,9 @@ public interface KapuaQuery { * @since 1.0.0 */ @XmlTransient - KapuaSortCriteria getSortCriteria(); + public KapuaSortCriteria getSortCriteria() { + return sortCriteria; + } /** * Sets the {@link KapuaQuery} {@link KapuaSortCriteria}. @@ -112,7 +184,9 @@ public interface KapuaQuery { * The {@link KapuaQuery} {@link KapuaSortCriteria}. * @since 1.0.0 */ - void setSortCriteria(@NotNull KapuaSortCriteria sortCriteria); + public void setSortCriteria(KapuaSortCriteria sortCriteria) { + this.sortCriteria = sortCriteria; + } /** * Gets whether to include not scoped {@link KapuaEntity}es in the result set. @@ -122,7 +196,7 @@ public interface KapuaQuery { * @return Whether to include not scoped {@link KapuaEntity}es in the result set. * @since 2.0.0 */ - default boolean getNotScopedEntities() { + public boolean getNotScopedEntities() { return false; } @@ -133,7 +207,9 @@ default boolean getNotScopedEntities() { * @since 1.5.0 */ @XmlTransient - KapuaSortCriteria getDefaultSortCriteria(); + public KapuaSortCriteria getDefaultSortCriteria() { + return fieldSortCriteria(KapuaEntityAttributes.ENTITY_ID, SortOrder.ASCENDING); + } /** * Gets the {@link KapuaQuery} offset. @@ -142,20 +218,25 @@ default boolean getNotScopedEntities() { * @since 1.0.0 */ @XmlElement(name = "offset") - Integer getOffset(); + public Integer getOffset() { + return offset; + } /** * Set the {@link KapuaQuery} offset in the result set from which start query. *

        - * If set to {@code null} the {@link KapuaQuery} will start from the first result found. - * This also mean that {@link #setOffset(Integer)} with {@code 0} or {@code null} will produce the same result. + * If set to {@code null} the {@link KapuaQuery} will start from the first result found. This also mean that {@link #setOffset(Integer)} with {@code 0} or {@code null} will produce the same + * result. *

        * This method and {@link #setLimit(Integer)} are meant to be used to paginate through the result set. * - * @param offset The {@link KapuaQuery} offset. + * @param offset + * The {@link KapuaQuery} offset. * @since 1.0.0 */ - void setOffset(Integer offset); + public void setOffset(Integer offset) { + this.offset = offset; + } /** * Gets the {@link KapuaQuery} limit. @@ -164,7 +245,9 @@ default boolean getNotScopedEntities() { * @since 1.0.0 */ @XmlElement(name = "limit") - Integer getLimit(); + public Integer getLimit() { + return limit; + } /** * Sets max number of result that will be fetched by this {@link KapuaEntity}. @@ -173,20 +256,24 @@ default boolean getNotScopedEntities() { *

        * This method and {@link #setOffset(Integer)} are meant to be used to paginate through the result set. * - * @param limit The max number of result that will be fetched by this {@link KapuaEntity}. + * @param limit + * The max number of result that will be fetched by this {@link KapuaEntity}. * @since 1.0.0 */ - void setLimit(Integer limit); + public void setLimit(Integer limit) { + this.limit = limit; + } /** - * Get the {@code askTotalCount} flag. If {@literal true}, the returning {@link KapuaListResult} will also return a value in - * the {@code totalCount} field, indicating how many entries matched the query regardless of {@code limit} and - * {@code offset}. If {@literal false}, {@code totalCount} will be {@literal null}. + * Get the {@code askTotalCount} flag. If {@literal true}, the returning {@link KapuaListResult} will also return a value in the {@code totalCount} field, indicating how many entries matched the + * query regardless of {@code limit} and {@code offset}. If {@literal false}, {@code totalCount} will be {@literal null}. * * @return The value of {@code askTotalCount} * @since 1.2.0 */ - Boolean getAskTotalCount(); + public Boolean getAskTotalCount() { + return askTotalCount; + } /** * Set the {@code askTotalCount} flag. @@ -194,67 +281,94 @@ default boolean getNotScopedEntities() { * @param askTotalCount * @since 1.2.0 */ - void setAskTotalCount(Boolean askTotalCount); + public void setAskTotalCount(Boolean askTotalCount) { + this.askTotalCount = askTotalCount; + } // Predicates factory /** * Creates a new {@link AttributePredicate} * - * @param attributeName The name of the attribute - * @param attributeValue The value of the attribute - * @param The type of {@code attributeValue} + * @param attributeName + * The name of the attribute + * @param attributeValue + * The value of the attribute + * @param + * The type of {@code attributeValue} * @return A new {@link AttributePredicate} for the given parameters */ - AttributePredicate attributePredicate(String attributeName, T attributeValue); + public AttributePredicate attributePredicate(String attributeName, T attributeValue) { + return new AttributePredicate<>(attributeName, attributeValue); + } /** * Creates a new {@link AttributePredicate} * - * @param attributeName The name of the attribute - * @param attributeValue The value of the attribute - * @param operator The operator to apply - * @param The type of {@code attributeValue} + * @param attributeName + * The name of the attribute + * @param attributeValue + * The value of the attribute + * @param operator + * The operator to apply + * @param + * The type of {@code attributeValue} * @return A new {@link AttributePredicate} for the given parameters */ - AttributePredicate attributePredicate(String attributeName, T attributeValue, AttributePredicate.Operator operator); + public AttributePredicate attributePredicate(String attributeName, T attributeValue, AttributePredicate.Operator operator) { + return new AttributePredicate<>(attributeName, attributeValue, operator); + } /** * Creates a new, empty {@link AndPredicate} * * @return A new, empty {@link AndPredicate} */ - AndPredicate andPredicate(); + public AndPredicate andPredicate() { + return new AndPredicate(); + } /** * Creates a new {@link AndPredicate} creating a logical AND with all the provided {@link QueryPredicate} * - * @param queryPredicates A list of {@link QueryPredicate}s to create the {@link AndPredicate} + * @param queryPredicates + * A list of {@link QueryPredicate}s to create the {@link AndPredicate} * @return A new {@link AndPredicate} */ - AndPredicate andPredicate(QueryPredicate... queryPredicates); + public AndPredicate andPredicate(QueryPredicate... queryPredicates) { + return new AndPredicate(queryPredicates); + } /** * Creates a new, empty {@link OrPredicate} * * @return A new, empty {@link OrPredicate} */ - OrPredicate orPredicate(); + public OrPredicate orPredicate() { + return new OrPredicate(); + } /** * Creates a new {@link OrPredicate} creating a logical OR with all the provided {@link QueryPredicate} * - * @param queryPredicates A list of {@link QueryPredicate}s to create the {@link OrPredicate} + * @param queryPredicates + * A list of {@link QueryPredicate}s to create the {@link OrPredicate} * @return A new {@link OrPredicate} */ - OrPredicate orPredicate(QueryPredicate... queryPredicates); + public OrPredicate orPredicate(QueryPredicate... queryPredicates) { + return new OrPredicate(queryPredicates); + } /** * Creates a new {@link FieldSortCriteria} * - * @param attributeName The name of the attribute - * @param sortOrder The {@link SortOrder} + * @param attributeName + * The name of the attribute + * @param sortOrder + * The {@link SortOrder} * @return */ - FieldSortCriteria fieldSortCriteria(String attributeName, SortOrder sortOrder); + public FieldSortCriteria fieldSortCriteria(String attributeName, SortOrder sortOrder) { + return new FieldSortCriteria(attributeName, sortOrder); + } } diff --git a/service/api/src/main/java/org/eclipse/kapua/model/query/QueryFactory.java b/service/api/src/main/java/org/eclipse/kapua/model/query/QueryFactory.java deleted file mode 100644 index adc9c83b1d1..00000000000 --- a/service/api/src/main/java/org/eclipse/kapua/model/query/QueryFactory.java +++ /dev/null @@ -1,31 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.model.query; - -import org.eclipse.kapua.model.KapuaObjectFactory; - -/** - * {@link KapuaQuery} {@link KapuaObjectFactory} definition. - * - * @since 2.0.0 - */ -public interface QueryFactory extends KapuaObjectFactory { - - /** - * Instantiates a new {@link KapuaQuery}. - * - * @return The newly instantiated {@link KapuaQuery}. - * @since 2.0.0 - */ - KapuaQuery newQuery(); -} diff --git a/commons/src/main/java/org/eclipse/kapua/commons/model/query/predicate/AbstractMatchPredicate.java b/service/api/src/main/java/org/eclipse/kapua/model/query/predicate/AbstractMatchPredicate.java similarity index 88% rename from commons/src/main/java/org/eclipse/kapua/commons/model/query/predicate/AbstractMatchPredicate.java rename to service/api/src/main/java/org/eclipse/kapua/model/query/predicate/AbstractMatchPredicate.java index 40f4fe530a4..f5e2e6fd5c2 100644 --- a/commons/src/main/java/org/eclipse/kapua/commons/model/query/predicate/AbstractMatchPredicate.java +++ b/service/api/src/main/java/org/eclipse/kapua/model/query/predicate/AbstractMatchPredicate.java @@ -10,12 +10,10 @@ * Contributors: * Eurotech - initial API and implementation *******************************************************************************/ -package org.eclipse.kapua.commons.model.query.predicate; +package org.eclipse.kapua.model.query.predicate; import java.util.List; -import org.eclipse.kapua.model.query.predicate.MatchPredicate; - /** * {@link MatchPredicate} implementation. * diff --git a/service/api/src/main/java/org/eclipse/kapua/model/query/predicate/AndPredicate.java b/service/api/src/main/java/org/eclipse/kapua/model/query/predicate/AndPredicate.java index 1104ad0aaf0..81f03b26960 100644 --- a/service/api/src/main/java/org/eclipse/kapua/model/query/predicate/AndPredicate.java +++ b/service/api/src/main/java/org/eclipse/kapua/model/query/predicate/AndPredicate.java @@ -12,8 +12,13 @@ *******************************************************************************/ package org.eclipse.kapua.model.query.predicate; -import javax.validation.constraints.NotNull; +import java.util.ArrayList; import java.util.List; +import java.util.Objects; + +import javax.validation.constraints.NotNull; + +import com.google.common.collect.Lists; /** * {@link AndPredicate} definition. @@ -22,17 +27,51 @@ * * @since 1.0.0 */ -public interface AndPredicate extends QueryPredicate { +public class AndPredicate implements QueryPredicate { + + private List predicates; + + /** + * Constructor. + * + * @since 1.0.0 + */ + public AndPredicate() { + setPredicates(new ArrayList<>()); + } + + /** + * Constructor which accepts a not null array of {@link QueryPredicate}s. + * + * @param predicates + * the {@link QueryPredicate}s to add. + * @throws NullPointerException + * if the given parameter is {@code null}. + * @since 1.0.0 + */ + public AndPredicate(@NotNull QueryPredicate... predicates) { + Objects.requireNonNull(predicates); + + setPredicates(Lists.newArrayList(predicates)); + } /** * Adds the given {@link QueryPredicate} to the {@link AndPredicate}. * - * @param predicate The {@link AndPredicate} to concatenate + * @param predicate + * The {@link AndPredicate} to concatenate * @return {@code this} {@link AndPredicate}. - * @throws NullPointerException if the given parameter is {@code null}. + * @throws NullPointerException + * if the given parameter is {@code null}. * @since 1.0.0 */ - AndPredicate and(@NotNull QueryPredicate predicate); + public AndPredicate and(@NotNull QueryPredicate predicate) { + Objects.requireNonNull(predicates); + + getPredicates().add(predicate); + + return this; + } /** * Gets all {@link QueryPredicate} set for this {@link AndPredicate} @@ -40,14 +79,20 @@ public interface AndPredicate extends QueryPredicate { * @return The {@link List} of {@link QueryPredicate}s * @since 1.0.0 */ - List getPredicates(); + public List getPredicates() { + return this.predicates; + } /** * Sets a {@link List} of {@link QueryPredicate}s in AND clause * - * @param predicates The {@link List} of {@link QueryPredicate}s - * @throws NullPointerException if the given parameter is {@code null}. + * @param predicates + * The {@link List} of {@link QueryPredicate}s + * @throws NullPointerException + * if the given parameter is {@code null}. * @since 1.1.0 */ - void setPredicates(@NotNull List predicates); + public void setPredicates(List predicates) { + this.predicates = predicates; + } } diff --git a/service/api/src/main/java/org/eclipse/kapua/model/query/predicate/AttributePredicate.java b/service/api/src/main/java/org/eclipse/kapua/model/query/predicate/AttributePredicate.java index 79fde273391..172ac756db2 100644 --- a/service/api/src/main/java/org/eclipse/kapua/model/query/predicate/AttributePredicate.java +++ b/service/api/src/main/java/org/eclipse/kapua/model/query/predicate/AttributePredicate.java @@ -15,10 +15,11 @@ /** * {@link AttributePredicate} definition. * - * @param Attribute value type. + * @param + * Attribute value type. * @since 1.3.0 */ -public interface AttributePredicate extends QueryPredicate { +public class AttributePredicate implements QueryPredicate { /** * {@link AttributePredicate}s operators @@ -27,7 +28,7 @@ public interface AttributePredicate extends QueryPredicate { * * @since 1.3.0 */ - enum Operator { + public static enum Operator { /** * {@literal #EQUAL} {@link Operator} *

        @@ -66,8 +67,7 @@ enum Operator { /** * {@literal #STARTS_WITH} {@link Operator} *

        - * Matches results with value that starts with the given value. - * To be used with {@link String} {@link org.eclipse.kapua.model.KapuaEntityAttributes}. + * Matches results with value that starts with the given value. To be used with {@link String} {@link org.eclipse.kapua.model.KapuaEntityAttributes}. * * @since 1.3.0 */ @@ -76,8 +76,7 @@ enum Operator { /** * The same of {@link #STARTS_WITH} {@link Operator} but case insensitive *

        - * Matches results with value that starts with the given value, case insensitive. - * To be used with {@link String} {@link org.eclipse.kapua.model.KapuaEntityAttributes}. + * Matches results with value that starts with the given value, case insensitive. To be used with {@link String} {@link org.eclipse.kapua.model.KapuaEntityAttributes}. * * @since 1.3.0 */ @@ -86,8 +85,7 @@ enum Operator { /** * {@literal #LIKE} {@link Operator} *

        - * Matches results with value that are like (in SQL fashion) the given value. - * To be used with {@link String} {@link org.eclipse.kapua.model.KapuaEntityAttributes}. + * Matches results with value that are like (in SQL fashion) the given value. To be used with {@link String} {@link org.eclipse.kapua.model.KapuaEntityAttributes}. *

        * If you want to match only the beginning of the {@link String} please consider using {@link #STARTS_WITH}. * @@ -98,8 +96,7 @@ enum Operator { /** * {@link #LIKE} {@link Operator} but case insensitive *

        - * Matches results with value that are like (in SQL fashion) the given value case insensitive. - * To be used with {@link String} {@link org.eclipse.kapua.model.KapuaEntityAttributes}. + * Matches results with value that are like (in SQL fashion) the given value case insensitive. To be used with {@link String} {@link org.eclipse.kapua.model.KapuaEntityAttributes}. *

        * If you want to match only the beginning of the {@link String} please consider using {@link #STARTS_WITH_IGNORE_CASE}. * @@ -110,8 +107,7 @@ enum Operator { /** * {@literal #GREATER_THAN} {@link Operator} *

        - * Matches result with value that is greater but not equal. - * To be used with {@link Comparable} types. + * Matches result with value that is greater but not equal. To be used with {@link Comparable} types. * * @since 1.3.0 */ @@ -120,8 +116,7 @@ enum Operator { /** * {@literal #GREATER_THAN_OR_EQUAL} {@link Operator} *

        - * Matches result with value that is greater or equal. - * To be used with {@link Comparable} types. + * Matches result with value that is greater or equal. To be used with {@link Comparable} types. * * @since 1.3.0 */ @@ -130,8 +125,7 @@ enum Operator { /** * {@literal #LESS_THAN} {@link Operator} *

        - * Matches result with value that is less but not equal. - * To be used with {@link Comparable} types. + * Matches result with value that is less but not equal. To be used with {@link Comparable} types. * * @since 1.3.0 */ @@ -140,21 +134,58 @@ enum Operator { /** * {@literal #LESS_THAN_OR_EQUAL} {@link Operator} *

        - * Matches result with value that is less or equal. - * To be used with {@link Comparable} types. + * Matches result with value that is less or equal. To be used with {@link Comparable} types. * * @since 1.3.0 */ LESS_THAN_OR_EQUAL } + private String attributeName; + private T attributeValue; + private Operator operator; + + /** + * Constructor. + *

        + * Defaults ot {@link org.eclipse.kapua.model.query.predicate.AttributePredicate.Operator#EQUAL} + * + * @param attributeName + * The name of {@link org.eclipse.kapua.model.KapuaEntityAttributes} to set into the {@link AttributePredicate}. + * @param attributeValue + * The value of {@link org.eclipse.kapua.model.KapuaEntityAttributes} to set into the {@link AttributePredicate}. + * @since 1.0.0 + */ + public AttributePredicate(String attributeName, T attributeValue) { + this(attributeName, attributeValue, Operator.EQUAL); + } + + /** + * Constructor. + * + * @param attributeName + * The name of {@link org.eclipse.kapua.model.KapuaEntityAttributes} to set into the {@link AttributePredicate}. + * @param attributeValue + * The value of {@link org.eclipse.kapua.model.KapuaEntityAttributes} to set into the {@link AttributePredicate}. + * @param operator + * The {@link org.eclipse.kapua.model.query.predicate.AttributePredicate.Operator} to set into the {@link AttributePredicate}. + * @since 1.0.0 + */ + public AttributePredicate(String attributeName, T attributeValue, Operator operator) { + this.attributeName = attributeName; + this.attributeValue = attributeValue; + this.operator = operator; + } + /** * Gets the name of the {@link org.eclipse.kapua.model.KapuaEntityAttributes} to compare. * * @return The name name of the {@link org.eclipse.kapua.model.KapuaEntityAttributes} to compare. * @since 1.3.0 */ - String getAttributeName(); + public String getAttributeName() { + return attributeName; + } /** * Gets the value to compare the results. @@ -162,7 +193,9 @@ enum Operator { * @return The value to compare the results. * @since 1.3.0 */ - T getAttributeValue(); + public T getAttributeValue() { + return attributeValue; + } /** * Get the {@link Operator} used to compare results. @@ -170,5 +203,7 @@ enum Operator { * @return The {@link Operator} used to compare results. * @since 1.3.0 */ - Operator getOperator(); + public Operator getOperator() { + return operator; + } } diff --git a/service/api/src/main/java/org/eclipse/kapua/model/query/predicate/OrPredicate.java b/service/api/src/main/java/org/eclipse/kapua/model/query/predicate/OrPredicate.java index 2cc4c8a36dc..58c5bb5640a 100644 --- a/service/api/src/main/java/org/eclipse/kapua/model/query/predicate/OrPredicate.java +++ b/service/api/src/main/java/org/eclipse/kapua/model/query/predicate/OrPredicate.java @@ -12,8 +12,13 @@ *******************************************************************************/ package org.eclipse.kapua.model.query.predicate; -import javax.validation.constraints.NotNull; +import java.util.ArrayList; import java.util.List; +import java.util.Objects; + +import javax.validation.constraints.NotNull; + +import com.google.common.collect.Lists; /** * {@link OrPredicate} definition. @@ -22,17 +27,51 @@ * * @since 1.0.0 */ -public interface OrPredicate extends QueryPredicate { +public class OrPredicate implements QueryPredicate { + + private List predicates; + + /** + * Constructor. + * + * @since 1.0.0 + */ + public OrPredicate() { + setPredicates(new ArrayList<>()); + } + + /** + * Constructor which accepts a not {@code null} array of {@link QueryPredicate}s. + * + * @param predicates + * the {@link QueryPredicate}s to add. + * @throws NullPointerException + * if the given parameter is {@code null}. + * @since 1.0.0 + */ + public OrPredicate(@NotNull QueryPredicate... predicates) { + Objects.requireNonNull(predicates); + + setPredicates(Lists.newArrayList(predicates)); + } /** * Adds the given {@link QueryPredicate} to the {@link OrPredicate}. * - * @param predicate The {@link OrPredicate} to concatenate + * @param predicate + * The {@link OrPredicate} to concatenate * @return {@code this} {@link OrPredicate}. - * @throws NullPointerException if the given parameter is {@code null}. + * @throws NullPointerException + * if the given parameter is {@code null}. * @since 1.0.0 */ - OrPredicate or(@NotNull QueryPredicate predicate); + public OrPredicate or(@NotNull QueryPredicate predicate) { + Objects.requireNonNull(predicates); + + getPredicates().add(predicate); + + return this; + } /** * Gets all {@link QueryPredicate} set for this {@link OrPredicate} @@ -40,15 +79,21 @@ public interface OrPredicate extends QueryPredicate { * @return The {@link List} of {@link QueryPredicate}s * @since 1.0.0 */ - List getPredicates(); + public List getPredicates() { + return this.predicates; + } /** * Sets a {@link List} of {@link QueryPredicate}s in OR clause * - * @param predicates The {@link List} of {@link QueryPredicate}s - * @throws NullPointerException if the given parameter is {@code null}. + * @param predicates + * The {@link List} of {@link QueryPredicate}s + * @throws NullPointerException + * if the given parameter is {@code null}. * @since 1.1.0 */ - void setPredicates(@NotNull List predicates); + public void setPredicates(List predicates) { + this.predicates = predicates; + } } diff --git a/service/api/src/main/java/org/eclipse/kapua/service/KapuaEntityService.java b/service/api/src/main/java/org/eclipse/kapua/service/KapuaEntityService.java index 48cb9eb52aa..bfd6ad52236 100644 --- a/service/api/src/main/java/org/eclipse/kapua/service/KapuaEntityService.java +++ b/service/api/src/main/java/org/eclipse/kapua/service/KapuaEntityService.java @@ -12,6 +12,8 @@ *******************************************************************************/ package org.eclipse.kapua.service; +import javax.validation.constraints.NotNull; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.model.KapuaEntity; import org.eclipse.kapua.model.KapuaEntityCreator; @@ -19,21 +21,22 @@ import org.eclipse.kapua.model.query.KapuaListResult; import org.eclipse.kapua.model.query.KapuaQuery; -import javax.validation.constraints.NotNull; - /** * Base {@code interface} for all {@link KapuaService}s that are managing {@link KapuaEntity}es. * - * @param Type of the {@link KapuaEntity} being managed. - * @param Type of the {@link KapuaEntityCreator} being managed. + * @param + * Type of the {@link KapuaEntity} being managed. + * @param + * Type of the {@link KapuaEntityCreator} being managed. * @since 1.0.0 */ -public interface KapuaEntityService> extends KapuaService { +public interface KapuaEntityService extends KapuaService { /** * Creates a {@link KapuaEntity} using information provided in the given {@link KapuaEntityCreator}. * - * @param creator The {@link KapuaEntityCreator}. + * @param creator + * The {@link KapuaEntityCreator}. * @return The newly created {@link KapuaEntity}. * @throws KapuaException * @since 1.0.0 @@ -43,8 +46,10 @@ public interface KapuaEntityService Type of the {@link KapuaEntity} being managed. + * @param + * Type of the {@link KapuaEntity} being managed. * @since 1.0 */ -public interface KapuaUpdatableEntityService extends KapuaService { +public interface KapuaUpdatableEntityService extends KapuaService { /** * Updates the given {@link KapuaUpdatableEntity}. * - * @param entity The {@link KapuaUpdatableEntity}. + * @param entity + * The {@link KapuaUpdatableEntity}. * @return The updated {@link KapuaUpdatableEntity}. * @throws KapuaException * @since 1.0.0 diff --git a/service/api/src/test/java/org/eclipse/kapua/model/config/metatype/EmptyTocdTest.java b/service/api/src/test/java/org/eclipse/kapua/model/config/metatype/EmptyTocdTest.java index ca901683cf5..4b7e65ebc69 100644 --- a/service/api/src/test/java/org/eclipse/kapua/model/config/metatype/EmptyTocdTest.java +++ b/service/api/src/test/java/org/eclipse/kapua/model/config/metatype/EmptyTocdTest.java @@ -15,6 +15,10 @@ import java.util.Arrays; import java.util.List; +import java.util.Arrays; +import java.util.List; + +import org.eclipse.kapua.model.config.metatype.KapuaTocd; import org.eclipse.kapua.qa.markers.junit.JUnitTests; import org.junit.Assert; import org.junit.Before; @@ -27,21 +31,21 @@ public class EmptyTocdTest { @Before public void createInstanceOfClass() { - Assert.assertNotNull(emptyTocd = new EmptyTocd()); + Assert.assertNotNull(emptyTocd = KapuaTocd.empty()); } - EmptyTocd emptyTocd; + KapuaTocd emptyTocd; //helper list of objects List objList = Arrays.asList( - new EmptyTocd("1", "name"), - new EmptyTocd("", ""), - new EmptyTocd("2", ""), - new EmptyTocd("", "name2")); + KapuaTocd.empty("1", "name"), + KapuaTocd.empty("", ""), + KapuaTocd.empty("2", ""), + KapuaTocd.empty("", "name2")); @Test public void emptyTocdTest() { - EmptyTocd emptyTocd = new EmptyTocd("49", "name"); + KapuaTocd emptyTocd = KapuaTocd.empty("49", "name"); Assert.assertEquals("tocd.id", "49", emptyTocd.getId()); Assert.assertEquals("tocd.name", "name", emptyTocd.getName()); } diff --git a/service/api/src/test/java/org/eclipse/kapua/model/config/metatype/KapuaTadTest.java b/service/api/src/test/java/org/eclipse/kapua/model/config/metatype/KapuaTadTest.java deleted file mode 100644 index 2c608bfe3b2..00000000000 --- a/service/api/src/test/java/org/eclipse/kapua/model/config/metatype/KapuaTadTest.java +++ /dev/null @@ -1,283 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2020, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.model.config.metatype; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.xml.namespace.QName; - -import org.eclipse.kapua.qa.markers.junit.JUnitTests; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.experimental.categories.Category; - -@Category(JUnitTests.class) -public class KapuaTadTest { - - @Before - public void createInstanceOfClasses() { - - kapuaTad = new KapuaTad(); - toption = new KapuaToption(); - toption2 = new KapuaToption(); - } - - KapuaTad kapuaTad; - KapuaToption toption; - KapuaToption toption2; - - @Test - public void getOptionToNullTest() { - kapuaTad.getOption(); - Assert.assertTrue(kapuaTad.getOption().isEmpty()); - } - - @Test - public void setAndGetOptionRegularTest() { - List option = new ArrayList<>(); - option.add(toption); - kapuaTad.setOption(option); - Assert.assertEquals("tadImpl.option", option, kapuaTad.getOption()); - } - - @Test - public void addAndGetOptionTest() { - List options = new ArrayList<>(); - options.add(toption); - options.add(toption2); - - kapuaTad.addOption(toption); - kapuaTad.addOption(toption2); - - Assert.assertEquals("tadImpl.option", options, kapuaTad.getOption()); - } - - @Test - public void getAnyTest() { - Assert.assertTrue(kapuaTad.getAny().isEmpty()); - } - - @Test - public void setAndGetAnyTest() { - List options = new ArrayList<>(); - options.add(toption); - options.add(toption2); - options.add(null); - kapuaTad.setAny(options); - Assert.assertEquals("tadImpl.option", options, kapuaTad.getAny()); - } - - @Test - public void setAndGetNameToNullTest() { - kapuaTad.setName(null); - Assert.assertNull(kapuaTad.getName()); - } - - @Test - public void setAndGetNameTest() { - String[] permittedValues = { "", "regularName", "49", "regular Name", "regular name with spaces", "!@#$%&*()_+/->,<", "NAME", "name123" }; - for (String value : permittedValues) { - kapuaTad.setName(value); - Assert.assertTrue(kapuaTad.getName().contains(value)); - } - } - - @Test - public void setAndGetDescriptionToNullTest() { - kapuaTad.setDescription(null); - Assert.assertNull(kapuaTad.getDescription()); - } - - @Test - public void setAndGetDescriptionTest() { - String[] permittedValues = { "", "regularDescription", "49", "regular Description", "regular description with spaces", "!@#$%&*()_+/->,<", "DESCRIPTION", "description123" }; - for (String value : permittedValues) { - kapuaTad.setDescription(value); - Assert.assertTrue(kapuaTad.getDescription().contains(value)); - } - } - - @Test - public void setAndGetIdToNullTest() { - kapuaTad.setId(null); - Assert.assertNull(kapuaTad.getId()); - } - - @Test - public void setAndGetIdTest() { - String[] permittedValues = { "", "regularId", "49", "regular Id", "regular id with spaces", "!@#$%&*()_+/->,<", "ID", "id123" }; - for (String value : permittedValues) { - kapuaTad.setId(value); - Assert.assertTrue(kapuaTad.getId().contains(value)); - } - } - - @Test - public void setAndGetTypeStringTest() { - kapuaTad.setType(KapuaTscalar.STRING); - Assert.assertEquals("tadImpl.type", KapuaTscalar.STRING, kapuaTad.getType()); - } - - @Test - public void setAndGetTypeLongTest() { - kapuaTad.setType(KapuaTscalar.LONG); - Assert.assertEquals("tadImpl.type", KapuaTscalar.LONG, kapuaTad.getType()); - } - - @Test - public void setAndGetTypeDoubleTest() { - kapuaTad.setType(KapuaTscalar.DOUBLE); - Assert.assertEquals("tadImpl.type", KapuaTscalar.DOUBLE, kapuaTad.getType()); - } - - @Test - public void setAndGetTypeFloatTest() { - kapuaTad.setType(KapuaTscalar.FLOAT); - Assert.assertEquals("tadImpl.type", KapuaTscalar.FLOAT, kapuaTad.getType()); - } - - @Test - public void setAndGetTypeIntegerTest() { - kapuaTad.setType(KapuaTscalar.INTEGER); - Assert.assertEquals("tadImpl.type", KapuaTscalar.INTEGER, kapuaTad.getType()); - } - - @Test - public void setAndGetTypeByteTest() { - kapuaTad.setType(KapuaTscalar.BYTE); - Assert.assertEquals("tadImpl.type", KapuaTscalar.BYTE, kapuaTad.getType()); - } - - @Test - public void setAndGetTypeCharTest() { - kapuaTad.setType(KapuaTscalar.CHAR); - Assert.assertEquals("tadImpl.type", KapuaTscalar.CHAR, kapuaTad.getType()); - } - - @Test - public void setAndGetTypeBooleanTest() { - kapuaTad.setType(KapuaTscalar.BOOLEAN); - Assert.assertEquals("tadImpl.type", KapuaTscalar.BOOLEAN, kapuaTad.getType()); - } - - @Test - public void setAndGetTypeShortTest() { - kapuaTad.setType(KapuaTscalar.SHORT); - Assert.assertEquals("tadImpl.type", KapuaTscalar.SHORT, kapuaTad.getType()); - } - - @Test - public void setAndGetTypePasswordTest() { - kapuaTad.setType(KapuaTscalar.PASSWORD); - Assert.assertEquals("tadImpl.type", KapuaTscalar.PASSWORD, kapuaTad.getType()); - } - - @Test - public void setAndGetCardinalityToNullTest() { - kapuaTad.setCardinality(null); - Assert.assertEquals("tadImpl.cardinality", 0, (int) kapuaTad.getCardinality()); - } - - @Test - public void setAndGetCardinalityRegularTest() { - int[] permittedValues = { 1, 10, 100, 500, -2147483648, 2147483647, 0 }; - for (int value : permittedValues) { - kapuaTad.setCardinality(value); - Assert.assertEquals("tadImpl.cardinality", Integer.valueOf(value), kapuaTad.getCardinality()); - } - } - - @Test - public void setAndGetMinToNullTest() { - kapuaTad.setMin(null); - Assert.assertNull(kapuaTad.getMin()); - } - - @Test - public void setAndGetMinTest() { - String[] permittedValues = { "", "regularMin", "49", "regular Min", "regular min with spaces", "!@#$%&*()_+/->,<", "MIN", "min123" }; - for (String value : permittedValues) { - kapuaTad.setMin(value); - Assert.assertTrue(kapuaTad.getMin().contains(value)); - } - } - - @Test - public void setAndGetMaxToNullTest() { - kapuaTad.setMax(null); - Assert.assertNull(kapuaTad.getMax()); - } - - @Test - public void setAndGetMaxTest() { - String[] permittedValues = { "", "regularMax", "49", "regular Max", "regular max with spaces", "!@#$%&*()_+/->,<", "MAX", "max123" }; - for (String value : permittedValues) { - kapuaTad.setMax(value); - Assert.assertTrue(kapuaTad.getMax().contains(value)); - } - } - - @Test - public void setAndGetDefaultToNullTest() { - kapuaTad.setDefault(null); - Assert.assertNull(kapuaTad.getDefault()); - } - - @Test - public void setAndGetDefaultTest() { - String[] permittedValues = { "", "regularDefault", "49", "regular Default", "regular default with spaces", "!@#$%&*()_+/->,<", "DEFAULT", "default123" }; - for (String value : permittedValues) { - kapuaTad.setDefault(value); - Assert.assertTrue(kapuaTad.getDefault().contains(value)); - } - } - - @Test - public void setIsRequiredToNullTest() { - kapuaTad.setRequired(null); - Assert.assertTrue(kapuaTad.isRequired()); - } - - @Test - public void setAndIsRequiredTest() { - boolean[] permittedValues = { false, true }; - for (boolean value : permittedValues) { - kapuaTad.setRequired(value); - Assert.assertEquals("tadImpl.value", value, kapuaTad.isRequired()); - } - } - - @Test - public void putAndGetOtherAttributeTest() { - Map expectedValues = new HashMap<>(); - - expectedValues.put(QName.valueOf("1"), "a"); - expectedValues.put(QName.valueOf("2"), "b"); - expectedValues.put(QName.valueOf("3"), "c"); - - kapuaTad.putOtherAttribute(QName.valueOf("1"), "a"); - kapuaTad.putOtherAttribute(QName.valueOf("2"), "b"); - kapuaTad.putOtherAttribute(QName.valueOf("3"), "c"); - - Assert.assertEquals("tadImpl.attributes", expectedValues, kapuaTad.getOtherAttributes()); - } - - @Test - public void getOtherAttributeTest() { - Assert.assertTrue(kapuaTad.getOtherAttributes().isEmpty()); - } -} diff --git a/service/api/src/test/java/org/eclipse/kapua/model/config/metatype/KapuaTattributeTest.java b/service/api/src/test/java/org/eclipse/kapua/model/config/metatype/KapuaTattributeTest.java index 131abfa8c44..85a3f992e61 100644 --- a/service/api/src/test/java/org/eclipse/kapua/model/config/metatype/KapuaTattributeTest.java +++ b/service/api/src/test/java/org/eclipse/kapua/model/config/metatype/KapuaTattributeTest.java @@ -24,40 +24,40 @@ public class KapuaTattributeTest { @Before public void createInstanceOfClass() { - tattributeImpl = new KapuaTattribute(); + kapuaTattribute = new KapuaTattribute(); } - KapuaTattribute tattributeImpl; + KapuaTattribute kapuaTattribute; @Test public void getValueTest() { - Assert.assertTrue(tattributeImpl.getValue().isEmpty()); + Assert.assertTrue(kapuaTattribute.getValue().isEmpty()); } @Test public void getAnyTest() { - Assert.assertTrue(tattributeImpl.getAny().isEmpty()); + Assert.assertTrue(kapuaTattribute.getAny().isEmpty()); } @Test public void setAndGetAdrefToNullTest() { - tattributeImpl.setAdref(null); - Assert.assertNull(tattributeImpl.getAdref()); + kapuaTattribute.setAdref(null); + Assert.assertNull(kapuaTattribute.getAdref()); } @Test public void setAndGetAdrefTest() { String[] permittedValues = { "", "!@#$%^^&**(-()_)+/|", "regularAdref", "regular Adref", "49", "regularAdref49", "ADREF", "246465494135646120009090049684646496468456468496846464968496844" }; for (String value : permittedValues) { - tattributeImpl.setAdref(value); - Assert.assertTrue(tattributeImpl.getAdref().contains(value)); + kapuaTattribute.setAdref(value); + Assert.assertTrue(kapuaTattribute.getAdref().contains(value)); } } @Test public void setAndGetContentToNullTest() { - tattributeImpl.setContent(null); - Assert.assertNull(tattributeImpl.getContent()); + kapuaTattribute.setContent(null); + Assert.assertNull(kapuaTattribute.getContent()); } @Test @@ -65,13 +65,13 @@ public void setAndGetContentTest() { String[] permittedValues = { "", "!@#$%^^&**(-()_)+/|", "regularContent", "regular Content", "49", "regularContent49", "CONTENT", "246465494135646120009090049684646496468456468496846464968496844" }; for (String value : permittedValues) { - tattributeImpl.setContent(value); - Assert.assertTrue(tattributeImpl.getContent().contains(value)); + kapuaTattribute.setContent(value); + Assert.assertTrue(kapuaTattribute.getContent().contains(value)); } } @Test public void getOtherAttributesTest() { - Assert.assertTrue(tattributeImpl.getOtherAttributes().isEmpty()); + Assert.assertTrue(kapuaTattribute.getOtherAttributes().isEmpty()); } } diff --git a/service/api/src/test/java/org/eclipse/kapua/model/config/metatype/KapuaTdesignateTest.java b/service/api/src/test/java/org/eclipse/kapua/model/config/metatype/KapuaTdesignateTest.java index 0ee4d41d154..b7b7cb8b1cc 100644 --- a/service/api/src/test/java/org/eclipse/kapua/model/config/metatype/KapuaTdesignateTest.java +++ b/service/api/src/test/java/org/eclipse/kapua/model/config/metatype/KapuaTdesignateTest.java @@ -14,6 +14,11 @@ import java.util.ArrayList; +import java.util.ArrayList; + +import org.eclipse.kapua.model.config.metatype.KapuaTdesignate; +import org.eclipse.kapua.model.config.metatype.KapuaTobject; +import org.eclipse.kapua.model.config.metatype.KapuaToption; import org.eclipse.kapua.qa.markers.junit.JUnitTests; import org.junit.Assert; import org.junit.Before; diff --git a/service/api/src/test/java/org/eclipse/kapua/model/config/metatype/KapuaTiconTest.java b/service/api/src/test/java/org/eclipse/kapua/model/config/metatype/KapuaTiconTest.java index be81b085155..79b7dbfa65a 100644 --- a/service/api/src/test/java/org/eclipse/kapua/model/config/metatype/KapuaTiconTest.java +++ b/service/api/src/test/java/org/eclipse/kapua/model/config/metatype/KapuaTiconTest.java @@ -26,47 +26,47 @@ public class KapuaTiconTest { @Before public void createInstanceOfClass() { - ticonImpl = new KapuaTicon(); + kapuaTicon = new KapuaTicon(); } - KapuaTicon ticonImpl; + KapuaTicon kapuaTicon; @Test public void getAnyTest() { - Assert.assertTrue(ticonImpl.getAny().isEmpty()); + Assert.assertTrue(kapuaTicon.getAny().isEmpty()); } @Test public void setAndGetResourcesToNullTest() { - ticonImpl.setResource(null); - Assert.assertNull(ticonImpl.getResource()); + kapuaTicon.setResource(null); + Assert.assertNull(kapuaTicon.getResource()); } @Test public void setAndGetResourcesTest() { String[] permittedValues = { "", "regularResources", "49", "regular Resources", "regular esources with spaces", "!@#$%&*()_+/->,<", "RESOURCES", "resources123" }; for (String value : permittedValues) { - ticonImpl.setResource(value); - Assert.assertTrue(ticonImpl.getResource().contains(value)); + kapuaTicon.setResource(value); + Assert.assertTrue(kapuaTicon.getResource().contains(value)); } } @Test public void setAndGetSizeToNullTest() { - ticonImpl.setSize(null); - Assert.assertNull(ticonImpl.getSize()); + kapuaTicon.setSize(null); + Assert.assertNull(kapuaTicon.getSize()); } @Test public void setAndGetSizeBigIntTest() { String numStr = "453453453456465765234923423094723472394723423482304823095734957320948305712324000123123"; BigInteger num = new BigInteger(numStr); - ticonImpl.setSize(num); - Assert.assertEquals("ticonImpl.size", num, ticonImpl.getSize()); + kapuaTicon.setSize(num); + Assert.assertEquals("KapuaTicon.size", num, kapuaTicon.getSize()); } @Test public void getOtherAttributesTest() { - Assert.assertTrue(ticonImpl.getOtherAttributes().isEmpty()); + Assert.assertTrue(kapuaTicon.getOtherAttributes().isEmpty()); } } diff --git a/service/api/src/test/java/org/eclipse/kapua/model/config/metatype/KapuaTmetadataTest.java b/service/api/src/test/java/org/eclipse/kapua/model/config/metatype/KapuaTmetadataTest.java index 1af97f2ad92..21dafe9f9b4 100644 --- a/service/api/src/test/java/org/eclipse/kapua/model/config/metatype/KapuaTmetadataTest.java +++ b/service/api/src/test/java/org/eclipse/kapua/model/config/metatype/KapuaTmetadataTest.java @@ -30,13 +30,13 @@ public class KapuaTmetadataTest { @Before public void createInstanceOfClasses() { - emptyTocd = new EmptyTocd(); + emptyTocd = KapuaTocd.empty(); tocd = new KapuaTocd(); tmetadata = new KapuaTmetadata(); tdesignate = new KapuaTdesignate(); } - EmptyTocd emptyTocd; + KapuaTocd emptyTocd; KapuaTocd tocd; KapuaTmetadata tmetadata; KapuaTdesignate tdesignate; diff --git a/service/api/src/test/java/org/eclipse/kapua/model/config/metatype/KapuaTobjectTest.java b/service/api/src/test/java/org/eclipse/kapua/model/config/metatype/KapuaTobjectTest.java index 54ace97a6f5..836ae5ed683 100644 --- a/service/api/src/test/java/org/eclipse/kapua/model/config/metatype/KapuaTobjectTest.java +++ b/service/api/src/test/java/org/eclipse/kapua/model/config/metatype/KapuaTobjectTest.java @@ -23,25 +23,25 @@ public class KapuaTobjectTest { @Before public void createInstanceOfClasses() { - tobjectImpl = new KapuaTobject(); + kapuaTobject = new KapuaTobject(); } - KapuaTobject tobjectImpl; + KapuaTobject kapuaTobject; @Test public void getAttributeTest() { - Assert.assertTrue(tobjectImpl.getAttribute().isEmpty()); + Assert.assertTrue(kapuaTobject.getAttribute().isEmpty()); } @Test public void getAnyTest() { - Assert.assertTrue(tobjectImpl.getAny().isEmpty()); + Assert.assertTrue(kapuaTobject.getAny().isEmpty()); } @Test public void setAndGetOcdrefToNullTest() { - tobjectImpl.setOcdref(null); - Assert.assertNull(tobjectImpl.getOcdref()); + kapuaTobject.setOcdref(null); + Assert.assertNull(kapuaTobject.getOcdref()); } @Test @@ -49,13 +49,13 @@ public void setAndGetOcdrefTest() { String[] permittedValues = { "", "!@#$%^^&**(-()_)+/|", "regularOcdref", "regular Ocdref", "49", "regularOcdref49", "OCDREF", "246465494135646120009090049684646496468456468496846464968496844" }; for (String value : permittedValues) { - tobjectImpl.setOcdref(value); - Assert.assertTrue(tobjectImpl.getOcdref().contains(value)); + kapuaTobject.setOcdref(value); + Assert.assertTrue(kapuaTobject.getOcdref().contains(value)); } } @Test public void testGetOtherAttributes() { - Assert.assertTrue(tobjectImpl.getOtherAttributes().isEmpty()); + Assert.assertTrue(kapuaTobject.getOtherAttributes().isEmpty()); } } diff --git a/service/api/src/test/java/org/eclipse/kapua/model/config/metatype/KapuaTocdTest.java b/service/api/src/test/java/org/eclipse/kapua/model/config/metatype/KapuaTocdTest.java index 5d65a8e45dc..70b0fe6ab98 100644 --- a/service/api/src/test/java/org/eclipse/kapua/model/config/metatype/KapuaTocdTest.java +++ b/service/api/src/test/java/org/eclipse/kapua/model/config/metatype/KapuaTocdTest.java @@ -10,7 +10,7 @@ * Contributors: * Eurotech - initial API and implementation *******************************************************************************/ -package org.eclipse.kapua.model.config.metatype; +package org.eclipse.kapua.commons.configuration.metatype; import java.util.ArrayList; import java.util.HashMap; @@ -19,6 +19,9 @@ import javax.xml.namespace.QName; +import org.eclipse.kapua.model.config.metatype.KapuaTad; +import org.eclipse.kapua.model.config.metatype.KapuaTicon; +import org.eclipse.kapua.model.config.metatype.KapuaTocd; import org.eclipse.kapua.qa.markers.junit.JUnitTests; import org.junit.Assert; import org.junit.Before; @@ -32,7 +35,7 @@ public class KapuaTocdTest { public void createInstanceOfClasses() { kapuaTocd = new KapuaTocd(); - kapuaTad1 = new KapuaTad(); + kapuaTad = new KapuaTad(); kapuaTad2 = new KapuaTad(); kapuaTad3 = new KapuaTad(); ticon = new KapuaTicon(); @@ -40,7 +43,7 @@ public void createInstanceOfClasses() { } KapuaTocd kapuaTocd; - KapuaTad kapuaTad1; + KapuaTad kapuaTad; KapuaTad kapuaTad2; KapuaTad kapuaTad3; KapuaTicon ticon; @@ -54,9 +57,9 @@ public void getADTest() { @Test public void setAndGetADTest() { List expectedValues = new ArrayList<>(); - expectedValues.add(kapuaTad1); + expectedValues.add(kapuaTad); kapuaTocd.setAD(expectedValues); - Assert.assertEquals("tocdImpl.ad", expectedValues, kapuaTocd.getAD()); + Assert.assertEquals("kapuaTocd.ad", expectedValues, kapuaTocd.getAD()); } @Test @@ -77,7 +80,7 @@ public void setAndGetIconTest() { List listOfObj = new ArrayList<>(); listOfObj.add(ticon); kapuaTocd.setIcon(listOfObj); - Assert.assertEquals("tocdImpl.icon", listOfObj, kapuaTocd.getIcon()); + Assert.assertEquals("kapuaTocd.icon", listOfObj, kapuaTocd.getIcon()); } @Test @@ -99,7 +102,7 @@ public void setAndGetAnyTest() { options.add(ticon); options.add(ticon2); kapuaTocd.setAny(options); - Assert.assertEquals("tocdImpl.any", options, kapuaTocd.getAny()); + Assert.assertEquals("kapuaTocd.any", options, kapuaTocd.getAny()); } @Test @@ -166,7 +169,7 @@ public void putAndGetOtherAttributeTest() { kapuaTocd.putOtherAttribute(QName.valueOf("2"), "b"); kapuaTocd.putOtherAttribute(QName.valueOf("3"), "c"); - Assert.assertEquals("tocdImpl.otherAttributes", expectedValues, kapuaTocd.getOtherAttributes()); + Assert.assertEquals("kapuaTocd.otherAttributes", expectedValues, kapuaTocd.getOtherAttributes()); } @Test @@ -183,6 +186,6 @@ public void testSetAndGetOtherAttribute() { values.put(QName.valueOf("3"), "c"); kapuaTocd.setOtherAttributes(values); - Assert.assertEquals("tocdImpl.otherAttributes", values, kapuaTocd.getOtherAttributes()); + Assert.assertEquals("kapuaTocd.otherAttributes", values, kapuaTocd.getOtherAttributes()); } } diff --git a/service/api/src/test/java/org/eclipse/kapua/model/config/metatype/KapuaToptionTest.java b/service/api/src/test/java/org/eclipse/kapua/model/config/metatype/KapuaToptionTest.java index fe008696b4a..9f87ab88d56 100644 --- a/service/api/src/test/java/org/eclipse/kapua/model/config/metatype/KapuaToptionTest.java +++ b/service/api/src/test/java/org/eclipse/kapua/model/config/metatype/KapuaToptionTest.java @@ -12,6 +12,7 @@ *******************************************************************************/ package org.eclipse.kapua.model.config.metatype; +import org.eclipse.kapua.model.config.metatype.KapuaToption; import org.eclipse.kapua.qa.markers.junit.JUnitTests; import org.junit.Assert; import org.junit.Before; diff --git a/service/authentication-app/pom.xml b/service/authentication-app/pom.xml index 61961c6a479..21b13533861 100644 --- a/service/authentication-app/pom.xml +++ b/service/authentication-app/pom.xml @@ -17,7 +17,7 @@ kapua-service org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT 4.0.0 diff --git a/service/authentication-app/src/main/java/org/eclipse/kapua/service/authentication/SpringBridge.java b/service/authentication-app/src/main/java/org/eclipse/kapua/service/authentication/SpringBridge.java index 589e5759062..c045e1b11d2 100644 --- a/service/authentication-app/src/main/java/org/eclipse/kapua/service/authentication/SpringBridge.java +++ b/service/authentication-app/src/main/java/org/eclipse/kapua/service/authentication/SpringBridge.java @@ -24,7 +24,6 @@ import org.eclipse.kapua.service.authentication.credential.handler.CredentialTypeHandler; import org.eclipse.kapua.service.authentication.setting.ServiceAuthenticationSetting; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; import org.eclipse.kapua.service.camel.application.MetricsCamel; import org.eclipse.kapua.service.client.protocol.ProtocolDescriptorProvider; import org.eclipse.kapua.service.device.authentication.api.DeviceConnectionCredentialAdapter; @@ -111,11 +110,6 @@ DeviceConnectionFactory deviceConnectionFactory() { return KapuaLocator.getInstance().getComponent(DeviceConnectionFactory.class); } - @Bean - PermissionFactory permissionFactory() { - return KapuaLocator.getInstance().getComponent(PermissionFactory.class); - } - @Bean DeviceConnectionService deviceConnectionService() { return KapuaLocator.getInstance().getComponent(DeviceConnectionService.class); diff --git a/service/authentication-app/src/main/resources/spring/applicationContext.xml b/service/authentication-app/src/main/resources/spring/applicationContext.xml index 222cf9f91e4..b42fd60d120 100644 --- a/service/authentication-app/src/main/resources/spring/applicationContext.xml +++ b/service/authentication-app/src/main/resources/spring/applicationContext.xml @@ -60,7 +60,6 @@ - @@ -70,7 +69,6 @@ - diff --git a/service/authentication/pom.xml b/service/authentication/pom.xml index ddac23de86c..bb77c61f2cf 100644 --- a/service/authentication/pom.xml +++ b/service/authentication/pom.xml @@ -17,7 +17,7 @@ org.eclipse.kapua kapua-service - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-service-authentication diff --git a/service/authentication/src/main/java/org/eclipse/kapua/service/authentication/AuthenticationServiceBackEndCall.java b/service/authentication/src/main/java/org/eclipse/kapua/service/authentication/AuthenticationServiceBackEndCall.java index 967fe211b87..52ce8c26b7f 100644 --- a/service/authentication/src/main/java/org/eclipse/kapua/service/authentication/AuthenticationServiceBackEndCall.java +++ b/service/authentication/src/main/java/org/eclipse/kapua/service/authentication/AuthenticationServiceBackEndCall.java @@ -36,7 +36,6 @@ import org.eclipse.kapua.commons.security.KapuaSecurityUtils; import org.eclipse.kapua.locator.KapuaLocator; import org.eclipse.kapua.model.KapuaEntity; -import org.eclipse.kapua.model.id.KapuaIdFactory; import org.eclipse.kapua.service.account.Account; import org.eclipse.kapua.service.account.AccountService; import org.eclipse.kapua.service.authentication.authentication.Authenticator; @@ -67,8 +66,6 @@ public class AuthenticationServiceBackEndCall { private AuthenticationService authenticationService; private AccountService accountService; private DeviceConnectionService deviceConnectionService; - private CredentialsFactory credentialFactory; - private KapuaIdFactory kapuaIdFactory; private UserService userService; @Inject @@ -79,15 +76,14 @@ public AuthenticationServiceBackEndCall() { authenticationService = locator.getService(AuthenticationService.class); accountService = locator.getService(AccountService.class); deviceConnectionService = locator.getService(DeviceConnectionService.class); - credentialFactory = locator.getFactory(CredentialsFactory.class); - kapuaIdFactory = locator.getFactory(KapuaIdFactory.class); userService = locator.getService(UserService.class); authenticationMetric = locator.getComponent(AuthMetric.class); } public AuthResponse brokerConnect(AuthRequest authRequest) { try { - logger.info("Login for clientId {} - user: {} - password: {} - client certificates: {}", authRequest.getClientId(), authRequest.getUsername(), Strings.isNullOrEmpty(authRequest.getPassword()) ? "no" : "yes", authRequest.getCertificates() != null ? "yes" : "no"); + logger.info("Login for clientId {} - user: {} - password: {} - client certificates: {}", authRequest.getClientId(), authRequest.getUsername(), + Strings.isNullOrEmpty(authRequest.getPassword()) ? "no" : "yes", authRequest.getCertificates() != null ? "yes" : "no"); ThreadContext.unbindSubject(); String deviceConnectionAuthType = extractAuthTypeFromAuthRequest(authRequest); LoginCredentials authenticationCredentials = buildLoginCredentialsFromAuthType(authRequest, deviceConnectionAuthType); @@ -249,7 +245,8 @@ private void updateError(AuthResponse authResponse, @NotNull Exception exception /** * Extracts the {@link DeviceConnection#getAuthenticationType()} to be used for this connect attempt from the {@link AuthRequest}. * - * @param authRequest The {@link AuthRequest} from which to extract data. + * @param authRequest + * The {@link AuthRequest} from which to extract data. * @return The resolved {@link DeviceConnection#getAuthenticationType()}. * @throws KapuaException * @since 2.0.0 @@ -271,8 +268,10 @@ private String extractAuthTypeFromAuthRequest(AuthRequest authRequest) throws Ka /** * Builds the {@link LoginCredentials} to be used from the resolved {@link DeviceConnection#getAuthenticationType()}. * - * @param authRequest The {@link AuthRequest} with the {@link LoginCredentials} values. - * @param deviceConnectionAuthType The resolved {@link DeviceConnection#getAuthenticationType()}. + * @param authRequest + * The {@link AuthRequest} with the {@link LoginCredentials} values. + * @param deviceConnectionAuthType + * The resolved {@link DeviceConnection#getAuthenticationType()}. * @return The {@link LoginCredentials} for the given {@link DeviceConnection#getAuthenticationType()}. * @throws KapuaException * @since 2.0.0 diff --git a/service/authentication/src/main/java/org/eclipse/kapua/service/authentication/authentication/AdminAuthenticationLogic.java b/service/authentication/src/main/java/org/eclipse/kapua/service/authentication/authentication/AdminAuthenticationLogic.java index 6a7a3922bd3..63783fb0f0b 100644 --- a/service/authentication/src/main/java/org/eclipse/kapua/service/authentication/authentication/AdminAuthenticationLogic.java +++ b/service/authentication/src/main/java/org/eclipse/kapua/service/authentication/authentication/AdminAuthenticationLogic.java @@ -12,7 +12,8 @@ *******************************************************************************/ package org.eclipse.kapua.service.authentication.authentication; -import com.codahale.metrics.Timer.Context; +import java.util.List; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.client.security.bean.AuthAcl; import org.eclipse.kapua.client.security.bean.AuthContext; @@ -20,14 +21,13 @@ import org.eclipse.kapua.commons.model.id.KapuaEid; import org.eclipse.kapua.commons.security.KapuaSecurityUtils; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; import org.eclipse.kapua.service.device.registry.connection.DeviceConnection; import org.eclipse.kapua.service.device.registry.connection.DeviceConnectionFactory; import org.eclipse.kapua.service.device.registry.connection.DeviceConnectionService; import org.eclipse.kapua.service.device.registry.connection.option.DeviceConnectionOptionFactory; import org.eclipse.kapua.service.device.registry.connection.option.DeviceConnectionOptionService; -import java.util.List; +import com.codahale.metrics.Timer.Context; /** * Admin profile authentication logic implementation @@ -43,9 +43,8 @@ public AdminAuthenticationLogic( DeviceConnectionOptionService deviceConnectionOptionService, AuthorizationService authorizationService, DeviceConnectionFactory deviceConnectionFactory, - PermissionFactory permissionFactory, DeviceConnectionService deviceConnectionService) { - super(aclCreator, authenticationMetric, deviceConnectionOptionFactory, deviceConnectionOptionService, authorizationService, deviceConnectionFactory, permissionFactory, deviceConnectionService); + super(aclCreator, authenticationMetric, deviceConnectionOptionFactory, deviceConnectionOptionService, authorizationService, deviceConnectionFactory, deviceConnectionService); } @Override diff --git a/service/authentication/src/main/java/org/eclipse/kapua/service/authentication/authentication/AuthenticationLogic.java b/service/authentication/src/main/java/org/eclipse/kapua/service/authentication/authentication/AuthenticationLogic.java index c505cabf576..69536c5eeeb 100644 --- a/service/authentication/src/main/java/org/eclipse/kapua/service/authentication/authentication/AuthenticationLogic.java +++ b/service/authentication/src/main/java/org/eclipse/kapua/service/authentication/authentication/AuthenticationLogic.java @@ -12,6 +12,10 @@ *******************************************************************************/ package org.eclipse.kapua.service.authentication.authentication; +import java.text.MessageFormat; +import java.util.List; +import java.util.Map; + import org.apache.shiro.ShiroException; import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.client.security.bean.AclUtils; @@ -22,8 +26,8 @@ import org.eclipse.kapua.commons.model.id.KapuaEid; import org.eclipse.kapua.commons.security.KapuaSecurityUtils; import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; import org.eclipse.kapua.service.device.registry.ConnectionUserCouplingMode; import org.eclipse.kapua.service.device.registry.connection.DeviceConnection; import org.eclipse.kapua.service.device.registry.connection.DeviceConnectionCreator; @@ -32,15 +36,10 @@ import org.eclipse.kapua.service.device.registry.connection.DeviceConnectionStatus; import org.eclipse.kapua.service.device.registry.connection.option.DeviceConnectionOptionAttributes; import org.eclipse.kapua.service.device.registry.connection.option.DeviceConnectionOptionFactory; -import org.eclipse.kapua.service.device.registry.connection.option.DeviceConnectionOptionQuery; import org.eclipse.kapua.service.device.registry.connection.option.DeviceConnectionOptionService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.text.MessageFormat; -import java.util.List; -import java.util.Map; - /** * Authentication logic definition * @@ -60,7 +59,6 @@ public abstract class AuthenticationLogic { protected final DeviceConnectionOptionService deviceConnectionOptionService; protected final AuthorizationService authorizationService; protected final DeviceConnectionFactory deviceConnectionFactory; - protected final PermissionFactory permissionFactory; protected final DeviceConnectionService deviceConnectionService; private static final String USER_NOT_AUTHORIZED = "User not authorized!"; @@ -72,7 +70,6 @@ protected AuthenticationLogic( DeviceConnectionOptionService deviceConnectionOptionService, AuthorizationService authorizationService, DeviceConnectionFactory deviceConnectionFactory, - PermissionFactory permissionFactory, DeviceConnectionService deviceConnectionService) { this.aclCreator = aclCreator; this.authenticationMetric = authenticationMetric; @@ -80,7 +77,6 @@ protected AuthenticationLogic( this.deviceConnectionOptionService = deviceConnectionOptionService; this.authorizationService = authorizationService; this.deviceConnectionFactory = deviceConnectionFactory; - this.permissionFactory = permissionFactory; this.deviceConnectionService = deviceConnectionService; } @@ -98,8 +94,8 @@ public abstract List connect(AuthContext authContext) * Execute the disconnection logic * * @param authContext - * @return true send disconnect message (if the disconnection is a clean disconnection) - * false don't send disconnect message (the disconnection is caused by a stealing link or the device is currently connected to another node) + * @return true send disconnect message (if the disconnection is a clean disconnection) false don't send disconnect message (the disconnection is caused by a stealing link or the device is + * currently connected to another node) */ public abstract boolean disconnect(AuthContext authContext); @@ -224,7 +220,7 @@ protected void enforceDeviceUserBound(ConnectionUserCouplingMode connectionUserC */ protected void checkConnectionCountByReservedUserId(KapuaId scopeId, KapuaId userId, long count) throws KapuaException { // check that no devices have this user as strict user - DeviceConnectionOptionQuery query = deviceConnectionOptionFactory.newQuery(scopeId); + final KapuaQuery query = new KapuaQuery(scopeId); query.setPredicate(query.attributePredicate(DeviceConnectionOptionAttributes.RESERVED_USER_ID, userId)); query.setLimit(1); @@ -268,7 +264,7 @@ protected ConnectionUserCouplingMode loadConnectionUserCouplingModeFromConfig(Ma */ protected DeviceConnection createDeviceConnection(AuthContext authContext) throws KapuaException { // TODO manage the stealing link event (may be a good idea to use different connect status (connect -stealing)? - DeviceConnectionCreator deviceConnectionCreator = deviceConnectionFactory.newCreator(KapuaEid.parseCompactId(authContext.getScopeId())); + DeviceConnectionCreator deviceConnectionCreator = new DeviceConnectionCreator(KapuaEid.parseCompactId(authContext.getScopeId())); deviceConnectionCreator.setStatus(DeviceConnectionStatus.CONNECTED); deviceConnectionCreator.setClientId(authContext.getClientId()); deviceConnectionCreator.setClientIp(authContext.getClientIp()); @@ -286,7 +282,8 @@ protected DeviceConnection createDeviceConnection(AuthContext authContext) throw * Updates a {@link DeviceConnection} using the info provided. * * @param authContext - * @param deviceConnection The {@link DeviceConnection} to update, or null if it needs to be created + * @param deviceConnection + * The {@link DeviceConnection} to update, or null if it needs to be created * @return The updated {@link DeviceConnection} * @throws KapuaException */ diff --git a/service/authentication/src/main/java/org/eclipse/kapua/service/authentication/authentication/UserAuthenticationLogic.java b/service/authentication/src/main/java/org/eclipse/kapua/service/authentication/authentication/UserAuthenticationLogic.java index ccb638962fb..c9cf462ac0a 100644 --- a/service/authentication/src/main/java/org/eclipse/kapua/service/authentication/authentication/UserAuthenticationLogic.java +++ b/service/authentication/src/main/java/org/eclipse/kapua/service/authentication/authentication/UserAuthenticationLogic.java @@ -12,7 +12,9 @@ *******************************************************************************/ package org.eclipse.kapua.service.authentication.authentication; -import com.codahale.metrics.Timer.Context; +import java.util.ArrayList; +import java.util.List; + import org.apache.shiro.ShiroException; import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.KapuaIllegalAccessException; @@ -26,7 +28,6 @@ import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.authorization.AuthorizationService; import org.eclipse.kapua.service.authorization.permission.Permission; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; import org.eclipse.kapua.service.device.registry.connection.DeviceConnection; import org.eclipse.kapua.service.device.registry.connection.DeviceConnectionFactory; import org.eclipse.kapua.service.device.registry.connection.DeviceConnectionService; @@ -34,8 +35,7 @@ import org.eclipse.kapua.service.device.registry.connection.option.DeviceConnectionOptionFactory; import org.eclipse.kapua.service.device.registry.connection.option.DeviceConnectionOptionService; -import java.util.ArrayList; -import java.util.List; +import com.codahale.metrics.Timer.Context; /** * User profile authentication logic implementation @@ -51,9 +51,8 @@ public UserAuthenticationLogic( DeviceConnectionOptionService deviceConnectionOptionService, AuthorizationService authorizationService, DeviceConnectionFactory deviceConnectionFactory, - PermissionFactory permissionFactory, DeviceConnectionService deviceConnectionService) { - super(aclCreator, authenticationMetric, deviceConnectionOptionFactory, deviceConnectionOptionService, authorizationService, deviceConnectionFactory, permissionFactory, deviceConnectionService); + super(aclCreator, authenticationMetric, deviceConnectionOptionFactory, deviceConnectionOptionService, authorizationService, deviceConnectionFactory, deviceConnectionService); } @Override @@ -123,15 +122,15 @@ protected List buildAuthorizationMap(UserPermissions userPermissions, A protected UserPermissions updatePermissions(AuthContext authContext) throws KapuaException { List permissions = new ArrayList<>(); KapuaId scopeId = KapuaEid.parseCompactId(authContext.getScopeId()); - permissions.add(permissionFactory.newPermission(Domains.BROKER, Actions.connect, scopeId)); - permissions.add(permissionFactory.newPermission(Domains.DEVICE_MANAGEMENT, Actions.read, scopeId)); - permissions.add(permissionFactory.newPermission(Domains.DEVICE_MANAGEMENT, Actions.write, scopeId)); - permissions.add(permissionFactory.newPermission(Domains.DATASTORE, Actions.read, scopeId)); - permissions.add(permissionFactory.newPermission(Domains.DATASTORE, Actions.write, scopeId)); + permissions.add(new Permission(Domains.BROKER, Actions.connect, scopeId)); + permissions.add(new Permission(Domains.DEVICE_MANAGEMENT, Actions.read, scopeId)); + permissions.add(new Permission(Domains.DEVICE_MANAGEMENT, Actions.write, scopeId)); + permissions.add(new Permission(Domains.DATASTORE, Actions.read, scopeId)); + permissions.add(new Permission(Domains.DATASTORE, Actions.write, scopeId)); UserPermissions userPermissions = new UserPermissions(authorizationService.isPermitted(permissions)); if (!userPermissions.isBrokerConnect()) { - throw new KapuaIllegalAccessException(permissionFactory.newPermission(Domains.BROKER, Actions.connect, scopeId).toString()); + throw new KapuaIllegalAccessException(new Permission(Domains.BROKER, Actions.connect, scopeId).toString()); } return userPermissions; } diff --git a/service/camel/pom.xml b/service/camel/pom.xml index 247c9dc88b7..af8be948d06 100644 --- a/service/camel/pom.xml +++ b/service/camel/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-service - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-service-camel diff --git a/service/client/pom.xml b/service/client/pom.xml index 256633f5f45..a361b042fde 100644 --- a/service/client/pom.xml +++ b/service/client/pom.xml @@ -17,7 +17,7 @@ org.eclipse.kapua kapua-service - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-service-client diff --git a/service/commons/elasticsearch/client-api/pom.xml b/service/commons/elasticsearch/client-api/pom.xml index 5d0ff5352a9..73650e7f6b8 100644 --- a/service/commons/elasticsearch/client-api/pom.xml +++ b/service/commons/elasticsearch/client-api/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-service-elasticsearch - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-service-elasticsearch-client-api diff --git a/service/commons/elasticsearch/client-api/src/main/java/org/eclipse/kapua/service/elasticsearch/client/ElasticsearchRepository.java b/service/commons/elasticsearch/client-api/src/main/java/org/eclipse/kapua/service/elasticsearch/client/ElasticsearchRepository.java index 2580650644d..efb9413048c 100644 --- a/service/commons/elasticsearch/client-api/src/main/java/org/eclipse/kapua/service/elasticsearch/client/ElasticsearchRepository.java +++ b/service/commons/elasticsearch/client-api/src/main/java/org/eclipse/kapua/service/elasticsearch/client/ElasticsearchRepository.java @@ -12,8 +12,12 @@ *******************************************************************************/ package org.eclipse.kapua.service.elasticsearch.client; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.node.ObjectNode; +import java.util.List; +import java.util.Set; +import java.util.function.Function; +import java.util.function.Supplier; +import java.util.stream.Collectors; + import org.eclipse.kapua.commons.cache.LocalCache; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.elasticsearch.client.exception.ClientException; @@ -37,20 +41,22 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ObjectNode; public abstract class ElasticsearchRepository< T extends Storable, L extends StorableListResult, Q extends StorableQuery> implements StorableRepository { + protected final ElasticsearchClientProvider elasticsearchClientProviderInstance; private final Class clazz; - private final StorableFactory storableFactory; + private final StorableFactory storableFactory; protected final StorablePredicateFactory storablePredicateFactory; protected final Logger logger = LoggerFactory.getLogger(this.getClass()); protected final LocalCache indexUpserted; + private final Function querySupplier; + private final Supplier listSupplier; protected abstract String indexResolver(KapuaId scopeId); @@ -63,26 +69,34 @@ public abstract class ElasticsearchRepository< protected ElasticsearchRepository( ElasticsearchClientProvider elasticsearchClientProviderInstance, Class clazz, - StorableFactory storableFactory, + StorableFactory storableFactory, StorablePredicateFactory storablePredicateFactory, - LocalCache indexesCache) { + LocalCache indexesCache, + Function querySupplier, + Supplier listSupplier) { this.elasticsearchClientProviderInstance = elasticsearchClientProviderInstance; this.storableFactory = storableFactory; this.storablePredicateFactory = storablePredicateFactory; this.clazz = clazz; this.indexUpserted = indexesCache; + this.querySupplier = querySupplier; + this.listSupplier = listSupplier; } protected ElasticsearchRepository( ElasticsearchClientProvider elasticsearchClientProviderInstance, Class clazz, - StorableFactory storableFactory, - StorablePredicateFactory storablePredicateFactory) { + StorableFactory storableFactory, + StorablePredicateFactory storablePredicateFactory, + Function querySupplier, + Supplier listSupplier) { this.elasticsearchClientProviderInstance = elasticsearchClientProviderInstance; this.storableFactory = storableFactory; this.storablePredicateFactory = storablePredicateFactory; this.clazz = clazz; this.indexUpserted = new LocalCache<>(0, null); + this.querySupplier = querySupplier; + this.listSupplier = listSupplier; } @Override @@ -92,7 +106,7 @@ public T find(KapuaId scopeId, StorableId id) { protected T doFind(KapuaId scopeId, String indexName, StorableId id) { try { - final Q idsQuery = storableFactory.newQuery(scopeId); + final Q idsQuery = querySupplier.apply(scopeId); idsQuery.setLimit(1); final IdsPredicate idsPredicate = storablePredicateFactory.newIdsPredicate(); @@ -123,7 +137,7 @@ public L query(Q query) { final String indexName = indexResolver(query.getScopeId()); synchIndex(indexName); final ResultList partialResult = elasticsearchClientProviderInstance.getElasticsearchClient().query(indexName, query, clazz); - final L res = storableFactory.newListResult(); + final L res = listSupplier.get(); res.addItems(partialResult.getResult()); res.setTotalCount(partialResult.getTotalCount()); setLimitExceed(query, partialResult.getTotalHitsExceedsCount(), res); @@ -229,7 +243,6 @@ public Set upsert(List items) { } } - protected void doUpsertIndex(String indexName) { final ElasticsearchClient elasticsearchClient; try { diff --git a/service/commons/elasticsearch/client-rest/pom.xml b/service/commons/elasticsearch/client-rest/pom.xml index 2fd83072d81..d11bfaaebdd 100644 --- a/service/commons/elasticsearch/client-rest/pom.xml +++ b/service/commons/elasticsearch/client-rest/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-service-elasticsearch - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-service-elasticsearch-client-rest diff --git a/service/commons/elasticsearch/pom.xml b/service/commons/elasticsearch/pom.xml index bb71bbfc719..fa86a235231 100644 --- a/service/commons/elasticsearch/pom.xml +++ b/service/commons/elasticsearch/pom.xml @@ -19,7 +19,7 @@ kapua-service-commons org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-service-elasticsearch diff --git a/service/commons/pom.xml b/service/commons/pom.xml index 01d92ffcdbc..f861384542e 100644 --- a/service/commons/pom.xml +++ b/service/commons/pom.xml @@ -19,7 +19,7 @@ kapua-service org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-service-commons diff --git a/service/commons/storable/api/pom.xml b/service/commons/storable/api/pom.xml index a8c7885fe32..c77a5d9d59a 100644 --- a/service/commons/storable/api/pom.xml +++ b/service/commons/storable/api/pom.xml @@ -19,7 +19,7 @@ kapua-service-storable org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-service-storable-api diff --git a/service/commons/storable/api/src/main/java/org/eclipse/kapua/service/storable/StorableFactory.java b/service/commons/storable/api/src/main/java/org/eclipse/kapua/service/storable/StorableFactory.java index 659f70ffe2e..df2b6e48108 100644 --- a/service/commons/storable/api/src/main/java/org/eclipse/kapua/service/storable/StorableFactory.java +++ b/service/commons/storable/api/src/main/java/org/eclipse/kapua/service/storable/StorableFactory.java @@ -13,10 +13,7 @@ package org.eclipse.kapua.service.storable; import org.eclipse.kapua.model.KapuaObjectFactory; -import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.storable.model.Storable; -import org.eclipse.kapua.service.storable.model.StorableListResult; -import org.eclipse.kapua.service.storable.model.query.StorableQuery; /** * {@link StorableFactory} definition. @@ -25,7 +22,7 @@ * * @since 1.3.0 */ -public interface StorableFactory, Q extends StorableQuery> extends KapuaObjectFactory { +public interface StorableFactory extends KapuaObjectFactory { /** * Instantiates a new {@link Storable}. @@ -35,20 +32,4 @@ public interface StorableFactory * It is the base {@code interface} for all {@link Object} creators that are {@link Storable}. * - * @param The {@link Storable} for which this is a {@link StorableCreator} for. + * @param + * The {@link Storable} for which this is a {@link StorableCreator} for. * @since 1.0.0 */ -public interface StorableCreator { +public class StorableCreator { + + private KapuaId scopeId; + + public StorableCreator() { + } + + public StorableCreator(KapuaId scopeId) { + this.scopeId = scopeId; + } /** * Gets the scope {@link KapuaId}. @@ -30,13 +40,18 @@ public interface StorableCreator { * @return The scope {@link KapuaId}. * @since 1.0.0 */ - KapuaId getScopeId(); + public KapuaId getScopeId() { + return scopeId; + } /** * Sets the scope {@link KapuaId}. * - * @param scopeId The scope {@link KapuaId}. + * @param scopeId + * The scope {@link KapuaId}. * @since 1.3.0 */ - void setScopeId(KapuaId scopeId); + public void setScopeId(KapuaId scopeId) { + this.scopeId = scopeId; + } } diff --git a/service/commons/storable/api/src/main/java/org/eclipse/kapua/service/storable/model/StorableListResult.java b/service/commons/storable/api/src/main/java/org/eclipse/kapua/service/storable/model/StorableListResult.java index 2b0ec146a47..bb58db06de2 100644 --- a/service/commons/storable/api/src/main/java/org/eclipse/kapua/service/storable/model/StorableListResult.java +++ b/service/commons/storable/api/src/main/java/org/eclipse/kapua/service/storable/model/StorableListResult.java @@ -12,32 +12,95 @@ *******************************************************************************/ package org.eclipse.kapua.service.storable.model; -import org.eclipse.kapua.KapuaSerializable; -import org.eclipse.kapua.model.query.KapuaQuery; -import org.eclipse.kapua.service.storable.model.query.StorableQuery; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; -import javax.validation.constraints.NotNull; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; -import java.util.Collection; -import java.util.List; + +import org.eclipse.kapua.KapuaSerializable; +import org.eclipse.kapua.model.query.KapuaQuery; +import org.eclipse.kapua.service.storable.model.query.StorableQuery; /** * {@link StorableListResult} definition. *

        * It is the base {@code interface} for all list of {@link Storable}s * - * @param The {@link Storable} for which this is a {@link StorableListResult} for. + * @param + * The {@link Storable} for which this is a {@link StorableListResult} for. * @since 1.0.0 */ @XmlRootElement(name = "result") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(propOrder = {"limitExceeded", "size", "items", "nextKey", "totalCount"}) -public interface StorableListResult extends KapuaSerializable { +@XmlType(propOrder = { "limitExceeded", "size", "items", "nextKey", "totalCount" }) +public abstract class StorableListResult implements KapuaSerializable { + + private static final long serialVersionUID = -6792613517586602315L; + + private boolean limitExceeded; + private ArrayList items; + private Object nextKey; + private Long totalCount; + + /** + * Constructor. + * + * @since 1.0.0 + */ + public StorableListResult() { + } + + /** + * Constructor. + * + * @param storables + * The {@link Storable}s to add to the {@link StorableListResult}. + * @param totalCount + * The total count of the {@link Storable}s matched. + * @since 1.3.0 + */ + public StorableListResult(List storables, Long totalCount) { + this(); + + addItems(storables); + setTotalCount(totalCount); + } + + /** + * Constructors. + * + * @param nextKey + * The {@link StorableListResult#getNextKey()}. + * @since 1.0.0 + * @deprecated Since 1.3.0, this is not used! + */ + @Deprecated + public StorableListResult(Object nextKey) { + this(); + this.nextKey = nextKey; + } + + /** + * Constructor. + * + * @param nextKeyOffset + * The {@link StorableListResult#getNextKey()}. + * @param totalCount + * The {@link StorableListResult#getTotalCount()}. + * @since 1.0.0 + * @deprecated Since 1.3.0, this is not used! + */ + @Deprecated + public StorableListResult(Object nextKeyOffset, Long totalCount) { + this(nextKeyOffset); + this.totalCount = totalCount; + } /** * Gets whether or not the {@link StorableQuery#getLimit()} has been exceeded. @@ -48,15 +111,20 @@ public interface StorableListResult extends KapuaSerializabl * @since 1.0.0 */ @XmlElement(name = "limitExceeded") - boolean isLimitExceeded(); + public boolean isLimitExceeded() { + return limitExceeded; + } /** * Sets whether or not the {@link StorableQuery#getLimit()} has been exceeded. * - * @param limitExceeded {@code true} if the {@link StorableQuery#getLimit()} has been exceeded, {@code false} otherwise. + * @param limitExceeded + * {@code true} if the {@link StorableQuery#getLimit()} has been exceeded, {@code false} otherwise. * @since 1.0.0 */ - void setLimitExceeded(boolean limitExceeded); + public void setLimitExceeded(boolean limitExceeded) { + this.limitExceeded = limitExceeded; + } /** * Gets the {@link Storable}s @@ -66,18 +134,28 @@ public interface StorableListResult extends KapuaSerializabl */ @XmlElementWrapper(name = "items") @XmlElement(name = "item") - List getItems(); + public List getItems() { + if (items == null) { + items = new ArrayList<>(); + } + + return items; + } /** * Gets the {@link Storable} at the given position in the {@link StorableListResult}. * - * @param i The position in the {@link StorableListResult} + * @param index + * The position in the {@link StorableListResult} * @return The {@link Storable} at the position - * @throws IndexOutOfBoundsException If position is not available. + * @throws IndexOutOfBoundsException + * If position is not available. * @see List#get(int) * @since 1.0.0 */ - E getItem(int i); + public E getItem(int index) { + return getItems().get(index); + } /** * Returns the first element in the {@link StorableListResult}. @@ -87,7 +165,9 @@ public interface StorableListResult extends KapuaSerializabl * @return The first element in the {@link Storable} or {@code null} if not present. * @since 1.0.0 */ - E getFirstItem(); + public E getFirstItem() { + return this.isEmpty() ? null : getItem(0); + } /** * Gets the result {@link StorableListResult} size. @@ -97,7 +177,9 @@ public interface StorableListResult extends KapuaSerializabl * @since 1.0.0 */ @XmlElement(name = "size") - int getSize(); + public int getSize() { + return getItems().size(); + } /** * Checks if the result {@link StorableListResult} is empty. @@ -106,24 +188,32 @@ public interface StorableListResult extends KapuaSerializabl * @see List#isEmpty() * @since 1.0.0 */ - boolean isEmpty(); + public boolean isEmpty() { + return getItems().isEmpty(); + } /** * Adds {@link Storable}s to the result {@link StorableListResult} * - * @param items The {@link Storable}s to add. + * @param items + * The {@link Storable}s to add. * @see List#addAll(Collection) * @since 1.0.0 */ - void addItems(Collection items); + public void addItems(Collection items) { + getItems().addAll(items); + } /** * Adds a {@link Storable} to the {@link StorableListResult}. * - * @param item The {@link Storable} to add. + * @param item + * The {@link Storable} to add. * @since 1.3.0 */ - void addItem(@NotNull E item); + public void addItem(E item) { + getItems().add(item); + } /** * Clears {@link Storable} result {@link StorableListResult} @@ -131,7 +221,9 @@ public interface StorableListResult extends KapuaSerializabl * @see List#clear() * @since 1.0.0 */ - void clearItems(); + public void clearItems() { + getItems().clear(); + } /** * Get the next key. @@ -143,7 +235,9 @@ public interface StorableListResult extends KapuaSerializabl * @since 1.0.0 */ @XmlElement(name = "nextKey") - Object getNextKey(); + public Object getNextKey() { + return nextKey; + } /** * Gets the total count of {@link Storable}s that match the {@link StorableQuery#getPredicate()}s regardless of {@link StorableQuery#getLimit()} and {@link StorableQuery#getOffset()} @@ -151,7 +245,9 @@ public interface StorableListResult extends KapuaSerializabl * @return The total count * @since 1.0.0 */ - Long getTotalCount(); + public Long getTotalCount() { + return totalCount; + } /** * Sets the total count of {@link Storable}s that match the {@link KapuaQuery#getPredicate()}s regardless of {@code limit} and {@code offset} @@ -160,6 +256,8 @@ public interface StorableListResult extends KapuaSerializabl * @since 1.0.0 */ @XmlElement(name = "totalCount") - void setTotalCount(Long totalCount); + public void setTotalCount(Long totalCount) { + this.totalCount = totalCount; + } } diff --git a/service/commons/storable/api/src/main/java/org/eclipse/kapua/service/storable/model/query/StorableField.java b/service/commons/storable/api/src/main/java/org/eclipse/kapua/service/storable/model/query/StorableField.java index 3e552225e4a..7f0308e7bbd 100644 --- a/service/commons/storable/api/src/main/java/org/eclipse/kapua/service/storable/model/query/StorableField.java +++ b/service/commons/storable/api/src/main/java/org/eclipse/kapua/service/storable/model/query/StorableField.java @@ -32,8 +32,7 @@ public interface StorableField { String field(); /** - * Watch out using this to get the {@link StorableField} actual name. - * Maybe {@link #field()} is what you are looking for! + * Watch out using this to get the {@link StorableField} actual name. Maybe {@link #field()} is what you are looking for! * * @return The {@link Enum#name()} * @since 1.3.0 @@ -41,4 +40,5 @@ public interface StorableField { */ @Deprecated String name(); + } diff --git a/service/commons/storable/api/src/main/java/org/eclipse/kapua/service/storable/model/query/StorableQuery.java b/service/commons/storable/api/src/main/java/org/eclipse/kapua/service/storable/model/query/StorableQuery.java index a86f562773d..5999f8895bc 100644 --- a/service/commons/storable/api/src/main/java/org/eclipse/kapua/service/storable/model/query/StorableQuery.java +++ b/service/commons/storable/api/src/main/java/org/eclipse/kapua/service/storable/model/query/StorableQuery.java @@ -12,24 +12,70 @@ *******************************************************************************/ package org.eclipse.kapua.service.storable.model.query; -import org.eclipse.kapua.model.KapuaEntity; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.model.id.KapuaIdAdapter; -import org.eclipse.kapua.service.storable.model.StorableListResult; -import org.eclipse.kapua.service.storable.model.query.predicate.StorablePredicate; +import java.util.ArrayList; +import java.util.List; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlTransient; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; -import java.util.List; + +import org.eclipse.kapua.model.KapuaEntity; +import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.id.KapuaIdAdapter; +import org.eclipse.kapua.service.storable.model.StorableListResult; +import org.eclipse.kapua.service.storable.model.query.predicate.StorablePredicate; /** * {@link StorableQuery} definition. * * @since 1.0.0 */ -public interface StorableQuery { +public abstract class StorableQuery { + + private StorablePredicate predicate; + + private KapuaId scopeId; + private Integer limit; + private Integer indexOffset; + private boolean askTotalCount; + private List sortFields; + private StorableFetchStyle fetchStyle; + private List fetchAttributes; + + /** + * Constructor. + *

        + * Forces the {@link StorableFetchStyle} to {@link StorableFetchStyle#SOURCE_FULL} + * + * @since 1.0.0 + */ + public StorableQuery() { + super(); + + setFetchStyle(StorableFetchStyle.SOURCE_FULL); + } + + /** + * Constructor. + * + * @param scopeId + * The scope KapuaId. + * @since 1.0.0 + */ + public StorableQuery(KapuaId scopeId) { + this(); + + setScopeId(scopeId); + } + + /** + * Gets the {@link StorableField}s. + * + * @return The {@link StorableField}s. + * @since 1.0.0 + */ + public abstract String[] getFields(); /** * Gets the fetch attribute names list. @@ -38,24 +84,35 @@ public interface StorableQuery { */ @XmlElementWrapper(name = "fetchAttributeName") @XmlElement(name = "fetchAttributeName") - public List getFetchAttributes(); + public List getFetchAttributes() { + if (fetchAttributes == null) { + fetchAttributes = new ArrayList<>(); + } + + return fetchAttributes; + } /** * Adds an attribute to the fetch attribute names list * - * @param fetchAttribute The fetch attribute to add to the list. + * @param fetchAttribute + * The fetch attribute to add to the list. * @since 1.0.0 */ - void addFetchAttributes(String fetchAttribute); + public void addFetchAttributes(String fetchAttribute) { + getFetchAttributes().add(fetchAttribute); + } /** - * Sets the fetch attribute names list.
        - * This list is a list of optional attributes of a {@link KapuaEntity} that can be fetched when querying. + * Sets the fetch attribute names list.
        This list is a list of optional attributes of a {@link KapuaEntity} that can be fetched when querying. * - * @param fetchAttributeNames The fetch attribute names list. + * @param fetchAttributeNames + * The fetch attribute names list. * @since 1.0.0 */ - void setFetchAttributes(List fetchAttributeNames); + public void setFetchAttributes(List fetchAttributeNames) { + fetchAttributes = fetchAttributeNames; + } /** * Gets the scope {@link KapuaId}. @@ -65,15 +122,20 @@ public interface StorableQuery { */ @XmlElement(name = "scopeId") @XmlJavaTypeAdapter(KapuaIdAdapter.class) - KapuaId getScopeId(); + public KapuaId getScopeId() { + return scopeId; + } /** * Sets the scope id * - * @param scopeId The scope {@link KapuaId}. + * @param scopeId + * The scope {@link KapuaId}. * @since 1.0.0 */ - void setScopeId(KapuaId scopeId); + public void setScopeId(KapuaId scopeId) { + this.scopeId = scopeId; + } /** * Gets the {@link StorablePredicate}s @@ -82,15 +144,20 @@ public interface StorableQuery { * @since 1.0.0 */ @XmlTransient - StorablePredicate getPredicate(); + public StorablePredicate getPredicate() { + return this.predicate; + } /** * Sets the {@link StorablePredicate}s * - * @param predicate The {@link StorablePredicate}s + * @param predicate + * The {@link StorablePredicate}s * @since 1.0.0 */ - void setPredicate(StorablePredicate predicate); + public void setPredicate(StorablePredicate predicate) { + this.predicate = predicate; + } /** * Gets the {@link StorableQuery} offset. @@ -99,21 +166,25 @@ public interface StorableQuery { * @since 1.0.0 */ @XmlElement(name = "offset") - Integer getOffset(); + public Integer getOffset() { + return indexOffset; + } /** * Set the {@link StorableQuery} offset in the result set from which start query. *

        - * If set to {@code null} the {@link StorableQuery} will start from the first result found. - * This also mean that {@link #setOffset(Integer)} with {@code 0} or {@code null} will produce the same result. + * If set to {@code null} the {@link StorableQuery} will start from the first result found. This also mean that {@link #setOffset(Integer)} with {@code 0} or {@code null} will produce the same + * result. *

        * This method and {@link #setLimit(Integer)} are meant to be used to paginate through the result set. * - * @param offset The {@link StorableQuery} offset. + * @param offset + * The {@link StorableQuery} offset. * @since 1.0.0 */ - void setOffset(Integer offset); - + public void setOffset(Integer offset) { + this.indexOffset = offset; + } /** * Gets the {@link StorableQuery} limit. @@ -122,7 +193,9 @@ public interface StorableQuery { * @since 1.0.0 */ @XmlElement(name = "limit") - Integer getLimit(); + public Integer getLimit() { + return limit; + } /** * Sets max number of result that will be fetched by this {@link KapuaEntity}. @@ -131,10 +204,13 @@ public interface StorableQuery { *

        * This method and {@link #setOffset(Integer)} are meant to be used to paginate through the result set. * - * @param limit The max number of result that will be fetched by this {@link KapuaEntity}. + * @param limit + * The max number of result that will be fetched by this {@link KapuaEntity}. * @since 1.0.0 */ - void setLimit(Integer limit); + public void setLimit(Integer limit) { + this.limit = limit; + } /** * Whether or not add the {@link StorableListResult#getTotalCount()} when processing the {@link StorableQuery}. @@ -143,15 +219,20 @@ public interface StorableQuery { * @since 1.0.0 */ @XmlElement(name = "askTotalCount") - boolean isAskTotalCount(); + public boolean isAskTotalCount() { + return askTotalCount; + } /** * Sets whether or not add the {@link StorableListResult#getTotalCount()} when processing the {@link StorableQuery}. * - * @param askTotalCount {@code true} to include the StorableListResult#getTotalCount(), {@code false} otherwise. + * @param askTotalCount + * {@code true} to include the StorableListResult#getTotalCount(), {@code false} otherwise. * @since 1.0.0 */ - void setAskTotalCount(boolean askTotalCount); + public void setAskTotalCount(boolean askTotalCount) { + this.askTotalCount = askTotalCount; + } /** * Gets the {@link StorableFetchStyle}. @@ -160,15 +241,20 @@ public interface StorableQuery { * @since 1.0.0 */ @XmlTransient - StorableFetchStyle getFetchStyle(); + public StorableFetchStyle getFetchStyle() { + return this.fetchStyle; + } /** * Sets the {@link StorableFetchStyle}. * - * @param fetchStyle The {@link StorableFetchStyle}. + * @param fetchStyle + * The {@link StorableFetchStyle}. * @since 1.0.0 */ - void setFetchStyle(StorableFetchStyle fetchStyle); + public void setFetchStyle(StorableFetchStyle fetchStyle) { + this.fetchStyle = fetchStyle; + } /** * Gets the {@link List} of {@link SortField}s @@ -177,31 +263,42 @@ public interface StorableQuery { * @since 1.0.0 */ @XmlJavaTypeAdapter(SortFieldXmlAdapter.class) - List getSortFields(); + public List getSortFields() { + if (sortFields == null) { + sortFields = new ArrayList<>(); + } + + return sortFields; + } /** * Sets the {@link List} of {@link SortField}s * - * @param sortFields The {@link List} of {@link SortField}s + * @param sortFields + * The {@link List} of {@link SortField}s * @since 1.0.0 */ - void setSortFields(List sortFields); + public void setSortFields(List sortFields) { + this.sortFields = sortFields; + } /** * Gets the included {@link StorableField}s according to the {@link StorableFetchStyle}. * - * @param fetchStyle The {@link StorableFetchStyle}. + * @param fetchStyle + * The {@link StorableFetchStyle}. * @return The included {@link StorableField}s according to the {@link StorableFetchStyle}. * @since 1.0.0 */ - String[] getIncludes(StorableFetchStyle fetchStyle); + public abstract String[] getIncludes(StorableFetchStyle fetchStyle); /** * Gets the excluded {@link StorableField}s according to the {@link StorableFetchStyle}. * - * @param fetchStyle The {@link StorableFetchStyle}. + * @param fetchStyle + * The {@link StorableFetchStyle}. * @return The excluded {@link StorableField}s according to the {@link StorableFetchStyle}. * @since 1.0.0 */ - String[] getExcludes(StorableFetchStyle fetchStyle); + public abstract String[] getExcludes(StorableFetchStyle fetchStyle); } diff --git a/service/commons/storable/internal/pom.xml b/service/commons/storable/internal/pom.xml index 232dc36ba55..2ca242ab448 100644 --- a/service/commons/storable/internal/pom.xml +++ b/service/commons/storable/internal/pom.xml @@ -19,7 +19,7 @@ kapua-service-storable org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-service-storable-internal diff --git a/service/commons/storable/internal/src/main/java/org/eclipse/kapua/service/storable/model/AbstractStorableListResult.java b/service/commons/storable/internal/src/main/java/org/eclipse/kapua/service/storable/model/AbstractStorableListResult.java deleted file mode 100644 index fd7ece2baba..00000000000 --- a/service/commons/storable/internal/src/main/java/org/eclipse/kapua/service/storable/model/AbstractStorableListResult.java +++ /dev/null @@ -1,154 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.storable.model; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -/** - * {@link StorableListResult} {@code abstract} implementation. - *

        - * This is the base for all {@link StorableListResult}'s implementations. - * - * @param The {@link Storable} for which this is a {@link StorableListResult} for. - * @since 1.0.0 - */ -public class AbstractStorableListResult implements StorableListResult { - - private static final long serialVersionUID = -6792613517586602315L; - - private boolean limitExceeded; - private ArrayList items; - private Object nextKey; - private Long totalCount; - - /** - * Constructor. - * - * @since 1.0.0 - */ - public AbstractStorableListResult() { - } - - /** - * Constructor. - * - * @param storables The {@link Storable}s to add to the {@link StorableListResult}. - * @param totalCount The total count of the {@link Storable}s matched. - * @since 1.3.0 - */ - public AbstractStorableListResult(List storables, Long totalCount) { - this(); - - addItems(storables); - setTotalCount(totalCount); - } - - /** - * Constructors. - * - * @param nextKey The {@link StorableListResult#getNextKey()}. - * @since 1.0.0 - * @deprecated Since 1.3.0, this is not used! - */ - @Deprecated - public AbstractStorableListResult(Object nextKey) { - this(); - this.nextKey = nextKey; - } - - /** - * Constructor. - * - * @param nextKeyOffset The {@link StorableListResult#getNextKey()}. - * @param totalCount The {@link StorableListResult#getTotalCount()}. - * @since 1.0.0 - * @deprecated Since 1.3.0, this is not used! - */ - @Deprecated - public AbstractStorableListResult(Object nextKeyOffset, Long totalCount) { - this(nextKeyOffset); - this.totalCount = totalCount; - } - - @Override - public boolean isLimitExceeded() { - return limitExceeded; - } - - @Override - public void setLimitExceeded(boolean limitExceeded) { - this.limitExceeded = limitExceeded; - } - - @Override - public E getItem(int index) { - return getItems().get(index); - } - - @Override - public E getFirstItem() { - return this.isEmpty() ? null : getItem(0); - } - - @Override - public int getSize() { - return getItems().size(); - } - - @Override - public boolean isEmpty() { - return getItems().isEmpty(); - } - - @Override - public List getItems() { - if (items == null) { - items = new ArrayList<>(); - } - - return items; - } - - @Override - public void addItems(Collection items) { - getItems().addAll(items); - } - - @Override - public void addItem(E item) { - getItems().add(item); - } - - @Override - public void clearItems() { - getItems().clear(); - } - - @Override - public Object getNextKey() { - return nextKey; - } - - @Override - public Long getTotalCount() { - return totalCount; - } - - @Override - public void setTotalCount(Long totalCount) { - this.totalCount = totalCount; - } - -} diff --git a/service/commons/storable/internal/src/main/java/org/eclipse/kapua/service/storable/model/query/AbstractStorableQuery.java b/service/commons/storable/internal/src/main/java/org/eclipse/kapua/service/storable/model/query/AbstractStorableQuery.java deleted file mode 100644 index 21199cc2681..00000000000 --- a/service/commons/storable/internal/src/main/java/org/eclipse/kapua/service/storable/model/query/AbstractStorableQuery.java +++ /dev/null @@ -1,167 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - * Red Hat Inc - *******************************************************************************/ -package org.eclipse.kapua.service.storable.model.query; - -import org.eclipse.kapua.commons.model.id.KapuaEid; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.storable.model.query.predicate.StorablePredicate; - -import java.util.ArrayList; -import java.util.List; - -/** - * {@link StorableQuery} {@code abstract} implementation. - *

        - * Is the base for all {@link StorableQuery} implementations. - * - * @since 1.0.0 - */ -public abstract class AbstractStorableQuery implements StorableQuery { - - private StorablePredicate predicate; - - private KapuaId scopeId; - private Integer limit; - private Integer indexOffset; - private boolean askTotalCount; - private List sortFields; - private StorableFetchStyle fetchStyle; - private List fetchAttributes; - - /** - * Constructor. - *

        - * Forces the {@link StorableFetchStyle} to {@link StorableFetchStyle#SOURCE_FULL} - * - * @since 1.0.0 - */ - public AbstractStorableQuery() { - super(); - - setFetchStyle(StorableFetchStyle.SOURCE_FULL); - } - - /** - * Constructor. - * - * @param scopeId The scope KapuaId. - * @since 1.0.0 - */ - public AbstractStorableQuery(KapuaId scopeId) { - this(); - - setScopeId(scopeId); - } - - /** - * Gets the {@link StorableField}s. - * - * @return The {@link StorableField}s. - * @since 1.0.0 - */ - public abstract String[] getFields(); - - @Override - public KapuaId getScopeId() { - return scopeId; - } - - @Override - public void setScopeId(KapuaId scopeId) { - this.scopeId = KapuaEid.parseKapuaId(scopeId); - } - - @Override - public StorablePredicate getPredicate() { - return this.predicate; - } - - @Override - public void setPredicate(StorablePredicate predicate) { - this.predicate = predicate; - } - - @Override - public Integer getOffset() { - return indexOffset; - } - - @Override - public void setOffset(Integer offset) { - this.indexOffset = offset; - } - - @Override - public void setLimit(Integer limit) { - this.limit = limit; - } - - @Override - public Integer getLimit() { - return limit; - } - - @Override - public boolean isAskTotalCount() { - return askTotalCount; - } - - @Override - public void setAskTotalCount(boolean askTotalCount) { - this.askTotalCount = askTotalCount; - } - - @Override - public List getSortFields() { - if (sortFields == null) { - sortFields = new ArrayList<>(); - } - - return sortFields; - } - - @Override - public void setSortFields(List sortFields) { - this.sortFields = sortFields; - } - - @Override - public StorableFetchStyle getFetchStyle() { - return this.fetchStyle; - } - - @Override - public void setFetchStyle(StorableFetchStyle fetchStyle) { - this.fetchStyle = fetchStyle; - } - - @Override - public List getFetchAttributes() { - if (fetchAttributes == null) { - fetchAttributes = new ArrayList<>(); - } - - return fetchAttributes; - } - - @Override - public void addFetchAttributes(String fetchAttribute) { - getFetchAttributes().add(fetchAttribute); - } - - @Override - public void setFetchAttributes(List fetchAttributeNames) { - fetchAttributes = fetchAttributeNames; - } -} diff --git a/service/commons/storable/internal/src/main/java/org/eclipse/kapua/service/storable/model/query/StorableFieldImpl.java b/service/commons/storable/internal/src/main/java/org/eclipse/kapua/service/storable/model/query/StorableFieldImpl.java deleted file mode 100644 index 5f9c5ff36da..00000000000 --- a/service/commons/storable/internal/src/main/java/org/eclipse/kapua/service/storable/model/query/StorableFieldImpl.java +++ /dev/null @@ -1,44 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.storable.model.query; - -/** - * {@link StorableField} implementation. - * - * @since 1.0.0 - */ -public class StorableFieldImpl implements StorableField { - - private final String field; - - /** - * Constructor. - * - * @param field The {@link StorableField} name. - * @since 1.0.0 - */ - public StorableFieldImpl(String field) { - this.field = field; - } - - @Override - public String field() { - return field; - } - - @Override - public String name() { - return field; - } - -} diff --git a/service/commons/storable/internal/src/main/java/org/eclipse/kapua/service/storable/model/query/predicate/AndPredicateImpl.java b/service/commons/storable/internal/src/main/java/org/eclipse/kapua/service/storable/model/query/predicate/AndPredicateImpl.java index a4ef55373db..8e747afdbab 100644 --- a/service/commons/storable/internal/src/main/java/org/eclipse/kapua/service/storable/model/query/predicate/AndPredicateImpl.java +++ b/service/commons/storable/internal/src/main/java/org/eclipse/kapua/service/storable/model/query/predicate/AndPredicateImpl.java @@ -12,16 +12,17 @@ *******************************************************************************/ package org.eclipse.kapua.service.storable.model.query.predicate; +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.kapua.service.storable.exception.MappingException; + import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.common.collect.Lists; -import org.eclipse.kapua.service.storable.exception.MappingException; - -import java.util.ArrayList; -import java.util.List; /** - * {@link AndPredicate} implementation. + * {@link AndPredicateImpl} implementation. * * @since 1.0.0 */ @@ -40,7 +41,8 @@ public AndPredicateImpl() { /** * Constructor. * - * @param storablePredicates The {@link StorablePredicate}s to add. + * @param storablePredicates + * The {@link StorablePredicate}s to add. * @since 1.0.0 */ public AndPredicateImpl(StorablePredicate... storablePredicates) { @@ -49,7 +51,6 @@ public AndPredicateImpl(StorablePredicate... storablePredicates) { setPredicates(Lists.newArrayList(storablePredicates)); } - @Override public List getPredicates() { if (predicates == null) { predicates = new ArrayList<>(); @@ -58,13 +59,11 @@ public List getPredicates() { return this.predicates; } - @Override - public AndPredicate addPredicate(StorablePredicate storablePredicate) { + public AndPredicateImpl addPredicate(StorablePredicate storablePredicate) { getPredicates().add(storablePredicate); return this; } - @Override public void setPredicates(List predicates) { this.predicates = predicates; } diff --git a/service/commons/storable/internal/src/main/java/org/eclipse/kapua/service/storable/model/query/predicate/StorablePredicateFactoryImpl.java b/service/commons/storable/internal/src/main/java/org/eclipse/kapua/service/storable/model/query/predicate/StorablePredicateFactoryImpl.java index 1c53c801060..28bfca84d3f 100644 --- a/service/commons/storable/internal/src/main/java/org/eclipse/kapua/service/storable/model/query/predicate/StorablePredicateFactoryImpl.java +++ b/service/commons/storable/internal/src/main/java/org/eclipse/kapua/service/storable/model/query/predicate/StorablePredicateFactoryImpl.java @@ -12,10 +12,10 @@ *******************************************************************************/ package org.eclipse.kapua.service.storable.model.query.predicate; -import org.eclipse.kapua.service.storable.model.query.StorableField; - import javax.inject.Singleton; +import org.eclipse.kapua.service.storable.model.query.StorableField; + @Singleton public class StorablePredicateFactoryImpl implements StorablePredicateFactory { diff --git a/service/commons/storable/pom.xml b/service/commons/storable/pom.xml index 14967b34dac..dca9a85d20c 100644 --- a/service/commons/storable/pom.xml +++ b/service/commons/storable/pom.xml @@ -19,7 +19,7 @@ kapua-service-commons org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-service-storable diff --git a/service/commons/utils/api/pom.xml b/service/commons/utils/api/pom.xml index 9d369e90ea6..6ea60f375f0 100644 --- a/service/commons/utils/api/pom.xml +++ b/service/commons/utils/api/pom.xml @@ -19,7 +19,7 @@ kapua-service-commons-utils org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-service-commons-utils-api diff --git a/service/commons/utils/internal/pom.xml b/service/commons/utils/internal/pom.xml index 555c35f87fb..a0921513958 100644 --- a/service/commons/utils/internal/pom.xml +++ b/service/commons/utils/internal/pom.xml @@ -19,7 +19,7 @@ kapua-service-commons-utils org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-service-commons-utils-internal diff --git a/service/commons/utils/pom.xml b/service/commons/utils/pom.xml index 570015d3c10..2295fc8e432 100644 --- a/service/commons/utils/pom.xml +++ b/service/commons/utils/pom.xml @@ -19,7 +19,7 @@ kapua-service-commons org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-service-commons-utils diff --git a/service/datastore/api/pom.xml b/service/datastore/api/pom.xml index 3d527ae63a0..f36618b5d84 100644 --- a/service/datastore/api/pom.xml +++ b/service/datastore/api/pom.xml @@ -19,7 +19,7 @@ org.eclipse.kapua kapua-datastore - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-datastore-api diff --git a/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/ChannelInfoFactory.java b/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/ChannelInfoFactory.java index 1c2308200c0..68f47f81667 100644 --- a/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/ChannelInfoFactory.java +++ b/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/ChannelInfoFactory.java @@ -13,8 +13,6 @@ package org.eclipse.kapua.service.datastore; import org.eclipse.kapua.service.datastore.model.ChannelInfo; -import org.eclipse.kapua.service.datastore.model.ChannelInfoListResult; -import org.eclipse.kapua.service.datastore.model.query.ChannelInfoQuery; import org.eclipse.kapua.service.storable.StorableFactory; /** @@ -24,5 +22,6 @@ * * @since 1.3.0 */ -public interface ChannelInfoFactory extends StorableFactory { +public interface ChannelInfoFactory extends StorableFactory { + } diff --git a/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/ClientInfoFactory.java b/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/ClientInfoFactory.java index e32e7a2d1ea..8b2cb73b104 100644 --- a/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/ClientInfoFactory.java +++ b/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/ClientInfoFactory.java @@ -13,8 +13,6 @@ package org.eclipse.kapua.service.datastore; import org.eclipse.kapua.service.datastore.model.ClientInfo; -import org.eclipse.kapua.service.datastore.model.ClientInfoListResult; -import org.eclipse.kapua.service.datastore.model.query.ClientInfoQuery; import org.eclipse.kapua.service.storable.StorableFactory; /** @@ -24,5 +22,6 @@ * * @since 1.3.0 */ -public interface ClientInfoFactory extends StorableFactory { +public interface ClientInfoFactory extends StorableFactory { + } diff --git a/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/MessageStoreFactory.java b/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/MessageStoreFactory.java index 812effec053..0e93e431107 100644 --- a/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/MessageStoreFactory.java +++ b/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/MessageStoreFactory.java @@ -13,9 +13,7 @@ package org.eclipse.kapua.service.datastore; import org.eclipse.kapua.service.datastore.model.DatastoreMessage; -import org.eclipse.kapua.service.datastore.model.MessageListResult; import org.eclipse.kapua.service.datastore.model.MetricInfo; -import org.eclipse.kapua.service.datastore.model.query.MessageQuery; import org.eclipse.kapua.service.storable.StorableFactory; /** @@ -25,5 +23,6 @@ * * @since 1.3.0 */ -public interface MessageStoreFactory extends StorableFactory { +public interface MessageStoreFactory extends StorableFactory { + } diff --git a/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/MetricInfoFactory.java b/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/MetricInfoFactory.java index 5aea903534c..c335225cf2b 100644 --- a/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/MetricInfoFactory.java +++ b/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/MetricInfoFactory.java @@ -13,8 +13,6 @@ package org.eclipse.kapua.service.datastore; import org.eclipse.kapua.service.datastore.model.MetricInfo; -import org.eclipse.kapua.service.datastore.model.MetricInfoListResult; -import org.eclipse.kapua.service.datastore.model.query.MetricInfoQuery; import org.eclipse.kapua.service.storable.StorableFactory; /** @@ -24,5 +22,6 @@ * * @since 1.3.0 */ -public interface MetricInfoFactory extends StorableFactory { +public interface MetricInfoFactory extends StorableFactory { + } diff --git a/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/ChannelInfoCreator.java b/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/ChannelInfoCreator.java index 12a1cbc4081..15528770163 100644 --- a/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/ChannelInfoCreator.java +++ b/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/ChannelInfoCreator.java @@ -12,17 +12,30 @@ *******************************************************************************/ package org.eclipse.kapua.service.datastore.model; +import java.util.Date; + +import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.storable.model.StorableCreator; import org.eclipse.kapua.service.storable.model.id.StorableId; -import java.util.Date; - /** * Channel information schema creator definition * * @since 1.0.0 */ -public interface ChannelInfoCreator extends StorableCreator { +public class ChannelInfoCreator extends StorableCreator { + + private String clientId; + private String name; + private StorableId messageId; + private Date messageTimestamp; + + public ChannelInfoCreator() { + } + + public ChannelInfoCreator(KapuaId scopeId) { + super(scopeId); + } /** * Get the client identifier @@ -30,13 +43,17 @@ public interface ChannelInfoCreator extends StorableCreator { * @return * @since 1.0.0 */ - String getClientId(); + public String getClientId() { + return this.clientId; + } /** * @param clientId * @since 1.3.0 */ - void setClientId(String clientId); + public void setClientId(String clientId) { + this.clientId = clientId; + } /** * Get the name @@ -44,7 +61,9 @@ public interface ChannelInfoCreator extends StorableCreator { * @return * @since 1.0.0 */ - String getName(); + public String getName() { + return name; + } /** * Set the channel name @@ -52,7 +71,9 @@ public interface ChannelInfoCreator extends StorableCreator { * @param name * @since 1.0.0 */ - void setName(String name); + public void setName(String name) { + this.name = name; + } /** * Get the message identifier (of the first message published on this channel) @@ -60,7 +81,9 @@ public interface ChannelInfoCreator extends StorableCreator { * @return * @since 1.0.0 */ - StorableId getMessageId(); + public StorableId getMessageId() { + return messageId; + } /** * Set the message identifier (of the first message published on this channel) @@ -68,7 +91,9 @@ public interface ChannelInfoCreator extends StorableCreator { * @param messageId * @since 1.0.0 */ - void setMessageId(StorableId messageId); + public void setMessageId(StorableId messageId) { + this.messageId = messageId; + } /** * Get the message timestamp (of the first message published on this channel) @@ -76,7 +101,9 @@ public interface ChannelInfoCreator extends StorableCreator { * @return * @since 1.0.0 */ - Date getMessageTimestamp(); + public Date getMessageTimestamp() { + return messageTimestamp; + } /** * Set the message timestamp (of the first message published on this channel) @@ -84,5 +111,8 @@ public interface ChannelInfoCreator extends StorableCreator { * @param messageTimestamp * @since 1.0.0 */ - void setMessageTimestamp(Date messageTimestamp); + public void setMessageTimestamp(Date messageTimestamp) { + this.messageTimestamp = messageTimestamp; + } + } diff --git a/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/ChannelInfoListResult.java b/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/ChannelInfoListResult.java index 3e5bad4a027..3db84383c2b 100644 --- a/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/ChannelInfoListResult.java +++ b/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/ChannelInfoListResult.java @@ -12,20 +12,18 @@ *******************************************************************************/ package org.eclipse.kapua.service.datastore.model; -import org.eclipse.kapua.service.datastore.model.xml.ChannelInfoXmlRegistry; -import org.eclipse.kapua.service.storable.model.StorableListResult; - import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; +import org.eclipse.kapua.service.storable.model.StorableListResult; + /** - * Channel information query result list definition.
        - * This object contains the list of the channel information objects retrieved by the search service. + * Channel information query result list definition.
        This object contains the list of the channel information objects retrieved by the search service. * * @since 1.0 */ @XmlRootElement(name = "channelInfos") -@XmlType(factoryClass = ChannelInfoXmlRegistry.class, factoryMethod = "newListResult") -public interface ChannelInfoListResult extends StorableListResult { +@XmlType +public class ChannelInfoListResult extends StorableListResult { } diff --git a/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/ClientInfoCreator.java b/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/ClientInfoCreator.java index 3eb1dd1d6f5..09e6ec0c5d6 100644 --- a/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/ClientInfoCreator.java +++ b/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/ClientInfoCreator.java @@ -12,26 +12,36 @@ *******************************************************************************/ package org.eclipse.kapua.service.datastore.model; +import java.util.Date; + import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.storable.model.StorableCreator; import org.eclipse.kapua.service.storable.model.id.StorableId; -import java.util.Date; - /** * Client information schema creator definition * * @since 1.0.0 */ -public interface ClientInfoCreator extends StorableCreator { +public class ClientInfoCreator extends StorableCreator { + + private String clientId; + private StorableId messageId; + private Date messageTimestamp; + + public ClientInfoCreator() { + } /** - * Get the account + * Construct a client information creator for the given account * - * @return + * @param scopeId + * The scope {@link KapuaId} * @since 1.0.0 */ - KapuaId getScopeId(); + public ClientInfoCreator(KapuaId scopeId) { + super(scopeId); + } /** * Get the client identifier @@ -39,7 +49,9 @@ public interface ClientInfoCreator extends StorableCreator { * @return * @since 1.0.0 */ - String getClientId(); + public String getClientId() { + return clientId; + } /** * Set the client identifier @@ -47,7 +59,9 @@ public interface ClientInfoCreator extends StorableCreator { * @param clientId * @since 1.0.0 */ - void setClientId(String clientId); + public void setClientId(String clientId) { + this.clientId = clientId; + } /** * Get the message identifier (of the first message published by this client) @@ -55,7 +69,9 @@ public interface ClientInfoCreator extends StorableCreator { * @return * @since 1.0.0 */ - StorableId getMessageId(); + public StorableId getMessageId() { + return messageId; + } /** * Set the message identifier (of the first message published by this client) @@ -63,7 +79,9 @@ public interface ClientInfoCreator extends StorableCreator { * @param messageId * @since 1.0.0 */ - void setMessageId(StorableId messageId); + public void setMessageId(StorableId messageId) { + this.messageId = messageId; + } /** * Get the message timestamp (of the first message published by this client) @@ -71,7 +89,9 @@ public interface ClientInfoCreator extends StorableCreator { * @return * @since 1.0.0 */ - Date getMessageTimestamp(); + public Date getMessageTimestamp() { + return messageTimestamp; + } /** * Set the message timestamp (of the first message published by this client) @@ -79,5 +99,8 @@ public interface ClientInfoCreator extends StorableCreator { * @param messageTimestamp * @since 1.0.0 */ - void setMessageTimestamp(Date messageTimestamp); + public void setMessageTimestamp(Date messageTimestamp) { + this.messageTimestamp = messageTimestamp; + } + } diff --git a/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/ClientInfoListResult.java b/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/ClientInfoListResult.java index 35907e5c477..c948808f9e0 100644 --- a/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/ClientInfoListResult.java +++ b/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/ClientInfoListResult.java @@ -12,20 +12,41 @@ *******************************************************************************/ package org.eclipse.kapua.service.datastore.model; -import org.eclipse.kapua.service.datastore.model.xml.ClientInfoXmlRegistry; -import org.eclipse.kapua.service.storable.model.StorableListResult; - import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; +import org.eclipse.kapua.service.elasticsearch.client.model.ResultList; +import org.eclipse.kapua.service.storable.model.StorableListResult; + /** - * Client information query result list definition.
        - * This object contains the list of the client information objects retrieved by the search service. + * Client information query result list definition.
        This object contains the list of the client information objects retrieved by the search service. * * @since 1.0 */ @XmlRootElement(name = "clientInfos") -@XmlType(factoryClass = ClientInfoXmlRegistry.class, factoryMethod = "newListResult") -public interface ClientInfoListResult extends StorableListResult { +@XmlType +public class ClientInfoListResult extends StorableListResult { + + private static final long serialVersionUID = -1398721444405133343L; + + /** + * Constructor. + * + * @since 1.0.0 + */ + public ClientInfoListResult() { + super(); + } + + /** + * Constructor. + * + * @param resultList + * The {@link ResultList} to add. + * @since 1.0.0 + */ + public ClientInfoListResult(ResultList resultList) { + super(resultList.getResult(), resultList.getTotalCount()); + } } diff --git a/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/MessageListResult.java b/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/MessageListResult.java index 4e2f0e70fec..6b3cfb0d913 100644 --- a/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/MessageListResult.java +++ b/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/MessageListResult.java @@ -12,20 +12,40 @@ *******************************************************************************/ package org.eclipse.kapua.service.datastore.model; -import org.eclipse.kapua.service.datastore.model.xml.DatastoreMessageXmlRegistry; -import org.eclipse.kapua.service.storable.model.StorableListResult; - import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; +import org.eclipse.kapua.service.elasticsearch.client.model.ResultList; +import org.eclipse.kapua.service.storable.model.StorableListResult; + /** - * Message information query result list definition.
        - * This object contains the list of the message objects retrieved by the search service. + * Message information query result list definition.
        This object contains the list of the message objects retrieved by the search service. * * @since 1.0 */ @XmlRootElement(name = "datastoreMessages") -@XmlType(factoryClass = DatastoreMessageXmlRegistry.class, factoryMethod = "newListResult") -public interface MessageListResult extends StorableListResult { +@XmlType +public class MessageListResult extends StorableListResult { + + private static final long serialVersionUID = 1L; + + /** + * Constructor. + * + * @since 1.0.0 + */ + public MessageListResult() { + super(); + } + /** + * Constructor. + * + * @param resultList + * The {@link ResultList} to add. + * @since 1.0.0 + */ + public MessageListResult(ResultList resultList) { + super(resultList.getResult(), resultList.getTotalCount()); + } } diff --git a/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/MetricInfoCreator.java b/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/MetricInfoCreator.java index c214aa79565..a4d9bc69df1 100644 --- a/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/MetricInfoCreator.java +++ b/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/MetricInfoCreator.java @@ -12,26 +12,41 @@ *******************************************************************************/ package org.eclipse.kapua.service.datastore.model; +import java.util.Date; + import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.storable.model.StorableCreator; import org.eclipse.kapua.service.storable.model.id.StorableId; -import java.util.Date; - /** * Metric information schema creator definition * * @since 1.0.0 */ -public interface MetricInfoCreator extends StorableCreator { +public class MetricInfoCreator extends StorableCreator { + + private String clientId; + private String channel; + + private String name; + private Class metricType; + + private StorableId messageId; + private Date messageTimestamp; + + public MetricInfoCreator() { + } /** - * Get the account + * Constructor. * - * @return + * @param scopeId + * The scope {@link KapuaId} * @since 1.0.0 */ - KapuaId getScopeId(); + public MetricInfoCreator(KapuaId scopeId) { + super(scopeId); + } /** * Get the client identifier @@ -39,15 +54,20 @@ public interface MetricInfoCreator extends StorableCreator { * @return * @since 1.0.0 */ - String getClientId(); + public String getClientId() { + return this.clientId; + } /** * Sets the client identifier * - * @param clientId The client identifier + * @param clientId + * The client identifier * @since 1.0.0 */ - void setClientId(String clientId); + public void setClientId(String clientId) { + this.clientId = clientId; + } /** * Get the channel @@ -55,7 +75,9 @@ public interface MetricInfoCreator extends StorableCreator { * @return * @since 1.0.0 */ - String getChannel(); + public String getChannel() { + return channel; + } /** * Set the channel @@ -63,7 +85,9 @@ public interface MetricInfoCreator extends StorableCreator { * @param channel * @since 1.0.0 */ - void setChannel(String channel); + public void setChannel(String channel) { + this.channel = channel; + } /** * Get the metric name @@ -71,7 +95,9 @@ public interface MetricInfoCreator extends StorableCreator { * @return * @since 1.0.0 */ - String getName(); + public String getName() { + return name; + } /** * Set the metric name @@ -79,7 +105,9 @@ public interface MetricInfoCreator extends StorableCreator { * @param name * @since 1.0.0 */ - void setName(String name); + public void setName(String name) { + this.name = name; + } /** * Get the metric type @@ -87,15 +115,20 @@ public interface MetricInfoCreator extends StorableCreator { * @return * @since 1.0.0 */ - Class getMetricType(); + public Class getMetricType() { + return metricType; + } /** * Sets the metric type * - * @param metricType The metric type + * @param metricType + * The metric type * @since 1.0.0 */ - void setMetricType(Class metricType); + public void setMetricType(Class metricType) { + this.metricType = metricType; + } /** * Get the message identifier (of the first message published that containing this metric) @@ -103,7 +136,9 @@ public interface MetricInfoCreator extends StorableCreator { * @return * @since 1.0.0 */ - StorableId getMessageId(); + public StorableId getMessageId() { + return messageId; + } /** * Set the message identifier (of the first message published that containing this metric) @@ -111,7 +146,9 @@ public interface MetricInfoCreator extends StorableCreator { * @param messageId * @since 1.0.0 */ - void setMessageId(StorableId messageId); + public void setMessageId(StorableId messageId) { + this.messageId = messageId; + } /** * Get the message timestamp (of the first message published that containing this metric) @@ -119,7 +156,9 @@ public interface MetricInfoCreator extends StorableCreator { * @return * @since 1.0.0 */ - Date getMessageTimestamp(); + public Date getMessageTimestamp() { + return messageTimestamp; + } /** * Set the message timestamp (of the first message published that containing this metric) @@ -127,5 +166,8 @@ public interface MetricInfoCreator extends StorableCreator { * @param messageTimestamp * @since 1.0.0 */ - void setMessageTimestamp(Date messageTimestamp); + public void setMessageTimestamp(Date messageTimestamp) { + this.messageTimestamp = messageTimestamp; + } + } diff --git a/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/MetricInfoListResult.java b/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/MetricInfoListResult.java index 72ae8058d4c..2f749737636 100644 --- a/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/MetricInfoListResult.java +++ b/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/MetricInfoListResult.java @@ -12,20 +12,40 @@ *******************************************************************************/ package org.eclipse.kapua.service.datastore.model; -import org.eclipse.kapua.service.datastore.model.xml.MetricInfoXmlRegistry; -import org.eclipse.kapua.service.storable.model.StorableListResult; - import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; +import org.eclipse.kapua.service.elasticsearch.client.model.ResultList; +import org.eclipse.kapua.service.storable.model.StorableListResult; + /** - * Metric information query result list definition.
        - * This object contains the list of the metric information objects retrieved by the search service. + * Metric information query result list definition.
        This object contains the list of the metric information objects retrieved by the search service. * * @since 1.0 */ @XmlRootElement(name = "metricInfos") -@XmlType(factoryClass = MetricInfoXmlRegistry.class, factoryMethod = "newListResult") -public interface MetricInfoListResult extends StorableListResult { +@XmlType +public class MetricInfoListResult extends StorableListResult { + + private static final long serialVersionUID = 9057086672566426909L; + + /** + * Constructor. + * + * @since 1.0.0 + */ + public MetricInfoListResult() { + super(); + } + /** + * Constructor. + * + * @param resultList + * The {@link ResultList} to add. + * @since 1.0.0 + */ + public MetricInfoListResult(ResultList resultList) { + super(resultList.getResult(), resultList.getTotalCount()); + } } diff --git a/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/query/ChannelInfoField.java b/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/query/ChannelInfoField.java new file mode 100644 index 00000000000..fe0a95b7b6f --- /dev/null +++ b/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/query/ChannelInfoField.java @@ -0,0 +1,70 @@ +/******************************************************************************* + * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Eurotech - initial API and implementation + *******************************************************************************/ +package org.eclipse.kapua.service.datastore.model.query; + +import org.eclipse.kapua.service.datastore.model.ChannelInfo; +import org.eclipse.kapua.service.storable.model.query.StorableField; + +/** + * This enumeration defines the fields names used in the {@link ChannelInfo} client schema + * + * @since 1.0.0 + */ +public enum ChannelInfoField implements StorableField { + /** + * Channel + * + * @since 1.0.0 + */ + CHANNEL(ChannelInfoSchema.CHANNEL_NAME), + + /** + * Client identifier + * + * @since 1.0.0 + */ + CLIENT_ID(ChannelInfoSchema.CHANNEL_CLIENT_ID), + + /** + * Scope id + * + * @since 1.0.0 + */ + SCOPE_ID(ChannelInfoSchema.CHANNEL_SCOPE_ID), + + /** + * Timestamp + * + * @since 1.0.0 + */ + TIMESTAMP(ChannelInfoSchema.CHANNEL_TIMESTAMP), + + /** + * Message identifier + * + * @since 1.0.0 + */ + MESSAGE_ID(ChannelInfoSchema.CHANNEL_MESSAGE_ID); + + private String field; + + private ChannelInfoField(String name) { + this.field = name; + } + + @Override + public String field() { + return field; + } + +} diff --git a/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/query/ChannelInfoQuery.java b/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/query/ChannelInfoQuery.java index 549991ed52c..a5edf969e58 100644 --- a/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/query/ChannelInfoQuery.java +++ b/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/query/ChannelInfoQuery.java @@ -12,14 +12,18 @@ *******************************************************************************/ package org.eclipse.kapua.service.datastore.model.query; -import org.eclipse.kapua.service.datastore.model.xml.ChannelInfoXmlRegistry; -import org.eclipse.kapua.service.storable.model.query.StorableQuery; +import java.util.Collections; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; +import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.service.storable.model.query.SortField; +import org.eclipse.kapua.service.storable.model.query.StorableFetchStyle; +import org.eclipse.kapua.service.storable.model.query.StorableQuery; + /** * Channel information schema query definition * @@ -27,7 +31,42 @@ */ @XmlRootElement(name = "query") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = ChannelInfoXmlRegistry.class, factoryMethod = "newQuery") -public interface ChannelInfoQuery extends StorableQuery { +@XmlType +public class ChannelInfoQuery extends StorableQuery { + + public ChannelInfoQuery() { + setSortFields(Collections.singletonList(SortField.ascending(ChannelInfoSchema.CHANNEL_NAME))); + } + + /** + * Constructor. + * + * @param scopeId + * The scope {@link KapuaId}. + * @since 1.0.0 + */ + public ChannelInfoQuery(KapuaId scopeId) { + super(scopeId); + setSortFields(Collections.singletonList(SortField.ascending(ChannelInfoSchema.CHANNEL_NAME))); + } + + @Override + public String[] getIncludes(StorableFetchStyle fetchStyle) { + return new String[] { "*" }; + } + + @Override + public String[] getExcludes(StorableFetchStyle fetchStyle) { + return new String[] { "" }; + } + + @Override + public String[] getFields() { + return new String[] { ChannelInfoField.SCOPE_ID.field(), + ChannelInfoField.CHANNEL.field(), + ChannelInfoField.TIMESTAMP.field(), + ChannelInfoField.MESSAGE_ID.field(), + ChannelInfoField.CLIENT_ID.field() }; + } } diff --git a/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/query/ChannelInfoSchema.java b/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/query/ChannelInfoSchema.java new file mode 100644 index 00000000000..f2205275a31 --- /dev/null +++ b/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/query/ChannelInfoSchema.java @@ -0,0 +1,67 @@ +/******************************************************************************* + * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Eurotech - initial API and implementation + *******************************************************************************/ +package org.eclipse.kapua.service.datastore.model.query; + +import org.eclipse.kapua.service.datastore.model.ChannelInfo; + +/** + * {@link ChannelInfo} schema definition. + * + * @since 1.0.0 + */ +public class ChannelInfoSchema { + + /** + * @since 1.0.0 + */ + private ChannelInfoSchema() { + } + + /** + * Channel information schema name + * + * @since 1.0.0 + */ + public static final String CHANNEL_TYPE_NAME = "channel"; + /** + * Channel information - channel + * + * @since 1.0.0 + */ + public static final String CHANNEL_NAME = "channel"; + /** + * Channel information - client identifier + * + * @since 1.0.0 + */ + public static final String CHANNEL_CLIENT_ID = "client_id"; + /** + * Channel information - scope id + * + * @since 1.0.0 + */ + public static final String CHANNEL_SCOPE_ID = "scope_id"; + /** + * Channel information - message timestamp (of the first message published in this channel) + * + * @since 1.0.0 + */ + public static final String CHANNEL_TIMESTAMP = "timestamp"; + /** + * Channel information - message identifier (of the first message published in this channel) + * + * @since 1.0.0 + */ + public static final String CHANNEL_MESSAGE_ID = "message_id"; + +} diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/mediator/ClientInfoField.java b/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/query/ClientInfoField.java similarity index 52% rename from service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/mediator/ClientInfoField.java rename to service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/query/ClientInfoField.java index 78eddc75dd6..10d14e5234e 100644 --- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/mediator/ClientInfoField.java +++ b/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/query/ClientInfoField.java @@ -10,13 +10,9 @@ * Contributors: * Eurotech - initial API and implementation *******************************************************************************/ -package org.eclipse.kapua.service.datastore.internal.mediator; +package org.eclipse.kapua.service.datastore.model.query; -import org.eclipse.kapua.locator.KapuaLocator; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.datastore.internal.schema.ClientInfoSchema; import org.eclipse.kapua.service.datastore.model.ClientInfo; -import org.eclipse.kapua.service.storable.model.id.StorableId; import org.eclipse.kapua.service.storable.model.query.StorableField; /** @@ -65,35 +61,4 @@ public String field() { return field; } - /** - * Get the client identifier (combining accountName and clientId).
        - * If the id is null then it is generated - * - * @param id - * @param scopeId - * @param clientId - * @return - */ - public static String getOrDeriveId(StorableId id, KapuaId scopeId, String clientId) { - if (id == null) { - //TODO: FIXME: REMOVE: A collaborator in a data class? Behaviour should not be part of a data class! - return KapuaLocator.getInstance().getComponent(DatastoreUtils.class).getHashCode(scopeId.toCompactId(), clientId); - } else { - return id.toString(); - } - } - - /** - * Get the client identifier (combining accountName and clientId).
        - * If the id is null then it is generated - * - * @param id - * @param clientInfo - * @return - */ - public static String getOrDeriveId(StorableId id, ClientInfo clientInfo) { - return getOrDeriveId(id, clientInfo.getScopeId(), clientInfo.getClientId()); - } - - } diff --git a/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/query/ClientInfoQuery.java b/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/query/ClientInfoQuery.java index 0efec444e69..08a9f56dd2c 100644 --- a/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/query/ClientInfoQuery.java +++ b/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/query/ClientInfoQuery.java @@ -12,14 +12,18 @@ *******************************************************************************/ package org.eclipse.kapua.service.datastore.model.query; -import org.eclipse.kapua.service.datastore.model.xml.ClientInfoXmlRegistry; -import org.eclipse.kapua.service.storable.model.query.StorableQuery; +import java.util.Collections; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; +import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.service.storable.model.query.SortField; +import org.eclipse.kapua.service.storable.model.query.StorableFetchStyle; +import org.eclipse.kapua.service.storable.model.query.StorableQuery; + /** * Client information schema query definition * @@ -27,7 +31,34 @@ */ @XmlRootElement(name = "query") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = ClientInfoXmlRegistry.class, factoryMethod = "newQuery") -public interface ClientInfoQuery extends StorableQuery { +@XmlType +public class ClientInfoQuery extends StorableQuery { + + public ClientInfoQuery() { + setSortFields(Collections.singletonList(SortField.ascending(ClientInfoSchema.CLIENT_ID))); + } + public ClientInfoQuery(KapuaId scopeId) { + super(scopeId); + setSortFields(Collections.singletonList(SortField.ascending(ClientInfoSchema.CLIENT_ID))); + } + + @Override + public String[] getIncludes(StorableFetchStyle fetchStyle) { + return new String[] { "*" }; + } + + @Override + public String[] getExcludes(StorableFetchStyle fetchStyle) { + return new String[] { "" }; + } + + @Override + public String[] getFields() { + return new String[] { ClientInfoField.SCOPE_ID.field(), + ClientInfoField.CLIENT_ID.field(), + ClientInfoField.TIMESTAMP.field(), + ClientInfoField.MESSAGE_ID.field() }; + } } + diff --git a/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/query/ClientInfoSchema.java b/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/query/ClientInfoSchema.java new file mode 100644 index 00000000000..07dee6bc071 --- /dev/null +++ b/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/query/ClientInfoSchema.java @@ -0,0 +1,64 @@ +/******************************************************************************* + * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Eurotech - initial API and implementation + *******************************************************************************/ +package org.eclipse.kapua.service.datastore.model.query; + +import org.eclipse.kapua.service.datastore.model.ClientInfo; + +/** + * {@link ClientInfo} schema definition. + * + * @since 1.0.0 + */ +public class ClientInfoSchema { + + /** + * @since 1.0.0 + */ + private ClientInfoSchema() { + } + + /** + * Client information schema name. + * + * @since 1.0.0 + */ + public static final String CLIENT_TYPE_NAME = "client"; + + /** + * Client information - client identifier + * + * @since 1.0.0 + */ + public static final String CLIENT_ID = "client_id"; + + /** + * Client information - scope id + * + * @since 1.0.0 + */ + public static final String CLIENT_SCOPE_ID = "scope_id"; + + /** + * Client information - message timestamp (of the first message published in this channel) + * + * @since 1.0.0 + */ + public static final String CLIENT_TIMESTAMP = "timestamp"; + + /** + * Client information - message identifier (of the first message published in this channel) + * + * @since 1.0.0 + */ + public static final String CLIENT_MESSAGE_ID = "message_id"; +} diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/mediator/MessageField.java b/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/query/MessageField.java similarity index 95% rename from service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/mediator/MessageField.java rename to service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/query/MessageField.java index b1b8dd8aa05..337ff222313 100644 --- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/mediator/MessageField.java +++ b/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/query/MessageField.java @@ -10,9 +10,8 @@ * Contributors: * Eurotech - initial API and implementation *******************************************************************************/ -package org.eclipse.kapua.service.datastore.internal.mediator; +package org.eclipse.kapua.service.datastore.model.query; -import org.eclipse.kapua.service.datastore.internal.schema.MessageSchema; import org.eclipse.kapua.service.storable.model.query.StorableField; /** diff --git a/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/query/MessageQuery.java b/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/query/MessageQuery.java index ed1aa813230..441ae053da3 100644 --- a/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/query/MessageQuery.java +++ b/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/query/MessageQuery.java @@ -12,14 +12,18 @@ *******************************************************************************/ package org.eclipse.kapua.service.datastore.model.query; -import org.eclipse.kapua.service.datastore.model.xml.DatastoreMessageXmlRegistry; -import org.eclipse.kapua.service.storable.model.query.StorableQuery; +import java.util.Collections; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; +import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.service.storable.model.query.SortField; +import org.eclipse.kapua.service.storable.model.query.StorableFetchStyle; +import org.eclipse.kapua.service.storable.model.query.StorableQuery; + /** * Datastore message schema query definition * @@ -27,7 +31,69 @@ */ @XmlRootElement(name = "query") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = DatastoreMessageXmlRegistry.class, factoryMethod = "newQuery") -public interface MessageQuery extends StorableQuery { +@XmlType +public class MessageQuery extends StorableQuery { + + public MessageQuery() { + setSortFields(Collections.singletonList(SortField.descending(MessageSchema.MESSAGE_TIMESTAMP))); + } + + /** + * Constructor. + * + * @param scopeId + * The scope {@link KapuaId}. + * @since 1.0.0 + */ + public MessageQuery(KapuaId scopeId) { + super(scopeId); + + setSortFields(Collections.singletonList(SortField.descending(MessageSchema.MESSAGE_TIMESTAMP))); + } + + @Override + public String[] getIncludes(StorableFetchStyle fetchStyle) { + // Fetch mode + String[] includeSource = null; + switch (fetchStyle) { + case FIELDS: + includeSource = getFields(); + break; + case SOURCE_SELECT: + includeSource = new String[] { MessageSchema.MESSAGE_CAPTURED_ON, MessageSchema.MESSAGE_POSITION + ".*", MessageSchema.MESSAGE_METRICS + ".*" }; + break; + case SOURCE_FULL: + includeSource = new String[] { "*" }; + } + return includeSource; + } + + @Override + public String[] getExcludes(StorableFetchStyle fetchStyle) { + // Fetch mode + String[] excludeSource = null; + switch (fetchStyle) { + case FIELDS: + excludeSource = new String[] { "" }; + break; + case SOURCE_SELECT: + excludeSource = new String[] { MessageSchema.MESSAGE_BODY }; + break; + case SOURCE_FULL: + excludeSource = new String[] { "" }; + } + return excludeSource; + } + + @Override + public String[] getFields() { + return new String[] { + MessageField.MESSAGE_ID.field(), + MessageField.SCOPE_ID.field(), + MessageField.DEVICE_ID.field(), + MessageField.CLIENT_ID.field(), + MessageField.CHANNEL.field(), + MessageField.TIMESTAMP.field() }; + } } diff --git a/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/query/MessageSchema.java b/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/query/MessageSchema.java new file mode 100644 index 00000000000..c0ded8bd89c --- /dev/null +++ b/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/query/MessageSchema.java @@ -0,0 +1,262 @@ +/******************************************************************************* + * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Eurotech - initial API and implementation + *******************************************************************************/ +package org.eclipse.kapua.service.datastore.model.query; + +import org.eclipse.kapua.message.Message; + +/** + * {@link Message} schema definition. + * + * @since 1.0.0 + */ +public class MessageSchema { + + /** + * @since 1.0.0 + */ + private MessageSchema() { + } + + /** + * Message schema name + * + * @since 1.0.0 + */ + public static final String MESSAGE_TYPE_NAME = "message"; + + /** + * Message id + * + * @since 1.0.0 + */ + public static final String MESSAGE_ID = "message_id"; + + /** + * Message timestamp + * + * @since 1.0.0 + */ + public static final String MESSAGE_TIMESTAMP = "timestamp"; + + /** + * Message received on timestamp + * + * @since 1.0.0 + */ + public static final String MESSAGE_RECEIVED_ON = "received_on"; + + /** + * Message received by address + * + * @since 1.0.0 + */ + public static final String MESSAGE_IP_ADDRESS = "ip_address"; + + /** + * Message scope id + * + * @since 1.0.0 + */ + public static final String MESSAGE_SCOPE_ID = "scope_id"; + + /** + * Message device identifier + * + * @since 1.0.0 + */ + public static final String MESSAGE_DEVICE_ID = "device_id"; + + /** + * Message client identifier + * + * @since 1.0.0 + */ + public static final String MESSAGE_CLIENT_ID = "client_id"; + + /** + * Message channel + * + * @since 1.0.0 + */ + public static final String MESSAGE_CHANNEL = "channel"; + + /** + * Message channel parts + * + * @since 1.0.0 + */ + public static final String MESSAGE_CHANNEL_PARTS = "channel_parts"; + + /** + * Message captured on timestamp + * + * @since 1.0.0 + */ + public static final String MESSAGE_CAPTURED_ON = "captured_on"; + + /** + * Message sent on timestamp + * + * @since 1.0.0 + */ + public static final String MESSAGE_SENT_ON = "sent_on"; + + /** + * Message position - (composed object) + * + * @since 1.0.0 + */ + public static final String MESSAGE_POSITION = "position"; + + /** + * Message position - location (field name relative to the position object) + * + * @since 1.0.0 + */ + public static final String MESSAGE_POS_LOCATION = "location"; + + /** + * Message position - location (full field name) + * + * @since 1.0.0 + */ + public static final String MESSAGE_POS_LOCATION_FULL = "position.location"; + + /** + * Message position - altitude (field name relative to the position object) + * + * @since 1.0.0 + */ + public static final String MESSAGE_POS_ALT = "alt"; + + /** + * Message position - altitude (full field name) + * + * @since 1.0.0 + */ + public static final String MESSAGE_POS_ALT_FULL = "position.alt"; + + /** + * Message position - precision (field name relative to the position object) + * + * @since 1.0.0 + */ + public static final String MESSAGE_POS_PRECISION = "precision"; + + /** + * Message position - precision (full field name) + * + * @since 1.0.0 + */ + public static final String MESSAGE_POS_PRECISION_FULL = "position.precision"; + + /** + * Message position - heading (field name relative to the position object) + * + * @since 1.0.0 + */ + public static final String MESSAGE_POS_HEADING = "heading"; + + /** + * Message position - heading (full field name) + * + * @since 1.0.0 + */ + public static final String MESSAGE_POS_HEADING_FULL = "position.heading"; + + /** + * Message position - speed (field name relative to the position object) + * + * @since 1.0.0 + */ + public static final String MESSAGE_POS_SPEED = "speed"; + + /** + * Message position - speed (full field name) + * + * @since 1.0.0 + */ + public static final String MESSAGE_POS_SPEED_FULL = "position.speed"; + + /** + * Message position - timestamp (field name relative to the position object) + * + * @since 1.0.0 + */ + public static final String MESSAGE_POS_TIMESTAMP = "timestamp"; + + /** + * Message position - timestamp (full field name) + * + * @since 1.0.0 + */ + public static final String MESSAGE_POS_TIMESTAMP_FULL = "position.timestamp"; + + /** + * Message position - satellites (field name relative to the position object) + * + * @since 1.0.0 + */ + public static final String MESSAGE_POS_SATELLITES = "satellites"; + + /** + * Message position - satellites (full field name) + * + * @since 1.0.0 + */ + public static final String MESSAGE_POS_SATELLITES_FULL = "position.satellites"; + + /** + * Message position - status (field name relative to the position object) + * + * @since 1.0.0 + */ + public static final String MESSAGE_POS_STATUS = "status"; + + /** + * Message position - status (full field name) + * + * @since 1.0.0 + */ + public static final String MESSAGE_POS_STATUS_FULL = "position.status"; + + /** + * Message metrics + * + * @since 1.0.0 + */ + public static final String MESSAGE_METRICS = "metrics"; + + /** + * Message body + * + * @since 1.0.0 + */ + public static final String MESSAGE_BODY = "body"; + + // position internal fields + /** + * Position latitude inner field + * + * @since 1.0.0 + */ + public static final String MESSAGE_POSITION_LATITUDE = "lat"; + + /** + * Position longitude inner field + * + * @since 1.0.0 + */ + public static final String MESSAGE_POSITION_LONGITUDE = "lon"; + +} diff --git a/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/query/MetricInfoField.java b/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/query/MetricInfoField.java new file mode 100644 index 00000000000..ecb86af6585 --- /dev/null +++ b/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/query/MetricInfoField.java @@ -0,0 +1,91 @@ +/******************************************************************************* + * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Eurotech - initial API and implementation + *******************************************************************************/ +package org.eclipse.kapua.service.datastore.model.query; + +import org.eclipse.kapua.service.datastore.model.MetricInfo; +import org.eclipse.kapua.service.storable.model.query.StorableField; + +/** + * This enumeration defines the fields names used in the {@link MetricInfo} client schema + * + * @since 1.0.0 + */ +public enum MetricInfoField implements StorableField { + /** + * Account name + * + * @since 1.0.0 + */ + SCOPE_ID(MetricInfoSchema.METRIC_SCOPE_ID), + + /** + * Client identifier + * + * @since 1.0.0 + */ + CLIENT_ID(MetricInfoSchema.METRIC_CLIENT_ID), + + /** + * Channel + * + * @since 1.0.0 + */ + CHANNEL(MetricInfoSchema.METRIC_CHANNEL), + + /** + * Full metric name (so with the metric type suffix) + * + * @since 1.0.0 + */ + NAME_FULL(MetricInfoSchema.METRIC_MTR_NAME_FULL), + + /** + * Metric type full name (not the acronym) + * + * @since 1.0.0 + */ + TYPE_FULL(MetricInfoSchema.METRIC_MTR_TYPE_FULL), + + /** + * Metric timestamp (derived from the message that published the metric) + * + * @since 1.3.0 + */ + TIMESTAMP(MetricInfoSchema.METRIC_MTR_TIMESTAMP), + + /** + * Metric timestamp (derived from the message that published the metric) + * + * @since 1.0.0 + */ + TIMESTAMP_FULL(MetricInfoSchema.METRIC_MTR_TIMESTAMP_FULL), + + /** + * Message identifier + * + * @since 1.0.0 + */ + MESSAGE_ID_FULL(MetricInfoSchema.METRIC_MTR_MSG_ID_FULL); + + private String field; + + private MetricInfoField(String name) { + this.field = name; + } + + @Override + public String field() { + return field; + } + +} diff --git a/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/query/MetricInfoQuery.java b/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/query/MetricInfoQuery.java index 262519bf677..162fdc5e591 100644 --- a/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/query/MetricInfoQuery.java +++ b/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/query/MetricInfoQuery.java @@ -12,14 +12,18 @@ *******************************************************************************/ package org.eclipse.kapua.service.datastore.model.query; -import org.eclipse.kapua.service.datastore.model.xml.MetricInfoXmlRegistry; -import org.eclipse.kapua.service.storable.model.query.StorableQuery; +import java.util.Collections; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; +import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.service.storable.model.query.SortField; +import org.eclipse.kapua.service.storable.model.query.StorableFetchStyle; +import org.eclipse.kapua.service.storable.model.query.StorableQuery; + /** * Metric information schema query definition * @@ -27,7 +31,45 @@ */ @XmlRootElement(name = "query") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = MetricInfoXmlRegistry.class, factoryMethod = "newQuery") -public interface MetricInfoQuery extends StorableQuery { +@XmlType +public class MetricInfoQuery extends StorableQuery { + + public MetricInfoQuery() { + setSortFields(Collections.singletonList(SortField.ascending(MetricInfoSchema.METRIC_MTR_NAME_FULL))); + } + + /** + * Constructor. + * + * @param scopeId + * The scope {@link KapuaId}. + * @since 1.0.0 + */ + public MetricInfoQuery(KapuaId scopeId) { + super(scopeId); + setSortFields(Collections.singletonList(SortField.ascending(MetricInfoSchema.METRIC_MTR_NAME_FULL))); + + } + + @Override + public String[] getIncludes(StorableFetchStyle fetchStyle) { + return new String[] { "*" }; + } + + @Override + public String[] getExcludes(StorableFetchStyle fetchStyle) { + return new String[] { "" }; + } + + @Override + public String[] getFields() { + return new String[] { MetricInfoField.SCOPE_ID.field(), + MetricInfoField.CLIENT_ID.field(), + MetricInfoField.CHANNEL.field(), + MetricInfoField.NAME_FULL.field(), + MetricInfoField.TYPE_FULL.field(), + MetricInfoField.TIMESTAMP_FULL.field(), + MetricInfoField.MESSAGE_ID_FULL.field() }; + } } diff --git a/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/query/MetricInfoSchema.java b/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/query/MetricInfoSchema.java new file mode 100644 index 00000000000..a28ba4405f4 --- /dev/null +++ b/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/query/MetricInfoSchema.java @@ -0,0 +1,135 @@ +/******************************************************************************* + * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Eurotech - initial API and implementation + *******************************************************************************/ +package org.eclipse.kapua.service.datastore.model.query; + +import org.eclipse.kapua.service.datastore.model.MetricInfo; + +/** + * {@link MetricInfo} schema definition. + * + * @since 1.0.0 + */ +public class MetricInfoSchema { + + /** + * @since 1.0.0 + */ + private MetricInfoSchema() { + } + + /** + * Metric information schema name + * + * @since 1.0.0 + */ + public static final String METRIC_TYPE_NAME = "metric"; + + /** + * Metric information - channel + * + * @since 1.0.0 + */ + public static final String METRIC_CHANNEL = "channel"; + + /** + * Metric information - client identifier + * + * @since 1.0.0 + */ + public static final String METRIC_CLIENT_ID = "client_id"; + + /** + * Metric information - scope id + * + * @since 1.0.0 + */ + public static final String METRIC_SCOPE_ID = "scope_id"; + + /** + * Metric information - metric map prefix + * + * @since 1.0.0 + */ + public static final String METRIC_MTR = "metric"; + + /** + * Metric information - name + * + * @since 1.0.0 + */ + public static final String METRIC_MTR_NAME = "name"; + + /** + * Metric information - full name (so with the metric type suffix) + * + * @since 1.0.0 + */ + public static final String METRIC_MTR_NAME_FULL = "metric.name"; + + /** + * Metric information - type + * + * @since 1.0.0 + */ + public static final String METRIC_MTR_TYPE = "type"; + + /** + * Metric information - full type (so with the metric type suffix) + * + * @since 1.0.0 + */ + public static final String METRIC_MTR_TYPE_FULL = "metric.type"; + + /** + * Metric information - value + * + * @since 1.0.0 + */ + public static final String METRIC_MTR_VALUE = "value"; + + /** + * Metric information - full value (so with the metric type suffix) + * + * @since 1.0.0 + */ + public static final String METRIC_MTR_VALUE_FULL = "metric.value"; + + /** + * Metric information - message timestamp (of the first message published in this channel) + * + * @since 1.0.0 + */ + public static final String METRIC_MTR_TIMESTAMP = "timestamp"; + + /** + * Metric information - message timestamp (of the first message published in this channel, with the metric type suffix) + * + * @since 1.0.0 + */ + public static final String METRIC_MTR_TIMESTAMP_FULL = "metric.timestamp"; + + /** + * Metric information - message identifier (of the first message published in this channel) + * + * @since 1.0.0 + */ + public static final String METRIC_MTR_MSG_ID = "message_id"; + + /** + * Metric information - full message identifier (of the first message published in this channel, with the metric type suffix) + * + * @since 1.0.0 + */ + public static final String METRIC_MTR_MSG_ID_FULL = "metric.message_id"; + +} diff --git a/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/xml/ChannelInfoXmlRegistry.java b/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/xml/ChannelInfoXmlRegistry.java deleted file mode 100644 index 5882830e5b5..00000000000 --- a/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/xml/ChannelInfoXmlRegistry.java +++ /dev/null @@ -1,49 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.datastore.model.xml; - -import org.eclipse.kapua.locator.KapuaLocator; -import org.eclipse.kapua.service.datastore.ChannelInfoFactory; -import org.eclipse.kapua.service.datastore.model.ChannelInfoListResult; -import org.eclipse.kapua.service.datastore.model.query.ChannelInfoQuery; - -import javax.xml.bind.annotation.XmlRegistry; - -/** - * Channel information xml registry - * - * @since 1.0 - */ -@XmlRegistry -public class ChannelInfoXmlRegistry { - - private final ChannelInfoFactory channelInfoFactory = KapuaLocator.getInstance().getFactory(ChannelInfoFactory.class); - - /** - * Creates a {@link ChannelInfoListResult} instance - * - * @return - */ - public ChannelInfoListResult newListResult() { - return channelInfoFactory.newListResult(); - } - - /** - * Creates a {@link ChannelInfoQuery} instance. - * - * @return - */ - public ChannelInfoQuery newQuery() { - return channelInfoFactory.newQuery(null); - } -} diff --git a/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/xml/ClientInfoXmlRegistry.java b/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/xml/ClientInfoXmlRegistry.java deleted file mode 100644 index 591a130db8b..00000000000 --- a/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/xml/ClientInfoXmlRegistry.java +++ /dev/null @@ -1,49 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.datastore.model.xml; - -import org.eclipse.kapua.locator.KapuaLocator; -import org.eclipse.kapua.service.datastore.ClientInfoFactory; -import org.eclipse.kapua.service.datastore.model.ClientInfoListResult; -import org.eclipse.kapua.service.datastore.model.query.ClientInfoQuery; - -import javax.xml.bind.annotation.XmlRegistry; - -/** - * Client information xml registry - * - * @since 1.0 - */ -@XmlRegistry -public class ClientInfoXmlRegistry { - - private final ClientInfoFactory clientInfoFactory = KapuaLocator.getInstance().getFactory(ClientInfoFactory.class); - - /** - * Creates a {@link ClientInfoListResult} instance - * - * @return - */ - public ClientInfoListResult newListResult() { - return clientInfoFactory.newListResult(); - } - - /** - * Creates a {@link ClientInfoQuery} instance. - * - * @return - */ - public ClientInfoQuery newQuery() { - return clientInfoFactory.newQuery(null); - } -} diff --git a/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/xml/DatastoreMessageXmlRegistry.java b/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/xml/DatastoreMessageXmlRegistry.java deleted file mode 100644 index b687541185f..00000000000 --- a/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/xml/DatastoreMessageXmlRegistry.java +++ /dev/null @@ -1,49 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.datastore.model.xml; - -import org.eclipse.kapua.locator.KapuaLocator; -import org.eclipse.kapua.service.datastore.MessageStoreFactory; -import org.eclipse.kapua.service.datastore.model.MessageListResult; -import org.eclipse.kapua.service.datastore.model.query.MessageQuery; - -import javax.xml.bind.annotation.XmlRegistry; - -/** - * Datastore message xml registry - * - * @since 1.0 - */ -@XmlRegistry -public class DatastoreMessageXmlRegistry { - - private final MessageStoreFactory messageStoreFactory = KapuaLocator.getInstance().getFactory(MessageStoreFactory.class); - - /** - * Creates a {@link MessageListResult} instance - * - * @return - */ - public MessageListResult newListResult() { - return messageStoreFactory.newListResult(); - } - - /** - * Creates a {@link MessageQuery} instance. - * - * @return - */ - public MessageQuery newQuery() { - return messageStoreFactory.newQuery(null); - } -} diff --git a/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/xml/MetricInfoXmlRegistry.java b/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/xml/MetricInfoXmlRegistry.java deleted file mode 100644 index 36ab6c9480a..00000000000 --- a/service/datastore/api/src/main/java/org/eclipse/kapua/service/datastore/model/xml/MetricInfoXmlRegistry.java +++ /dev/null @@ -1,49 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.datastore.model.xml; - -import org.eclipse.kapua.locator.KapuaLocator; -import org.eclipse.kapua.service.datastore.MetricInfoFactory; -import org.eclipse.kapua.service.datastore.model.MetricInfoListResult; -import org.eclipse.kapua.service.datastore.model.query.MetricInfoQuery; - -import javax.xml.bind.annotation.XmlRegistry; - -/** - * Metric information xml registry - * - * @since 1.0 - */ -@XmlRegistry -public class MetricInfoXmlRegistry { - - private final MetricInfoFactory metricInfoFactory = KapuaLocator.getInstance().getFactory(MetricInfoFactory.class); - - /** - * Creates a {@link MetricInfoListResult} instance - * - * @return - */ - public MetricInfoListResult newListResult() { - return metricInfoFactory.newListResult(); - } - - /** - * Creates a {@link MetricInfoQuery} instance. - * - * @return - */ - public MetricInfoQuery newQuery() { - return metricInfoFactory.newQuery(null); - } -} diff --git a/service/datastore/internal/pom.xml b/service/datastore/internal/pom.xml index 3a6b89e60a7..1408b3fdbd2 100644 --- a/service/datastore/internal/pom.xml +++ b/service/datastore/internal/pom.xml @@ -20,7 +20,7 @@ org.eclipse.kapua kapua-datastore - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-datastore-internal diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ChannelInfoElasticsearchRepository.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ChannelInfoElasticsearchRepository.java index fc4d15db6df..f2befa046ee 100644 --- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ChannelInfoElasticsearchRepository.java +++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ChannelInfoElasticsearchRepository.java @@ -12,21 +12,26 @@ *******************************************************************************/ package org.eclipse.kapua.service.datastore.internal; -import com.fasterxml.jackson.databind.JsonNode; +import javax.inject.Inject; + import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.datastore.ChannelInfoFactory; import org.eclipse.kapua.service.datastore.internal.mediator.DatastoreUtils; -import org.eclipse.kapua.service.datastore.internal.schema.ChannelInfoSchema; import org.eclipse.kapua.service.datastore.internal.setting.DatastoreSettings; import org.eclipse.kapua.service.datastore.model.ChannelInfo; import org.eclipse.kapua.service.datastore.model.ChannelInfoListResult; import org.eclipse.kapua.service.datastore.model.query.ChannelInfoQuery; +import org.eclipse.kapua.service.datastore.model.query.ChannelInfoSchema; import org.eclipse.kapua.service.elasticsearch.client.ElasticsearchClientProvider; +import org.eclipse.kapua.service.elasticsearch.client.SchemaKeys; import org.eclipse.kapua.service.storable.exception.MappingException; import org.eclipse.kapua.service.storable.model.id.StorableId; import org.eclipse.kapua.service.storable.model.query.predicate.StorablePredicateFactory; +import org.eclipse.kapua.service.storable.model.utils.KeyValueEntry; +import org.eclipse.kapua.service.storable.model.utils.MappingUtils; -import javax.inject.Inject; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ObjectNode; public class ChannelInfoElasticsearchRepository extends DatastoreElasticSearchRepositoryBase implements ChannelInfoRepository { @@ -45,7 +50,9 @@ protected ChannelInfoElasticsearchRepository( channelInfoFactory, storablePredicateFactory, datastoreCacheManager.getChannelsCache(), - datastoreSettings); + datastoreSettings, + scopeId -> new ChannelInfoQuery(scopeId), + () -> new ChannelInfoListResult()); this.datastoreUtils = datastoreUtils; } @@ -61,7 +68,48 @@ protected String indexResolver(KapuaId scopeId) { @Override protected JsonNode getIndexSchema() throws MappingException { - return ChannelInfoSchema.getChannelTypeSchema(); + return getChannelTypeSchema(); + } + + /** + * Create and return the Json representation of the channel info schema + * + * @return + * @throws MappingException + * @since 1.0.0 + */ + public static JsonNode getChannelTypeSchema() throws MappingException { + ObjectNode channelNode = MappingUtils.newObjectNode(); + + { + ObjectNode sourceChannel = MappingUtils.newObjectNode(new KeyValueEntry[] { new KeyValueEntry(SchemaKeys.KEY_ENABLED, true) }); + channelNode.set(SchemaKeys.KEY_SOURCE, sourceChannel); + + ObjectNode propertiesNode = MappingUtils.newObjectNode(); + { + ObjectNode channelScopeId = MappingUtils.newObjectNode( + new KeyValueEntry[] { new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE) }); + propertiesNode.set(ChannelInfoSchema.CHANNEL_SCOPE_ID, channelScopeId); + + ObjectNode channelClientId = MappingUtils.newObjectNode( + new KeyValueEntry[] { new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE) }); + propertiesNode.set(ChannelInfoSchema.CHANNEL_CLIENT_ID, channelClientId); + + ObjectNode channelName = MappingUtils.newObjectNode( + new KeyValueEntry[] { new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE) }); + propertiesNode.set(ChannelInfoSchema.CHANNEL_NAME, channelName); + + ObjectNode channelTimestamp = MappingUtils.newObjectNode( + new KeyValueEntry[] { new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_DATE), new KeyValueEntry(SchemaKeys.KEY_FORMAT, DatastoreUtils.DATASTORE_DATE_FORMAT) }); + propertiesNode.set(ChannelInfoSchema.CHANNEL_TIMESTAMP, channelTimestamp); + + ObjectNode channelMessageId = MappingUtils.newObjectNode( + new KeyValueEntry[] { new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE) }); + propertiesNode.set(ChannelInfoSchema.CHANNEL_MESSAGE_ID, channelMessageId); + } + channelNode.set(SchemaKeys.FIELD_NAME_PROPERTIES, propertiesNode); + } + return channelNode; } @Override diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ChannelInfoFactoryImpl.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ChannelInfoFactoryImpl.java index 9e7ba0ed93d..e9af08d5457 100644 --- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ChannelInfoFactoryImpl.java +++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ChannelInfoFactoryImpl.java @@ -12,16 +12,11 @@ *******************************************************************************/ package org.eclipse.kapua.service.datastore.internal; -import org.eclipse.kapua.model.id.KapuaId; +import javax.inject.Singleton; + import org.eclipse.kapua.service.datastore.ChannelInfoFactory; import org.eclipse.kapua.service.datastore.internal.model.ChannelInfoImpl; -import org.eclipse.kapua.service.datastore.internal.model.ChannelInfoListResultImpl; -import org.eclipse.kapua.service.datastore.internal.model.query.ChannelInfoQueryImpl; import org.eclipse.kapua.service.datastore.model.ChannelInfo; -import org.eclipse.kapua.service.datastore.model.ChannelInfoListResult; -import org.eclipse.kapua.service.datastore.model.query.ChannelInfoQuery; - -import javax.inject.Singleton; /** * {@link ChannelInfoFactory} implementation. @@ -35,14 +30,4 @@ public class ChannelInfoFactoryImpl implements ChannelInfoFactory { public ChannelInfo newStorable() { return new ChannelInfoImpl(); } - - @Override - public ChannelInfoListResult newListResult() { - return new ChannelInfoListResultImpl(); - } - - @Override - public ChannelInfoQuery newQuery(KapuaId scopeId) { - return new ChannelInfoQueryImpl(scopeId); - } } diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ChannelInfoRegistryFacadeImpl.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ChannelInfoRegistryFacadeImpl.java index e4fc7704cc7..bd9f6c59001 100644 --- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ChannelInfoRegistryFacadeImpl.java +++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ChannelInfoRegistryFacadeImpl.java @@ -12,13 +12,13 @@ *******************************************************************************/ package org.eclipse.kapua.service.datastore.internal; +import javax.inject.Inject; + import org.eclipse.kapua.KapuaIllegalArgumentException; import org.eclipse.kapua.commons.util.ArgumentValidator; import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.datastore.internal.mediator.ChannelInfoField; import org.eclipse.kapua.service.datastore.internal.mediator.ConfigurationException; -import org.eclipse.kapua.service.datastore.internal.model.ChannelInfoListResultImpl; -import org.eclipse.kapua.service.datastore.internal.model.query.ChannelInfoQueryImpl; +import org.eclipse.kapua.service.datastore.internal.mediator.InfoFieldHelper; import org.eclipse.kapua.service.datastore.model.ChannelInfo; import org.eclipse.kapua.service.datastore.model.ChannelInfoListResult; import org.eclipse.kapua.service.datastore.model.query.ChannelInfoQuery; @@ -31,8 +31,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.inject.Inject; - /** * Channel information registry facade * @@ -88,7 +86,7 @@ public StorableId upstore(ChannelInfo channelInfo) throws KapuaIllegalArgumentEx ArgumentValidator.notNull(channelInfo.getFirstMessageId(), "channelInfo.messageId"); ArgumentValidator.notNull(channelInfo.getFirstMessageOn(), "channelInfo.messageTimestamp"); - String channelInfoId = ChannelInfoField.getOrDeriveId(channelInfo.getId(), channelInfo); + String channelInfoId = InfoFieldHelper.getOrDeriveId(channelInfo.getId(), channelInfo); StorableId storableId = storableIdFactory.newStorableId(channelInfoId); // Store channel. Look up channel in the cache, and cache it if it doesn't exist @@ -155,7 +153,7 @@ public ChannelInfo find(KapuaId scopeId, StorableId id) throws KapuaIllegalArgum } private ChannelInfo doFind(KapuaId scopeId, StorableId id) throws KapuaIllegalArgumentException, ConfigurationException, ClientException { - ChannelInfoQueryImpl idsQuery = new ChannelInfoQueryImpl(scopeId); + ChannelInfoQuery idsQuery = new ChannelInfoQuery(scopeId); idsQuery.setLimit(1); IdsPredicate idsPredicate = storablePredicateFactory.newIdsPredicate(); @@ -182,7 +180,7 @@ public ChannelInfoListResult query(ChannelInfoQuery query) throws KapuaIllegalAr if (!isDatastoreServiceEnabled(query.getScopeId())) { LOG.debug("Storage not enabled for account {}, returning empty result", query.getScopeId()); - return new ChannelInfoListResultImpl(); + return new ChannelInfoListResult(); } return repository.query(query); diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ChannelInfoRegistryServiceImpl.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ChannelInfoRegistryServiceImpl.java index d780327d982..d051db8fd3c 100644 --- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ChannelInfoRegistryServiceImpl.java +++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ChannelInfoRegistryServiceImpl.java @@ -13,6 +13,14 @@ *******************************************************************************/ package org.eclipse.kapua.service.datastore.internal; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Optional; + +import javax.inject.Inject; +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.commons.model.domains.Domains; import org.eclipse.kapua.commons.service.internal.KapuaServiceDisabledException; @@ -22,20 +30,18 @@ import org.eclipse.kapua.service.account.AccountService; import org.eclipse.kapua.service.authorization.AuthorizationService; import org.eclipse.kapua.service.authorization.permission.Permission; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; import org.eclipse.kapua.service.datastore.ChannelInfoRegistryService; -import org.eclipse.kapua.service.datastore.internal.mediator.ChannelInfoField; -import org.eclipse.kapua.service.datastore.internal.mediator.MessageField; -import org.eclipse.kapua.service.datastore.internal.model.query.MessageQueryImpl; -import org.eclipse.kapua.service.datastore.internal.schema.MessageSchema; import org.eclipse.kapua.service.datastore.internal.setting.DatastoreSettings; import org.eclipse.kapua.service.datastore.internal.setting.DatastoreSettingsKey; import org.eclipse.kapua.service.datastore.model.ChannelInfo; import org.eclipse.kapua.service.datastore.model.ChannelInfoListResult; import org.eclipse.kapua.service.datastore.model.DatastoreMessage; import org.eclipse.kapua.service.datastore.model.MessageListResult; +import org.eclipse.kapua.service.datastore.model.query.ChannelInfoField; import org.eclipse.kapua.service.datastore.model.query.ChannelInfoQuery; +import org.eclipse.kapua.service.datastore.model.query.MessageField; import org.eclipse.kapua.service.datastore.model.query.MessageQuery; +import org.eclipse.kapua.service.datastore.model.query.MessageSchema; import org.eclipse.kapua.service.datastore.model.query.predicate.DatastorePredicateFactory; import org.eclipse.kapua.service.storable.model.id.StorableId; import org.eclipse.kapua.service.storable.model.query.SortField; @@ -46,13 +52,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.inject.Inject; -import javax.inject.Singleton; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.Optional; - /** * Channel info registry implementation * @@ -64,9 +63,7 @@ public class ChannelInfoRegistryServiceImpl implements ChannelInfoRegistryServic private static final Logger LOG = LoggerFactory.getLogger(ChannelInfoRegistryServiceImpl.class); private final DatastorePredicateFactory datastorePredicateFactory; protected final Integer maxResultWindowValue; - private final AccountService accountService; private final AuthorizationService authorizationService; - private final PermissionFactory permissionFactory; private final ChannelInfoRegistryFacade channelInfoRegistryFacade; private final MessageRepository messageRepository; private final DatastoreSettings datastoreSettings; @@ -83,17 +80,14 @@ public ChannelInfoRegistryServiceImpl( DatastorePredicateFactory datastorePredicateFactory, AccountService accountService, AuthorizationService authorizationService, - PermissionFactory permissionFactory, MessageRepository messageStoreService, ChannelInfoRegistryFacade channelInfoRegistryFacade, DatastoreSettings datastoreSettings) { this.datastorePredicateFactory = datastorePredicateFactory; this.authorizationService = authorizationService; - this.permissionFactory = permissionFactory; this.messageRepository = messageStoreService; this.channelInfoRegistryFacade = channelInfoRegistryFacade; this.datastoreSettings = datastoreSettings; - this.accountService = accountService; this.maxResultWindowValue = datastoreSettings.getInt(DatastoreSettingsKey.MAX_RESULT_WINDOW_VALUE); } @@ -211,14 +205,13 @@ public void delete(ChannelInfoQuery query) private void checkDataAccess(KapuaId scopeId, Actions action) throws KapuaException { - Permission permission = permissionFactory.newPermission(Domains.DATASTORE, action, scopeId); + Permission permission = new Permission(Domains.DATASTORE, action, scopeId); authorizationService.checkPermission(permission); } /** * Update the last published date and last published message identifier for the specified channel info, so it gets the timestamp and the message id of the last published message for the - * account/clientId in the - * channel info + * account/clientId in the channel info * * @param channelInfo * @throws KapuaException @@ -228,7 +221,7 @@ private void updateLastPublishedFields(ChannelInfo channelInfo) throws KapuaExce List sort = new ArrayList<>(); sort.add(SortField.descending(MessageSchema.MESSAGE_TIMESTAMP)); - MessageQuery messageQuery = new MessageQueryImpl(channelInfo.getScopeId()); + MessageQuery messageQuery = new MessageQuery(channelInfo.getScopeId()); messageQuery.setAskTotalCount(true); messageQuery.setFetchStyle(StorableFetchStyle.FIELDS); messageQuery.setLimit(1); diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ClientInfoElasticsearchRepository.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ClientInfoElasticsearchRepository.java index 44a4c3d4c47..670cf8524d4 100644 --- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ClientInfoElasticsearchRepository.java +++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ClientInfoElasticsearchRepository.java @@ -12,21 +12,26 @@ *******************************************************************************/ package org.eclipse.kapua.service.datastore.internal; -import com.fasterxml.jackson.databind.JsonNode; +import javax.inject.Inject; + import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.datastore.ClientInfoFactory; import org.eclipse.kapua.service.datastore.internal.mediator.DatastoreUtils; -import org.eclipse.kapua.service.datastore.internal.schema.ClientInfoSchema; import org.eclipse.kapua.service.datastore.internal.setting.DatastoreSettings; import org.eclipse.kapua.service.datastore.model.ClientInfo; import org.eclipse.kapua.service.datastore.model.ClientInfoListResult; import org.eclipse.kapua.service.datastore.model.query.ClientInfoQuery; +import org.eclipse.kapua.service.datastore.model.query.ClientInfoSchema; import org.eclipse.kapua.service.elasticsearch.client.ElasticsearchClientProvider; +import org.eclipse.kapua.service.elasticsearch.client.SchemaKeys; import org.eclipse.kapua.service.storable.exception.MappingException; import org.eclipse.kapua.service.storable.model.id.StorableId; import org.eclipse.kapua.service.storable.model.query.predicate.StorablePredicateFactory; +import org.eclipse.kapua.service.storable.model.utils.KeyValueEntry; +import org.eclipse.kapua.service.storable.model.utils.MappingUtils; -import javax.inject.Inject; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ObjectNode; public class ClientInfoElasticsearchRepository extends DatastoreElasticSearchRepositoryBase implements ClientInfoRepository { @@ -45,7 +50,9 @@ protected ClientInfoElasticsearchRepository( clientInfoFactory, storablePredicateFactory, datastoreCacheManager.getClientsCache(), - datastoreSettings); + datastoreSettings, + scopeId -> new ClientInfoQuery(scopeId), + () -> new ClientInfoListResult()); this.datastoreUtils = datastoreUtils; } @@ -56,7 +63,45 @@ protected String indexResolver(KapuaId scopeId) { @Override protected JsonNode getIndexSchema() throws MappingException { - return ClientInfoSchema.getClientTypeSchema(); + return getClientTypeSchema(); + } + + /** + * Create and return the Json representation of the client info schema + * + * @return + * @throws MappingException + * @since 1.0.0 + */ + public static JsonNode getClientTypeSchema() throws MappingException { + + ObjectNode clientNode = MappingUtils.newObjectNode(); + { + ObjectNode sourceClient = MappingUtils.newObjectNode(new KeyValueEntry[] { new KeyValueEntry(SchemaKeys.KEY_ENABLED, true) }); + clientNode.set(SchemaKeys.KEY_SOURCE, sourceClient); + + ObjectNode propertiesNode = MappingUtils.newObjectNode(); + { + ObjectNode clientId = MappingUtils.newObjectNode( + new KeyValueEntry[] { new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE) }); + propertiesNode.set(ClientInfoSchema.CLIENT_ID, clientId); + + ObjectNode clientTimestamp = MappingUtils.newObjectNode( + new KeyValueEntry[] { new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_DATE), new KeyValueEntry(SchemaKeys.KEY_FORMAT, DatastoreUtils.DATASTORE_DATE_FORMAT) }); + propertiesNode.set(ClientInfoSchema.CLIENT_TIMESTAMP, clientTimestamp); + + ObjectNode clientScopeId = MappingUtils.newObjectNode( + new KeyValueEntry[] { new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE) }); + propertiesNode.set(ClientInfoSchema.CLIENT_SCOPE_ID, clientScopeId); + + ObjectNode clientMessageId = MappingUtils.newObjectNode( + new KeyValueEntry[] { new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE) }); + propertiesNode.set(ClientInfoSchema.CLIENT_MESSAGE_ID, clientMessageId); + } + clientNode.set(SchemaKeys.FIELD_NAME_PROPERTIES, propertiesNode); + } + + return clientNode; } @Override diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ClientInfoFactoryImpl.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ClientInfoFactoryImpl.java index 960a5f6109f..acd9510a33a 100644 --- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ClientInfoFactoryImpl.java +++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ClientInfoFactoryImpl.java @@ -12,16 +12,11 @@ *******************************************************************************/ package org.eclipse.kapua.service.datastore.internal; -import org.eclipse.kapua.model.id.KapuaId; +import javax.inject.Singleton; + import org.eclipse.kapua.service.datastore.ClientInfoFactory; import org.eclipse.kapua.service.datastore.internal.model.ClientInfoImpl; -import org.eclipse.kapua.service.datastore.internal.model.ClientInfoListResultImpl; -import org.eclipse.kapua.service.datastore.internal.model.query.ClientInfoQueryImpl; import org.eclipse.kapua.service.datastore.model.ClientInfo; -import org.eclipse.kapua.service.datastore.model.ClientInfoListResult; -import org.eclipse.kapua.service.datastore.model.query.ClientInfoQuery; - -import javax.inject.Singleton; /** * {@link ClientInfoFactory} implementation. @@ -36,13 +31,4 @@ public ClientInfo newStorable() { return new ClientInfoImpl(); } - @Override - public ClientInfoListResult newListResult() { - return new ClientInfoListResultImpl(); - } - - @Override - public ClientInfoQuery newQuery(KapuaId scopeId) { - return new ClientInfoQueryImpl(scopeId); - } } diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ClientInfoRegistryFacadeImpl.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ClientInfoRegistryFacadeImpl.java index 85952aaf074..a8bae395a4a 100644 --- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ClientInfoRegistryFacadeImpl.java +++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ClientInfoRegistryFacadeImpl.java @@ -12,12 +12,13 @@ *******************************************************************************/ package org.eclipse.kapua.service.datastore.internal; +import javax.inject.Inject; + import org.eclipse.kapua.KapuaIllegalArgumentException; import org.eclipse.kapua.commons.util.ArgumentValidator; import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.datastore.internal.mediator.ClientInfoField; import org.eclipse.kapua.service.datastore.internal.mediator.ConfigurationException; -import org.eclipse.kapua.service.datastore.internal.model.ClientInfoListResultImpl; +import org.eclipse.kapua.service.datastore.internal.mediator.InfoFieldHelper; import org.eclipse.kapua.service.datastore.model.ClientInfo; import org.eclipse.kapua.service.datastore.model.ClientInfoListResult; import org.eclipse.kapua.service.datastore.model.query.ClientInfoQuery; @@ -29,8 +30,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.inject.Inject; - /** * Client information registry facade * @@ -86,7 +85,7 @@ public StorableId upstore(ClientInfo clientInfo) throws KapuaIllegalArgumentExce ArgumentValidator.notNull(clientInfo.getFirstMessageId(), "clientInfo.firstPublishedMessageId"); ArgumentValidator.notNull(clientInfo.getFirstMessageOn(), "clientInfo.firstPublishedMessageTimestamp"); - String clientInfoId = ClientInfoField.getOrDeriveId(clientInfo.getId(), clientInfo); + String clientInfoId = InfoFieldHelper.getOrDeriveId(clientInfo.getId(), clientInfo); StorableId storableId = storableIdFactory.newStorableId(clientInfoId); // Store channel. Look up channel in the cache, and cache it if it doesn't exist @@ -165,7 +164,7 @@ public ClientInfoListResult query(ClientInfoQuery query) throws KapuaIllegalArgu if (!isDatastoreServiceEnabled(query.getScopeId())) { LOG.debug("Storage not enabled for account {}, returning empty result", query.getScopeId()); - return new ClientInfoListResultImpl(); + return new ClientInfoListResult(); } return repository.query(query); diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ClientInfoRegistryServiceImpl.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ClientInfoRegistryServiceImpl.java index d2ca458e475..dfb1bf92243 100644 --- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ClientInfoRegistryServiceImpl.java +++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/ClientInfoRegistryServiceImpl.java @@ -13,29 +13,34 @@ *******************************************************************************/ package org.eclipse.kapua.service.datastore.internal; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Optional; + +import javax.inject.Inject; +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.commons.model.domains.Domains; import org.eclipse.kapua.commons.service.internal.KapuaServiceDisabledException; import org.eclipse.kapua.commons.util.ArgumentValidator; import org.eclipse.kapua.model.domain.Actions; import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.account.AccountService; import org.eclipse.kapua.service.authorization.AuthorizationService; import org.eclipse.kapua.service.authorization.permission.Permission; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; import org.eclipse.kapua.service.datastore.ClientInfoRegistryService; -import org.eclipse.kapua.service.datastore.internal.mediator.ClientInfoField; -import org.eclipse.kapua.service.datastore.internal.mediator.MessageField; -import org.eclipse.kapua.service.datastore.internal.model.query.MessageQueryImpl; -import org.eclipse.kapua.service.datastore.internal.schema.MessageSchema; import org.eclipse.kapua.service.datastore.internal.setting.DatastoreSettings; import org.eclipse.kapua.service.datastore.internal.setting.DatastoreSettingsKey; import org.eclipse.kapua.service.datastore.model.ClientInfo; import org.eclipse.kapua.service.datastore.model.ClientInfoListResult; import org.eclipse.kapua.service.datastore.model.DatastoreMessage; import org.eclipse.kapua.service.datastore.model.MessageListResult; +import org.eclipse.kapua.service.datastore.model.query.ClientInfoField; import org.eclipse.kapua.service.datastore.model.query.ClientInfoQuery; +import org.eclipse.kapua.service.datastore.model.query.MessageField; import org.eclipse.kapua.service.datastore.model.query.MessageQuery; +import org.eclipse.kapua.service.datastore.model.query.MessageSchema; import org.eclipse.kapua.service.datastore.model.query.predicate.DatastorePredicateFactory; import org.eclipse.kapua.service.storable.model.id.StorableId; import org.eclipse.kapua.service.storable.model.query.SortField; @@ -47,13 +52,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.inject.Inject; -import javax.inject.Singleton; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.Optional; - /** * Client information registry implementation. * @@ -65,9 +63,7 @@ public class ClientInfoRegistryServiceImpl implements ClientInfoRegistryService private static final Logger LOG = LoggerFactory.getLogger(ClientInfoRegistryServiceImpl.class); protected final Integer maxResultWindowValue; private final StorablePredicateFactory storablePredicateFactory; - private final AccountService accountService; private final AuthorizationService authorizationService; - private final PermissionFactory permissionFactory; private final ClientInfoRegistryFacade clientInfoRegistryFacade; private final DatastorePredicateFactory datastorePredicateFactory; private final MessageRepository messageRepository; @@ -82,17 +78,13 @@ public class ClientInfoRegistryServiceImpl implements ClientInfoRegistryService @Inject public ClientInfoRegistryServiceImpl( StorablePredicateFactory storablePredicateFactory, - AccountService accountService, AuthorizationService authorizationService, - PermissionFactory permissionFactory, DatastorePredicateFactory datastorePredicateFactory, ClientInfoRegistryFacade clientInfoRegistryFacade, MessageRepository messageRepository, DatastoreSettings datastoreSettings) { this.storablePredicateFactory = storablePredicateFactory; - this.accountService = accountService; this.authorizationService = authorizationService; - this.permissionFactory = permissionFactory; this.datastorePredicateFactory = datastorePredicateFactory; this.clientInfoRegistryFacade = clientInfoRegistryFacade; this.messageRepository = messageRepository; @@ -213,7 +205,7 @@ public void delete(KapuaId scopeId, StorableId id) private void checkAccess(KapuaId scopeId, Actions action) throws KapuaException { - Permission permission = permissionFactory.newPermission(Domains.DATASTORE, action, scopeId); + Permission permission = new Permission(Domains.DATASTORE, action, scopeId); authorizationService.checkPermission(permission); } @@ -228,7 +220,7 @@ private void updateLastPublishedFields(ClientInfo clientInfo) throws KapuaExcept List sort = new ArrayList<>(); sort.add(SortField.descending(MessageSchema.MESSAGE_TIMESTAMP)); - MessageQuery messageQuery = new MessageQueryImpl(clientInfo.getScopeId()); + MessageQuery messageQuery = new MessageQuery(clientInfo.getScopeId()); messageQuery.setAskTotalCount(true); messageQuery.setFetchStyle(StorableFetchStyle.FIELDS); messageQuery.setLimit(1); diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/DatastoreElasticSearchRepositoryBase.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/DatastoreElasticSearchRepositoryBase.java index b61b2cd96fa..2e9b06735a0 100644 --- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/DatastoreElasticSearchRepositoryBase.java +++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/DatastoreElasticSearchRepositoryBase.java @@ -12,8 +12,11 @@ *******************************************************************************/ package org.eclipse.kapua.service.datastore.internal; -import com.fasterxml.jackson.databind.node.ObjectNode; +import java.util.function.Function; +import java.util.function.Supplier; + import org.eclipse.kapua.commons.cache.LocalCache; +import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.datastore.internal.setting.DatastoreSettings; import org.eclipse.kapua.service.datastore.internal.setting.DatastoreSettingsKey; import org.eclipse.kapua.service.elasticsearch.client.ElasticsearchClientProvider; @@ -29,6 +32,8 @@ import org.eclipse.kapua.service.storable.model.utils.MappingUtils; import org.eclipse.kapua.service.storable.repository.StorableRepository; +import com.fasterxml.jackson.databind.node.ObjectNode; + public abstract class DatastoreElasticSearchRepositoryBase< T extends Storable, L extends StorableListResult, @@ -41,21 +46,25 @@ public abstract class DatastoreElasticSearchRepositoryBase< protected DatastoreElasticSearchRepositoryBase( ElasticsearchClientProvider elasticsearchClientProviderInstance, Class clazz, - StorableFactory storableFactory, + StorableFactory storableFactory, StorablePredicateFactory storablePredicateFactory, LocalCache indexesCache, - DatastoreSettings datastoreSettings) { + DatastoreSettings datastoreSettings, + Function querySupplier, + Supplier listSupplier) { super(elasticsearchClientProviderInstance, clazz, storableFactory, storablePredicateFactory, - indexesCache); + indexesCache, querySupplier, listSupplier); this.datastoreSettings = datastoreSettings; } protected DatastoreElasticSearchRepositoryBase( ElasticsearchClientProvider elasticsearchClientProviderInstance, Class clazz, - StorableFactory storableFactory, - StorablePredicateFactory storablePredicateFactory, DatastoreSettings datastoreSettings) { - super(elasticsearchClientProviderInstance, clazz, storableFactory, storablePredicateFactory); + StorableFactory storableFactory, + StorablePredicateFactory storablePredicateFactory, DatastoreSettings datastoreSettings, + Function querySupplier, + Supplier listSupplier) { + super(elasticsearchClientProviderInstance, clazz, storableFactory, storablePredicateFactory, querySupplier, listSupplier); this.datastoreSettings = datastoreSettings; } @@ -73,10 +82,10 @@ protected ObjectNode getMappingSchema(String idxName) throws MappingException { ObjectNode rootNode = MappingUtils.newObjectNode(); ObjectNode settingsNode = MappingUtils.newObjectNode(); - ObjectNode refreshIntervalNode = MappingUtils.newObjectNode(new KeyValueEntry[]{ + ObjectNode refreshIntervalNode = MappingUtils.newObjectNode(new KeyValueEntry[] { new KeyValueEntry(SchemaKeys.KEY_REFRESH_INTERVAL, idxRefreshInterval), new KeyValueEntry(SchemaKeys.KEY_SHARD_NUMBER, idxShardNumber), - new KeyValueEntry(SchemaKeys.KEY_REPLICA_NUMBER, idxReplicaNumber)}); + new KeyValueEntry(SchemaKeys.KEY_REPLICA_NUMBER, idxReplicaNumber) }); settingsNode.set(SchemaKeys.KEY_INDEX, refreshIntervalNode); rootNode.set(SchemaKeys.KEY_SETTINGS, settingsNode); logger.info("Creating index for '{}' - refresh: '{}' - shards: '{}' replicas: '{}': ", idxName, idxRefreshInterval, idxShardNumber, idxReplicaNumber); diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/DatastoreModule.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/DatastoreModule.java index b91414d9b25..0ca72691a5e 100644 --- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/DatastoreModule.java +++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/DatastoreModule.java @@ -25,7 +25,6 @@ import org.eclipse.kapua.model.domain.DomainEntry; import org.eclipse.kapua.service.account.AccountService; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; import org.eclipse.kapua.service.datastore.ChannelInfoFactory; import org.eclipse.kapua.service.datastore.ChannelInfoRegistryService; import org.eclipse.kapua.service.datastore.ClientInfoFactory; @@ -107,7 +106,6 @@ ConfigurationProvider configurationProvider( @Provides @Singleton MessageStoreService messageStoreService( - PermissionFactory permissionFactory, AuthorizationService authorizationService, Map, ServiceConfigurationManager> serviceConfigurationManagersByServiceClass, KapuaJpaTxManagerFactory jpaTxManagerFactory, @@ -116,7 +114,6 @@ MessageStoreService messageStoreService( DatastoreSettings datastoreSettings) { return new MessageStoreServiceImpl( jpaTxManagerFactory.create("kapua-datastore"), - permissionFactory, authorizationService, serviceConfigurationManagersByServiceClass.get(MessageStoreService.class), messageStoreFacade, diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MessageElasticsearchRepository.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MessageElasticsearchRepository.java index cefebc5323e..a25592b2571 100644 --- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MessageElasticsearchRepository.java +++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MessageElasticsearchRepository.java @@ -12,20 +12,24 @@ *******************************************************************************/ package org.eclipse.kapua.service.datastore.internal; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.node.ObjectNode; +import java.util.Map; +import java.util.Optional; +import java.util.stream.Collectors; + +import javax.inject.Inject; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.commons.cache.LocalCache; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.datastore.MessageStoreFactory; import org.eclipse.kapua.service.datastore.internal.mediator.DatastoreUtils; import org.eclipse.kapua.service.datastore.internal.mediator.Metric; -import org.eclipse.kapua.service.datastore.internal.schema.MessageSchema; import org.eclipse.kapua.service.datastore.internal.setting.DatastoreSettings; import org.eclipse.kapua.service.datastore.internal.setting.DatastoreSettingsKey; import org.eclipse.kapua.service.datastore.model.DatastoreMessage; import org.eclipse.kapua.service.datastore.model.MessageListResult; import org.eclipse.kapua.service.datastore.model.query.MessageQuery; +import org.eclipse.kapua.service.datastore.model.query.MessageSchema; import org.eclipse.kapua.service.elasticsearch.client.ElasticsearchClientProvider; import org.eclipse.kapua.service.elasticsearch.client.SchemaKeys; import org.eclipse.kapua.service.elasticsearch.client.exception.ClientException; @@ -37,12 +41,11 @@ import org.eclipse.kapua.service.storable.model.utils.KeyValueEntry; import org.eclipse.kapua.service.storable.model.utils.MappingUtils; -import javax.inject.Inject; -import java.util.Map; -import java.util.Optional; -import java.util.stream.Collectors; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ObjectNode; public class MessageElasticsearchRepository extends DatastoreElasticSearchRepositoryBase implements MessageRepository { + private final DatastoreUtils datastoreUtils; private final LocalCache> metricsByIndex; @@ -58,7 +61,9 @@ public MessageElasticsearchRepository( DatastoreMessage.class, messageStoreFactory, storablePredicateFactory, - datastoreSettings); + datastoreSettings, + scopeId -> new MessageQuery(scopeId), + () -> new MessageListResult()); this.datastoreUtils = datastoreUtils; metricsByIndex = datastoreCacheManager.getMetadataCache(); } @@ -66,7 +71,7 @@ public MessageElasticsearchRepository( @Override protected JsonNode getIndexSchema() { try { - return MessageSchema.getMessageTypeSchema(); + return getMessageTypeSchema(); } catch (MappingException e) { throw new RuntimeException(e); } @@ -87,6 +92,109 @@ protected String indexResolver(KapuaId scopeId, Long time) { return datastoreUtils.getDataIndexName(scopeId, time, indexingWindowOption); } + /** + * Create and return the Json representation of the message schema + * + * @return + * @throws MappingException + * @since 1.0.0 + */ + public static JsonNode getMessageTypeSchema() throws MappingException { + ObjectNode messageNode = MappingUtils.newObjectNode(); + { + ObjectNode sourceMessage = MappingUtils.newObjectNode(new KeyValueEntry[] { new KeyValueEntry(SchemaKeys.KEY_ENABLED, true) }); + messageNode.set(SchemaKeys.KEY_SOURCE, sourceMessage); + + ObjectNode propertiesNode = MappingUtils.newObjectNode(); + { + ObjectNode messageId = MappingUtils.newObjectNode( + new KeyValueEntry[] { new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE) }); + propertiesNode.set(MessageSchema.MESSAGE_ID, messageId); + + ObjectNode messageTimestamp = MappingUtils.newObjectNode( + new KeyValueEntry[] { new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_DATE), new KeyValueEntry(SchemaKeys.KEY_FORMAT, DatastoreUtils.DATASTORE_DATE_FORMAT) }); + propertiesNode.set(MessageSchema.MESSAGE_TIMESTAMP, messageTimestamp); + + ObjectNode messageReceivedOn = MappingUtils.newObjectNode( + new KeyValueEntry[] { new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_DATE), new KeyValueEntry(SchemaKeys.KEY_FORMAT, DatastoreUtils.DATASTORE_DATE_FORMAT) }); + propertiesNode.set(MessageSchema.MESSAGE_RECEIVED_ON, messageReceivedOn); + + ObjectNode messageIp = MappingUtils.newObjectNode(new KeyValueEntry[] { new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_IP) }); + propertiesNode.set(MessageSchema.MESSAGE_IP_ADDRESS, messageIp); + + ObjectNode messageScopeId = MappingUtils.newObjectNode( + new KeyValueEntry[] { new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE) }); + propertiesNode.set(MessageSchema.MESSAGE_SCOPE_ID, messageScopeId); + + ObjectNode messageDeviceId = MappingUtils.newObjectNode( + new KeyValueEntry[] { new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE) }); + propertiesNode.set(MessageSchema.MESSAGE_DEVICE_ID, messageDeviceId); + + ObjectNode messageClientId = MappingUtils.newObjectNode( + new KeyValueEntry[] { new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE) }); + propertiesNode.set(MessageSchema.MESSAGE_CLIENT_ID, messageClientId); + + ObjectNode messageChannel = MappingUtils.newObjectNode( + new KeyValueEntry[] { new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE) }); + propertiesNode.set(MessageSchema.MESSAGE_CHANNEL, messageChannel); + + ObjectNode messageCapturedOn = MappingUtils.newObjectNode( + new KeyValueEntry[] { new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_DATE), new KeyValueEntry(SchemaKeys.KEY_FORMAT, DatastoreUtils.DATASTORE_DATE_FORMAT) }); + propertiesNode.set(MessageSchema.MESSAGE_CAPTURED_ON, messageCapturedOn); + + ObjectNode messageSentOn = MappingUtils.newObjectNode( + new KeyValueEntry[] { new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_DATE), new KeyValueEntry(SchemaKeys.KEY_FORMAT, DatastoreUtils.DATASTORE_DATE_FORMAT) }); + propertiesNode.set(MessageSchema.MESSAGE_SENT_ON, messageSentOn); + + ObjectNode positionNode = MappingUtils.newObjectNode( + new KeyValueEntry[] { new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_OBJECT), new KeyValueEntry(SchemaKeys.KEY_ENABLED, true), + new KeyValueEntry(SchemaKeys.KEY_DYNAMIC, false) }); + + ObjectNode positionPropertiesNode = MappingUtils.newObjectNode(); + { + ObjectNode messagePositionPropLocation = MappingUtils.newObjectNode(new KeyValueEntry[] { new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_GEO_POINT) }); + positionPropertiesNode.set(MessageSchema.MESSAGE_POS_LOCATION, messagePositionPropLocation); + + ObjectNode messagePositionPropAlt = MappingUtils.newObjectNode(new KeyValueEntry[] { new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_DOUBLE) }); + positionPropertiesNode.set(MessageSchema.MESSAGE_POS_ALT, messagePositionPropAlt); + + ObjectNode messagePositionPropPrec = MappingUtils.newObjectNode(new KeyValueEntry[] { new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_DOUBLE) }); + positionPropertiesNode.set(MessageSchema.MESSAGE_POS_PRECISION, messagePositionPropPrec); + + ObjectNode messagePositionPropHead = MappingUtils.newObjectNode(new KeyValueEntry[] { new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_DOUBLE) }); + positionPropertiesNode.set(MessageSchema.MESSAGE_POS_HEADING, messagePositionPropHead); + + ObjectNode messagePositionPropSpeed = MappingUtils.newObjectNode(new KeyValueEntry[] { new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_DOUBLE) }); + positionPropertiesNode.set(MessageSchema.MESSAGE_POS_SPEED, messagePositionPropSpeed); + + ObjectNode messagePositionPropTime = MappingUtils.newObjectNode( + new KeyValueEntry[] { new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_DATE), new KeyValueEntry(SchemaKeys.KEY_FORMAT, DatastoreUtils.DATASTORE_DATE_FORMAT) }); + positionPropertiesNode.set(MessageSchema.MESSAGE_POS_TIMESTAMP, messagePositionPropTime); + + ObjectNode messagePositionPropSat = MappingUtils.newObjectNode(new KeyValueEntry[] { new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_INTEGER) }); + positionPropertiesNode.set(MessageSchema.MESSAGE_POS_SATELLITES, messagePositionPropSat); + + ObjectNode messagePositionPropStat = MappingUtils.newObjectNode(new KeyValueEntry[] { new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_INTEGER) }); + positionPropertiesNode.set(MessageSchema.MESSAGE_POS_STATUS, messagePositionPropStat); + } + positionNode.set(SchemaKeys.FIELD_NAME_PROPERTIES, positionPropertiesNode); + + propertiesNode.set(SchemaKeys.FIELD_NAME_POSITION, positionNode); + } + messageNode.set(SchemaKeys.FIELD_NAME_PROPERTIES, propertiesNode); + + ObjectNode messageMetrics = MappingUtils.newObjectNode( + new KeyValueEntry[] { new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_OBJECT), new KeyValueEntry(SchemaKeys.KEY_ENABLED, true), + new KeyValueEntry(SchemaKeys.KEY_DYNAMIC, true) }); + propertiesNode.set(MessageSchema.MESSAGE_METRICS, messageMetrics); + + ObjectNode messageBody = MappingUtils.newObjectNode( + new KeyValueEntry[] { new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_BINARY), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_FALSE) }); + propertiesNode.set(MessageSchema.MESSAGE_BODY, messageBody); + } + return messageNode; + } + @Override public DatastoreMessage find(KapuaId scopeId, StorableId storableId, long time) { return this.doFind(scopeId, indexResolver(scopeId, time), storableId); @@ -172,22 +280,23 @@ private ObjectNode getNewMessageMappingsBuilder(Map esMetrics) t ObjectNode metricMapping; for (Map.Entry esMetric : esMetrics.entrySet()) { Metric metric = esMetric.getValue(); - metricMapping = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_DYNAMIC, SchemaKeys.VALUE_TRUE)}); + metricMapping = MappingUtils.newObjectNode(new KeyValueEntry[] { new KeyValueEntry(SchemaKeys.KEY_DYNAMIC, SchemaKeys.VALUE_TRUE) }); ObjectNode metricMappingPropertiesNode = MappingUtils.newObjectNode(); // properties (inside metric name) ObjectNode valueMappingNode; switch (metric.getType()) { - case SchemaKeys.TYPE_STRING: - valueMappingNode = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE)}); - break; - case SchemaKeys.TYPE_DATE: - valueMappingNode = MappingUtils.newObjectNode( - new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_DATE), new KeyValueEntry(SchemaKeys.KEY_FORMAT, DatastoreUtils.DATASTORE_DATE_FORMAT)}); - break; - default: - valueMappingNode = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, metric.getType())}); - break; + case SchemaKeys.TYPE_STRING: + valueMappingNode = MappingUtils.newObjectNode( + new KeyValueEntry[] { new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE) }); + break; + case SchemaKeys.TYPE_DATE: + valueMappingNode = MappingUtils.newObjectNode( + new KeyValueEntry[] { new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_DATE), new KeyValueEntry(SchemaKeys.KEY_FORMAT, DatastoreUtils.DATASTORE_DATE_FORMAT) }); + break; + default: + valueMappingNode = MappingUtils.newObjectNode(new KeyValueEntry[] { new KeyValueEntry(SchemaKeys.KEY_TYPE, metric.getType()) }); + break; } metricMappingPropertiesNode.set(datastoreUtils.getClientMetricFromAcronym(metric.getType()), valueMappingNode); diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MessageStoreFacadeImpl.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MessageStoreFacadeImpl.java index e125bad715a..37672f1186a 100644 --- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MessageStoreFacadeImpl.java +++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MessageStoreFacadeImpl.java @@ -12,6 +12,13 @@ *******************************************************************************/ package org.eclipse.kapua.service.datastore.internal; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; + +import javax.inject.Inject; + import org.eclipse.kapua.KapuaIllegalArgumentException; import org.eclipse.kapua.commons.cache.LocalCache; import org.eclipse.kapua.commons.util.ArgumentValidator; @@ -22,33 +29,30 @@ import org.eclipse.kapua.message.internal.device.data.KapuaDataChannelImpl; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.datastore.exception.DatastoreDisabledException; -import org.eclipse.kapua.service.datastore.internal.mediator.ChannelInfoField; -import org.eclipse.kapua.service.datastore.internal.mediator.ClientInfoField; import org.eclipse.kapua.service.datastore.internal.mediator.ConfigurationException; import org.eclipse.kapua.service.datastore.internal.mediator.DatastoreChannel; import org.eclipse.kapua.service.datastore.internal.mediator.DatastoreUtils; -import org.eclipse.kapua.service.datastore.internal.mediator.MessageField; +import org.eclipse.kapua.service.datastore.internal.mediator.InfoFieldHelper; import org.eclipse.kapua.service.datastore.internal.mediator.MessageInfo; import org.eclipse.kapua.service.datastore.internal.mediator.MessageStoreConfiguration; import org.eclipse.kapua.service.datastore.internal.mediator.Metric; -import org.eclipse.kapua.service.datastore.internal.mediator.MetricInfoField; import org.eclipse.kapua.service.datastore.internal.model.ChannelInfoImpl; import org.eclipse.kapua.service.datastore.internal.model.ClientInfoImpl; import org.eclipse.kapua.service.datastore.internal.model.DataIndexBy; import org.eclipse.kapua.service.datastore.internal.model.DatastoreMessageImpl; -import org.eclipse.kapua.service.datastore.internal.model.MessageListResultImpl; import org.eclipse.kapua.service.datastore.internal.model.MessageUniquenessCheck; import org.eclipse.kapua.service.datastore.internal.model.MetricInfoImpl; -import org.eclipse.kapua.service.datastore.internal.model.query.ChannelInfoQueryImpl; -import org.eclipse.kapua.service.datastore.internal.model.query.ClientInfoQueryImpl; -import org.eclipse.kapua.service.datastore.internal.model.query.MetricInfoQueryImpl; import org.eclipse.kapua.service.datastore.internal.model.query.predicate.ChannelMatchPredicateImpl; import org.eclipse.kapua.service.datastore.model.ChannelInfoListResult; import org.eclipse.kapua.service.datastore.model.ClientInfoListResult; import org.eclipse.kapua.service.datastore.model.DatastoreMessage; import org.eclipse.kapua.service.datastore.model.MessageListResult; import org.eclipse.kapua.service.datastore.model.MetricInfoListResult; +import org.eclipse.kapua.service.datastore.model.query.ChannelInfoQuery; +import org.eclipse.kapua.service.datastore.model.query.ClientInfoQuery; +import org.eclipse.kapua.service.datastore.model.query.MessageField; import org.eclipse.kapua.service.datastore.model.query.MessageQuery; +import org.eclipse.kapua.service.datastore.model.query.MetricInfoQuery; import org.eclipse.kapua.service.elasticsearch.client.exception.ClientException; import org.eclipse.kapua.service.elasticsearch.client.exception.QueryMappingException; import org.eclipse.kapua.service.storable.exception.MappingException; @@ -57,12 +61,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.inject.Inject; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; - /** * Message store facade * @@ -126,7 +124,8 @@ public MessageStoreFacadeImpl( * @throws ClientException */ @Override - public StorableId store(KapuaMessage message, String messageId, boolean newInsert) throws KapuaIllegalArgumentException, DatastoreDisabledException, ConfigurationException, ClientException, MappingException { + public StorableId store(KapuaMessage message, String messageId, boolean newInsert) + throws KapuaIllegalArgumentException, DatastoreDisabledException, ConfigurationException, ClientException, MappingException { ArgumentValidator.notNull(message, "message"); ArgumentValidator.notNull(message.getScopeId(), SCOPE_ID); ArgumentValidator.notNull(message.getReceivedOn(), "receivedOn"); @@ -280,7 +279,6 @@ public long count(MessageQuery query) throws KapuaIllegalArgumentException, Conf return messageRepository.count(query); } - @Override public void onAfterMessageStore(MessageInfo messageInfo, DatastoreMessage message) throws KapuaIllegalArgumentException, @@ -293,7 +291,7 @@ public void onAfterMessageStore(MessageInfo messageInfo, DatastoreMessage messag ClientInfoImpl clientInfo = new ClientInfoImpl(message.getScopeId()); clientInfo.setClientId(message.getClientId()); - clientInfo.setId(storableIdFactory.newStorableId(ClientInfoField.getOrDeriveId(null, message.getScopeId(), message.getClientId()))); + clientInfo.setId(storableIdFactory.newStorableId(InfoFieldHelper.getOrDeriveId(null, message.getScopeId(), message.getClientId()))); clientInfo.setFirstMessageId(message.getDatastoreId()); clientInfo.setFirstMessageOn(message.getTimestamp()); clientInfoRegistryFacade.upstore(clientInfo); @@ -303,7 +301,7 @@ public void onAfterMessageStore(MessageInfo messageInfo, DatastoreMessage messag channelInfo.setName(semanticChannel); channelInfo.setFirstMessageId(message.getDatastoreId()); channelInfo.setFirstMessageOn(message.getTimestamp()); - channelInfo.setId(storableIdFactory.newStorableId(ChannelInfoField.getOrDeriveId(null, channelInfo))); + channelInfo.setId(storableIdFactory.newStorableId(InfoFieldHelper.getOrDeriveId(null, channelInfo))); channelInfoStoreFacade.upstore(channelInfo); KapuaPayload payload = message.getPayload(); @@ -324,7 +322,7 @@ public void onAfterMessageStore(MessageInfo messageInfo, DatastoreMessage messag metricInfo.setChannel(semanticChannel); metricInfo.setName(entry.getKey()); metricInfo.setMetricType(entry.getValue().getClass()); - metricInfo.setId(storableIdFactory.newStorableId(MetricInfoField.getOrDeriveId(null, metricInfo))); + metricInfo.setId(storableIdFactory.newStorableId(InfoFieldHelper.getOrDeriveId(null, metricInfo))); metricInfo.setFirstMessageId(message.getDatastoreId()); metricInfo.setFirstMessageOn(message.getTimestamp()); messageMetrics[i++] = metricInfo; @@ -352,13 +350,12 @@ public MessageListResult query(MessageQuery query) ArgumentValidator.notNull(query.getScopeId(), QUERY_SCOPE_ID); if (!this.isDatastoreServiceEnabled(query.getScopeId())) { LOG.debug("Storage not enabled for account {}, returning empty result", query.getScopeId()); - return new MessageListResultImpl(); + return new MessageListResult(); } return messageRepository.query(query); } - // TODO cache will not be reset from the client code it should be automatically reset // after some time. private void resetCache(KapuaId scopeId, KapuaId deviceId, String channel, String clientId) throws Exception { @@ -385,7 +382,7 @@ private void resetCache(KapuaId scopeId, KapuaId deviceId, String channel, Strin int offset = 0; long totalHits = 1; - MetricInfoQueryImpl metricQuery = new MetricInfoQueryImpl(scopeId); + MetricInfoQuery metricQuery = new MetricInfoQuery(scopeId); metricQuery.setLimit(pageSize + 1); metricQuery.setOffset(offset); @@ -414,7 +411,7 @@ private void resetCache(KapuaId scopeId, KapuaId deviceId, String channel, Strin LOG.debug("Removed cached channel metrics for: {}", channel); metricInfoRepository.delete(metricQuery); LOG.debug("Removed channel metrics for: {}", channel); - ChannelInfoQueryImpl channelQuery = new ChannelInfoQueryImpl(scopeId); + ChannelInfoQuery channelQuery = new ChannelInfoQuery(scopeId); channelQuery.setLimit(pageSize + 1); channelQuery.setOffset(offset); @@ -448,7 +445,7 @@ private void resetCache(KapuaId scopeId, KapuaId deviceId, String channel, Strin LOG.debug("Removed channels for: {}", channel); // Remove client if (isClientToDelete) { - ClientInfoQueryImpl clientInfoQuery = new ClientInfoQueryImpl(scopeId); + ClientInfoQuery clientInfoQuery = new ClientInfoQuery(scopeId); clientInfoQuery.setLimit(pageSize + 1); clientInfoQuery.setOffset(offset); @@ -483,8 +480,8 @@ private void resetCache(KapuaId scopeId, KapuaId deviceId, String channel, Strin // Utility methods /** - * Check if the channel admit any client identifier (so if the channel has a specific wildcard in the second topic level).
        - * In the MQTT word this method return true if the topic starts with 'account/+/'. + * Check if the channel admit any client identifier (so if the channel has a specific wildcard in the second topic level).
        In the MQTT word this method return true if the topic starts with + * 'account/+/'. * * @param clientId * @return @@ -494,7 +491,6 @@ private boolean isAnyClientId(String clientId) { return DatastoreChannel.SINGLE_LEVEL_WCARD.equals(clientId); } - @Override public void refreshAllIndexes() throws ClientException { messageRepository.refreshAllIndexes(); @@ -511,7 +507,6 @@ public void deleteAllIndexes() throws ClientException { metricInfoRepository.deleteAllIndexes(); } - @Override public void deleteIndexes(String indexExp) throws ClientException { messageRepository.deleteIndexes(indexExp); diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MessageStoreFactoryImpl.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MessageStoreFactoryImpl.java index c8c8379e9ef..14ae46706bd 100644 --- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MessageStoreFactoryImpl.java +++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MessageStoreFactoryImpl.java @@ -12,17 +12,12 @@ *******************************************************************************/ package org.eclipse.kapua.service.datastore.internal; -import org.eclipse.kapua.model.id.KapuaId; +import javax.inject.Singleton; + import org.eclipse.kapua.service.datastore.MessageStoreFactory; import org.eclipse.kapua.service.datastore.MetricInfoFactory; import org.eclipse.kapua.service.datastore.internal.model.DatastoreMessageImpl; -import org.eclipse.kapua.service.datastore.internal.model.MessageListResultImpl; -import org.eclipse.kapua.service.datastore.internal.model.query.MessageQueryImpl; import org.eclipse.kapua.service.datastore.model.DatastoreMessage; -import org.eclipse.kapua.service.datastore.model.MessageListResult; -import org.eclipse.kapua.service.datastore.model.query.MessageQuery; - -import javax.inject.Singleton; /** * {@link MetricInfoFactory} implementation. @@ -36,14 +31,4 @@ public class MessageStoreFactoryImpl implements MessageStoreFactory { public DatastoreMessage newStorable() { return new DatastoreMessageImpl(); } - - @Override - public MessageListResult newListResult() { - return new MessageListResultImpl(); - } - - @Override - public MessageQuery newQuery(KapuaId scopeId) { - return new MessageQueryImpl(scopeId); - } } diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MessageStoreServiceImpl.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MessageStoreServiceImpl.java index 0f6c2293f88..8c1d6b3a50e 100644 --- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MessageStoreServiceImpl.java +++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MessageStoreServiceImpl.java @@ -12,7 +12,12 @@ *******************************************************************************/ package org.eclipse.kapua.service.datastore.internal; -import com.codahale.metrics.Timer.Context; +import java.util.Optional; +import java.util.UUID; + +import javax.inject.Inject; +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaErrorCodes; import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.KapuaIllegalArgumentException; @@ -25,7 +30,6 @@ import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.authorization.AuthorizationService; import org.eclipse.kapua.service.authorization.permission.Permission; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; import org.eclipse.kapua.service.datastore.MessageStoreService; import org.eclipse.kapua.service.datastore.internal.mediator.ConfigurationException; import org.eclipse.kapua.service.datastore.internal.mediator.DatastoreCommunicationException; @@ -43,10 +47,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.inject.Inject; -import javax.inject.Singleton; -import java.util.Optional; -import java.util.UUID; +import com.codahale.metrics.Timer.Context; /** * Message store service implementation. @@ -60,7 +61,6 @@ public class MessageStoreServiceImpl extends KapuaConfigurableServiceBase implem private MetricsDatastore metrics; protected AuthorizationService authorizationService; - protected PermissionFactory permissionFactory; protected final Integer maxEntriesOnDelete; protected final Integer maxResultWindowValue; @@ -69,15 +69,13 @@ public class MessageStoreServiceImpl extends KapuaConfigurableServiceBase implem @Inject public MessageStoreServiceImpl( TxManager txManager, - PermissionFactory permissionFactory, AuthorizationService authorizationService, ServiceConfigurationManager serviceConfigurationManager, MessageStoreFacade messageStoreFacade, MetricsDatastore metricsDatastore, DatastoreSettings datastoreSettings ) { - super(txManager, serviceConfigurationManager, Domains.DATASTORE, authorizationService, permissionFactory); - this.permissionFactory = permissionFactory; + super(txManager, serviceConfigurationManager, Domains.DATASTORE, authorizationService); this.authorizationService = authorizationService; this.metrics = metricsDatastore; this.messageStoreFacade = messageStoreFacade; @@ -185,7 +183,8 @@ public long count(MessageQuery query) } catch (Exception e) { logException(e); throw new DatastoreException(KapuaErrorCodes.INTERNAL_ERROR, - e.getCause() != null && (e.getCause() instanceof ClientException) ? e.getCause() : e, //in case where there is a ClientException I just want this as a cause and not the runtime exception + e.getCause() != null && (e.getCause() instanceof ClientException) ? e.getCause() : e, + //in case where there is a ClientException I just want this as a cause and not the runtime exception e.getMessage()); } } @@ -218,7 +217,7 @@ public void delete(MessageQuery query) protected void checkDataAccess(KapuaId scopeId, Actions action) throws KapuaException { - Permission permission = permissionFactory.newPermission(Domains.DATASTORE, action, scopeId); + Permission permission = new Permission(Domains.DATASTORE, action, scopeId); authorizationService.checkPermission(permission); } diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MetricInfoFactoryImpl.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MetricInfoFactoryImpl.java index 986dd64da7e..6aba389bcf5 100644 --- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MetricInfoFactoryImpl.java +++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MetricInfoFactoryImpl.java @@ -12,16 +12,11 @@ *******************************************************************************/ package org.eclipse.kapua.service.datastore.internal; -import org.eclipse.kapua.model.id.KapuaId; +import javax.inject.Singleton; + import org.eclipse.kapua.service.datastore.MetricInfoFactory; import org.eclipse.kapua.service.datastore.internal.model.MetricInfoImpl; -import org.eclipse.kapua.service.datastore.internal.model.MetricInfoListResultImpl; -import org.eclipse.kapua.service.datastore.internal.model.query.MetricInfoQueryImpl; import org.eclipse.kapua.service.datastore.model.MetricInfo; -import org.eclipse.kapua.service.datastore.model.MetricInfoListResult; -import org.eclipse.kapua.service.datastore.model.query.MetricInfoQuery; - -import javax.inject.Singleton; /** * {@link MetricInfoFactory} implementation. @@ -35,14 +30,4 @@ public class MetricInfoFactoryImpl implements MetricInfoFactory { public MetricInfo newStorable() { return new MetricInfoImpl(); } - - @Override - public MetricInfoListResult newListResult() { - return new MetricInfoListResultImpl(); - } - - @Override - public MetricInfoQuery newQuery(KapuaId scopeId) { - return new MetricInfoQueryImpl(scopeId); - } } diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MetricInfoRegistryFacadeImpl.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MetricInfoRegistryFacadeImpl.java index 26e839a61e6..5d121aef37b 100644 --- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MetricInfoRegistryFacadeImpl.java +++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MetricInfoRegistryFacadeImpl.java @@ -22,9 +22,7 @@ import org.eclipse.kapua.commons.util.ArgumentValidator; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.datastore.internal.mediator.ConfigurationException; -import org.eclipse.kapua.service.datastore.internal.mediator.MetricInfoField; -import org.eclipse.kapua.service.datastore.internal.model.MetricInfoListResultImpl; -import org.eclipse.kapua.service.datastore.internal.model.query.MetricInfoQueryImpl; +import org.eclipse.kapua.service.datastore.internal.mediator.InfoFieldHelper; import org.eclipse.kapua.service.datastore.model.MetricInfo; import org.eclipse.kapua.service.datastore.model.MetricInfoListResult; import org.eclipse.kapua.service.datastore.model.query.MetricInfoQuery; @@ -91,7 +89,7 @@ public StorableId upstore(MetricInfo metricInfo) throws KapuaIllegalArgumentExce ArgumentValidator.notNull(metricInfo.getFirstMessageId(), "metricInfoCreator.firstPublishedMessageId"); ArgumentValidator.notNull(metricInfo.getFirstMessageOn(), "metricInfoCreator.firstPublishedMessageTimestamp"); - String metricInfoId = MetricInfoField.getOrDeriveId(metricInfo.getId(), metricInfo); + String metricInfoId = InfoFieldHelper.getOrDeriveId(metricInfo.getId(), metricInfo); StorableId storableId = storableIdFactory.newStorableId(metricInfoId); // Store channel. Look up channel in the cache, and cache it if it doesn't exist @@ -126,7 +124,7 @@ public void upstore(MetricInfo[] metricInfos) // Create a bulk request final List toUpsert = new ArrayList<>(); for (MetricInfo metricInfo : metricInfos) { - String metricInfoId = MetricInfoField.getOrDeriveId(metricInfo.getId(), metricInfo); + String metricInfoId = InfoFieldHelper.getOrDeriveId(metricInfo.getId(), metricInfo); // fix #REPLACE_ISSUE_NUMBER if (!datastoreCacheManager.getMetricsCache().get(metricInfoId)) { StorableId storableId = storableIdFactory.newStorableId(metricInfoId); @@ -198,7 +196,7 @@ public MetricInfo find(KapuaId scopeId, StorableId id) throws KapuaIllegalArgume } private MetricInfo doFind(KapuaId scopeId, StorableId id) throws KapuaIllegalArgumentException, ConfigurationException, ClientException { - MetricInfoQueryImpl idsQuery = new MetricInfoQueryImpl(scopeId); + MetricInfoQuery idsQuery = new MetricInfoQuery(scopeId); idsQuery.setLimit(1); IdsPredicate idsPredicate = storablePredicateFactory.newIdsPredicate(); @@ -225,7 +223,7 @@ public MetricInfoListResult query(MetricInfoQuery query) throws KapuaIllegalArgu if (!isDatastoreServiceEnabled(query.getScopeId())) { LOG.debug(STORAGE_NOT_ENABLED, query.getScopeId()); - return new MetricInfoListResultImpl(); + return new MetricInfoListResult(); } return repository.query(query); diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MetricInfoRegistryServiceImpl.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MetricInfoRegistryServiceImpl.java index 8063b15f995..08f3ad92b58 100644 --- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MetricInfoRegistryServiceImpl.java +++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MetricInfoRegistryServiceImpl.java @@ -13,6 +13,14 @@ *******************************************************************************/ package org.eclipse.kapua.service.datastore.internal; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Optional; + +import javax.inject.Inject; +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.commons.model.domains.Domains; import org.eclipse.kapua.commons.service.internal.KapuaServiceDisabledException; @@ -21,19 +29,17 @@ import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.authorization.AuthorizationService; import org.eclipse.kapua.service.authorization.permission.Permission; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; import org.eclipse.kapua.service.datastore.MetricInfoRegistryService; -import org.eclipse.kapua.service.datastore.internal.mediator.MessageField; -import org.eclipse.kapua.service.datastore.internal.mediator.MetricInfoField; -import org.eclipse.kapua.service.datastore.internal.model.query.MessageQueryImpl; -import org.eclipse.kapua.service.datastore.internal.schema.MessageSchema; import org.eclipse.kapua.service.datastore.internal.setting.DatastoreSettings; import org.eclipse.kapua.service.datastore.internal.setting.DatastoreSettingsKey; import org.eclipse.kapua.service.datastore.model.DatastoreMessage; import org.eclipse.kapua.service.datastore.model.MessageListResult; import org.eclipse.kapua.service.datastore.model.MetricInfo; import org.eclipse.kapua.service.datastore.model.MetricInfoListResult; +import org.eclipse.kapua.service.datastore.model.query.MessageField; import org.eclipse.kapua.service.datastore.model.query.MessageQuery; +import org.eclipse.kapua.service.datastore.model.query.MessageSchema; +import org.eclipse.kapua.service.datastore.model.query.MetricInfoField; import org.eclipse.kapua.service.datastore.model.query.MetricInfoQuery; import org.eclipse.kapua.service.datastore.model.query.predicate.DatastorePredicateFactory; import org.eclipse.kapua.service.storable.model.id.StorableId; @@ -47,13 +53,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.inject.Inject; -import javax.inject.Singleton; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.Optional; - /** * Metric information registry implementation. * @@ -67,7 +66,6 @@ public class MetricInfoRegistryServiceImpl implements MetricInfoRegistryService private final StorablePredicateFactory storablePredicateFactory; private final AuthorizationService authorizationService; - private final PermissionFactory permissionFactory; private final MetricInfoRegistryFacade metricInfoRegistryFacade; private final DatastorePredicateFactory datastorePredicateFactory; private final MessageRepository messageRepository; @@ -81,14 +79,12 @@ public class MetricInfoRegistryServiceImpl implements MetricInfoRegistryService public MetricInfoRegistryServiceImpl( StorablePredicateFactory storablePredicateFactory, AuthorizationService authorizationService, - PermissionFactory permissionFactory, DatastorePredicateFactory datastorePredicateFactory, MetricInfoRegistryFacade metricInfoRegistryFacade, MessageRepository messageRepository, DatastoreSettings datastoreSettings) { this.storablePredicateFactory = storablePredicateFactory; this.authorizationService = authorizationService; - this.permissionFactory = permissionFactory; this.datastorePredicateFactory = datastorePredicateFactory; this.metricInfoRegistryFacade = metricInfoRegistryFacade; this.messageRepository = messageRepository; @@ -211,7 +207,7 @@ public void delete(KapuaId scopeId, StorableId id) private void checkDataAccess(KapuaId scopeId, Actions action) throws KapuaException { - Permission permission = permissionFactory.newPermission(Domains.DATASTORE, action, scopeId); + Permission permission = new Permission(Domains.DATASTORE, action, scopeId); authorizationService.checkPermission(permission); } @@ -225,7 +221,7 @@ private void updateLastPublishedFields(MetricInfo metricInfo) throws KapuaExcept List sort = new ArrayList<>(); sort.add(SortField.descending(MessageSchema.MESSAGE_TIMESTAMP)); - MessageQuery messageQuery = new MessageQueryImpl(metricInfo.getScopeId()); + MessageQuery messageQuery = new MessageQuery(metricInfo.getScopeId()); messageQuery.setAskTotalCount(true); messageQuery.setFetchStyle(StorableFetchStyle.FIELDS); messageQuery.setLimit(1); diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MetricInfoRepositoryImpl.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MetricInfoRepositoryImpl.java index 87bbdc9b2cc..734ea428e61 100644 --- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MetricInfoRepositoryImpl.java +++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/MetricInfoRepositoryImpl.java @@ -12,21 +12,26 @@ *******************************************************************************/ package org.eclipse.kapua.service.datastore.internal; -import com.fasterxml.jackson.databind.JsonNode; +import javax.inject.Inject; + import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.datastore.MetricInfoFactory; import org.eclipse.kapua.service.datastore.internal.mediator.DatastoreUtils; -import org.eclipse.kapua.service.datastore.internal.schema.MetricInfoSchema; import org.eclipse.kapua.service.datastore.internal.setting.DatastoreSettings; import org.eclipse.kapua.service.datastore.model.MetricInfo; import org.eclipse.kapua.service.datastore.model.MetricInfoListResult; import org.eclipse.kapua.service.datastore.model.query.MetricInfoQuery; +import org.eclipse.kapua.service.datastore.model.query.MetricInfoSchema; import org.eclipse.kapua.service.elasticsearch.client.ElasticsearchClientProvider; +import org.eclipse.kapua.service.elasticsearch.client.SchemaKeys; import org.eclipse.kapua.service.storable.exception.MappingException; import org.eclipse.kapua.service.storable.model.id.StorableId; import org.eclipse.kapua.service.storable.model.query.predicate.StorablePredicateFactory; +import org.eclipse.kapua.service.storable.model.utils.KeyValueEntry; +import org.eclipse.kapua.service.storable.model.utils.MappingUtils; -import javax.inject.Inject; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ObjectNode; public class MetricInfoRepositoryImpl extends DatastoreElasticSearchRepositoryBase implements MetricInfoRepository { @@ -45,13 +50,77 @@ protected MetricInfoRepositoryImpl( metricInfoFactory, storablePredicateFactory, datastoreCacheManager.getMetricsCache(), - datastoreSettings); + datastoreSettings, + scopeId -> new MetricInfoQuery(scopeId), + () -> new MetricInfoListResult()); this.datastoreUtils = datastoreUtils; } @Override protected JsonNode getIndexSchema() throws MappingException { - return MetricInfoSchema.getMetricTypeSchema(); + return getMetricTypeSchema(); + } + + /** + * Create and return the Json representation of the metric info schema + * + * @return + * @throws MappingException + * @since 1.0.0 + */ + public static JsonNode getMetricTypeSchema() throws MappingException { + + ObjectNode metricNode = MappingUtils.newObjectNode(); + + ObjectNode sourceMetric = MappingUtils.newObjectNode(new KeyValueEntry[] { new KeyValueEntry(SchemaKeys.KEY_ENABLED, true) }); + metricNode.set(SchemaKeys.KEY_SOURCE, sourceMetric); + + ObjectNode propertiesNode = MappingUtils.newObjectNode(); + { + ObjectNode metricAccount = MappingUtils.newObjectNode( + new KeyValueEntry[] { new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE) }); + propertiesNode.set(MetricInfoSchema.METRIC_SCOPE_ID, metricAccount); + + ObjectNode metricClientId = MappingUtils.newObjectNode( + new KeyValueEntry[] { new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE) }); + propertiesNode.set(MetricInfoSchema.METRIC_CLIENT_ID, metricClientId); + + ObjectNode metricChannel = MappingUtils.newObjectNode( + new KeyValueEntry[] { new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE) }); + propertiesNode.set(MetricInfoSchema.METRIC_CHANNEL, metricChannel); + + ObjectNode metricMtrNode = MappingUtils.newObjectNode( + new KeyValueEntry[] { new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_OBJECT), new KeyValueEntry(SchemaKeys.KEY_ENABLED, true), + new KeyValueEntry(SchemaKeys.KEY_DYNAMIC, false) }); + ObjectNode metricMtrPropertiesNode = MappingUtils.newObjectNode(); + { + ObjectNode metricMtrNameNode = MappingUtils.newObjectNode( + new KeyValueEntry[] { new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE) }); + metricMtrPropertiesNode.set(MetricInfoSchema.METRIC_MTR_NAME, metricMtrNameNode); + + ObjectNode metricMtrTypeNode = MappingUtils.newObjectNode( + new KeyValueEntry[] { new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE) }); + metricMtrPropertiesNode.set(MetricInfoSchema.METRIC_MTR_TYPE, metricMtrTypeNode); + + ObjectNode metricMtrValueNode = MappingUtils.newObjectNode( + new KeyValueEntry[] { new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE) }); + metricMtrPropertiesNode.set(MetricInfoSchema.METRIC_MTR_VALUE, metricMtrValueNode); + + ObjectNode metricMtrTimestampNode = MappingUtils.newObjectNode( + new KeyValueEntry[] { new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_DATE), new KeyValueEntry(SchemaKeys.KEY_FORMAT, DatastoreUtils.DATASTORE_DATE_FORMAT) }); + metricMtrPropertiesNode.set(MetricInfoSchema.METRIC_MTR_TIMESTAMP, metricMtrTimestampNode); + + ObjectNode metricMtrMsgIdNode = MappingUtils.newObjectNode( + new KeyValueEntry[] { new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE) }); + metricMtrPropertiesNode.set(MetricInfoSchema.METRIC_MTR_MSG_ID, metricMtrMsgIdNode); + } + metricMtrNode.set(SchemaKeys.FIELD_NAME_PROPERTIES, metricMtrPropertiesNode); + + propertiesNode.set(MetricInfoSchema.METRIC_MTR, metricMtrNode); + } + metricNode.set(SchemaKeys.FIELD_NAME_PROPERTIES, propertiesNode); + + return metricNode; } @Override diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/converter/ModelContextImpl.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/converter/ModelContextImpl.java index 31d89b93067..fece3605e6d 100644 --- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/converter/ModelContextImpl.java +++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/converter/ModelContextImpl.java @@ -12,7 +12,16 @@ *******************************************************************************/ package org.eclipse.kapua.service.datastore.internal.converter; -import com.fasterxml.jackson.core.Base64Variants; +import java.math.BigInteger; +import java.text.ParseException; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import javax.inject.Inject; + import org.eclipse.kapua.commons.model.id.KapuaEid; import org.eclipse.kapua.commons.util.KapuaDateUtils; import org.eclipse.kapua.message.KapuaPayload; @@ -26,14 +35,14 @@ import org.eclipse.kapua.service.datastore.internal.model.ClientInfoImpl; import org.eclipse.kapua.service.datastore.internal.model.DatastoreMessageImpl; import org.eclipse.kapua.service.datastore.internal.model.MetricInfoImpl; -import org.eclipse.kapua.service.datastore.internal.schema.ChannelInfoSchema; -import org.eclipse.kapua.service.datastore.internal.schema.ClientInfoSchema; -import org.eclipse.kapua.service.datastore.internal.schema.MessageSchema; -import org.eclipse.kapua.service.datastore.internal.schema.MetricInfoSchema; import org.eclipse.kapua.service.datastore.model.ChannelInfo; import org.eclipse.kapua.service.datastore.model.ClientInfo; import org.eclipse.kapua.service.datastore.model.DatastoreMessage; import org.eclipse.kapua.service.datastore.model.MetricInfo; +import org.eclipse.kapua.service.datastore.model.query.ChannelInfoSchema; +import org.eclipse.kapua.service.datastore.model.query.ClientInfoSchema; +import org.eclipse.kapua.service.datastore.model.query.MessageSchema; +import org.eclipse.kapua.service.datastore.model.query.MetricInfoSchema; import org.eclipse.kapua.service.elasticsearch.client.ModelContext; import org.eclipse.kapua.service.elasticsearch.client.QueryConverter; import org.eclipse.kapua.service.elasticsearch.client.exception.DatamodelMappingException; @@ -42,14 +51,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.inject.Inject; -import java.math.BigInteger; -import java.text.ParseException; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; +import com.fasterxml.jackson.core.Base64Variants; /** * Datastore model context implementation @@ -128,7 +130,8 @@ public Map marshal(Object object) throws DatamodelMappingExcepti /** * Unmarshals the {@link DatastoreMessage}. * - * @param messageMap The {@link DatastoreMessage}. + * @param messageMap + * The {@link DatastoreMessage}. * @throws ParseException * @since 1.0.0 */ @@ -222,11 +225,11 @@ private DatastoreMessage unmarshalDatastoreMessage(Map messageMa if (messageMap.get(MessageSchema.MESSAGE_METRICS) != null) { Map metrics = (Map) messageMap.get(MessageSchema.MESSAGE_METRICS); Map payloadMetrics = new HashMap<>(); - String[] metricNames = metrics.keySet().toArray(new String[]{}); + String[] metricNames = metrics.keySet().toArray(new String[] {}); for (String metricsName : metricNames) { Map metricValue = (Map) metrics.get(metricsName); if (metricValue.size() > 0) { - String[] valueTypes = metricValue.keySet().toArray(new String[]{}); + String[] valueTypes = metricValue.keySet().toArray(new String[] {}); Object value = metricValue.get(valueTypes[0]); // since elasticsearch doesn't return always the same type of the saved field // (usually due to some promotion of the field type) @@ -305,7 +308,8 @@ private ClientInfo unmarshalClientInfo(Map clientInfoMap) throws /** * Marshals the {@link DatastoreMessage}. * - * @param message The {@link DatastoreMessage}. + * @param message + * The {@link DatastoreMessage}. * @throws ParseException * @since 1.0.0 */ @@ -357,7 +361,7 @@ private Map marshalDatastoreMessage(DatastoreMessage message) th Map kapuaMetrics = payload.getMetrics(); if (kapuaMetrics != null) { Map metrics = new HashMap<>(); - String[] metricNames = kapuaMetrics.keySet().toArray(new String[]{}); + String[] metricNames = kapuaMetrics.keySet().toArray(new String[] {}); for (String kapuaMetricName : metricNames) { Object metricValue = kapuaMetrics.get(kapuaMetricName); // Sanitize field names: '.' is not allowed diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/mediator/ChannelInfoField.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/mediator/ChannelInfoField.java deleted file mode 100644 index 8094e3b0c8f..00000000000 --- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/mediator/ChannelInfoField.java +++ /dev/null @@ -1,122 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.datastore.internal.mediator; - -import org.eclipse.kapua.locator.KapuaLocator; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.datastore.internal.schema.ChannelInfoSchema; -import org.eclipse.kapua.service.datastore.model.ChannelInfo; -import org.eclipse.kapua.service.datastore.model.ChannelInfoCreator; -import org.eclipse.kapua.service.storable.model.id.StorableId; -import org.eclipse.kapua.service.storable.model.query.StorableField; - -/** - * This enumeration defines the fields names used in the {@link ChannelInfo} client schema - * - * @since 1.0.0 - */ -public enum ChannelInfoField implements StorableField { - /** - * Channel - * - * @since 1.0.0 - */ - CHANNEL(ChannelInfoSchema.CHANNEL_NAME), - - /** - * Client identifier - * - * @since 1.0.0 - */ - CLIENT_ID(ChannelInfoSchema.CHANNEL_CLIENT_ID), - - /** - * Scope id - * - * @since 1.0.0 - */ - SCOPE_ID(ChannelInfoSchema.CHANNEL_SCOPE_ID), - - /** - * Timestamp - * - * @since 1.0.0 - */ - TIMESTAMP(ChannelInfoSchema.CHANNEL_TIMESTAMP), - - /** - * Message identifier - * - * @since 1.0.0 - */ - MESSAGE_ID(ChannelInfoSchema.CHANNEL_MESSAGE_ID); - - private String field; - - private ChannelInfoField(String name) { - this.field = name; - } - - @Override - public String field() { - return field; - } - - /** - * Get the channel identifier (combining accountName clientId and c).
        - * If the id is null then it is generated - * - * @param id - * @param scopeId - * @param clientId - * @param channel - * @return - */ - private static String getOrDeriveId(StorableId id, KapuaId scopeId, String clientId, String channel) { - if (id == null) { - //TODO: FIXME: REMOVE: A collaborator in a data class? Behaviour should not be part of a data class! - return KapuaLocator.getInstance().getComponent(DatastoreUtils.class).getHashCode(scopeId.toCompactId(), clientId, channel); - } else { - return id.toString(); - } - } - - /** - * Get the channel identifier getting parameters from the metricInfoCreator. Then it calls {@link ChannelInfoField#getOrDeriveId(StorableId id, KapuaId scopeId, String clientId, String channel)} - * - * @param id - * @param channelInfoCreator - * @return - */ - public static String getOrDeriveId(StorableId id, ChannelInfoCreator channelInfoCreator) { - return getOrDeriveId(id, - channelInfoCreator.getScopeId(), - channelInfoCreator.getClientId(), - channelInfoCreator.getName()); - } - - /** - * Get the channel identifier getting parameters from the channelInfo. Then it calls {@link ChannelInfoField#getOrDeriveId(StorableId id, KapuaId scopeId, String clientId, String channel)} - * - * @param id - * @param channelInfo - * @return - */ - public static String getOrDeriveId(StorableId id, ChannelInfo channelInfo) { - return getOrDeriveId(id, - channelInfo.getScopeId(), - channelInfo.getClientId(), - channelInfo.getName()); - } - -} diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/mediator/InfoFieldHelper.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/mediator/InfoFieldHelper.java new file mode 100644 index 00000000000..3c4bb94a92e --- /dev/null +++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/mediator/InfoFieldHelper.java @@ -0,0 +1,163 @@ +/******************************************************************************* + * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Eurotech - initial API and implementation + *******************************************************************************/ +package org.eclipse.kapua.service.datastore.internal.mediator; + +import org.eclipse.kapua.locator.KapuaLocator; +import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.service.datastore.model.ChannelInfo; +import org.eclipse.kapua.service.datastore.model.ChannelInfoCreator; +import org.eclipse.kapua.service.datastore.model.ClientInfo; +import org.eclipse.kapua.service.datastore.model.MetricInfo; +import org.eclipse.kapua.service.datastore.model.MetricInfoCreator; +import org.eclipse.kapua.service.storable.model.id.StorableId; + +public class InfoFieldHelper { + + private InfoFieldHelper() { + } + + /** + * Get the client identifier (combining accountName and clientId).
        + * If the id is null then it is generated + * + * @param id + * @param scopeId + * @param clientId + * @return + */ + public static String getOrDeriveId(StorableId id, KapuaId scopeId, String clientId) { + if (id == null) { + //TODO: FIXME: REMOVE: A collaborator in a data class? Behaviour should not be part of a data class! + return KapuaLocator.getInstance().getComponent(DatastoreUtils.class).getHashCode(scopeId.toCompactId(), clientId); + } else { + return id.toString(); + } + } + + /** + * Get the client identifier (combining accountName and clientId).
        + * If the id is null then it is generated + * + * @param id + * @param clientInfo + * @return + */ + public static String getOrDeriveId(StorableId id, ClientInfo clientInfo) { + return getOrDeriveId(id, clientInfo.getScopeId(), clientInfo.getClientId()); + } + + /** + * Get the channel identifier (combining accountName clientId and c).
        + * If the id is null then it is generated + * + * @param id + * @param scopeId + * @param clientId + * @param channel + * @return + */ + private static String getOrDeriveId(StorableId id, KapuaId scopeId, String clientId, String channel) { + if (id == null) { + //TODO: FIXME: REMOVE: A collaborator in a data class? Behaviour should not be part of a data class! + return KapuaLocator.getInstance().getComponent(DatastoreUtils.class).getHashCode(scopeId.toCompactId(), clientId, channel); + } else { + return id.toString(); + } + } + + /** + * Get the channel identifier getting parameters from the metricInfoCreator. Then it calls {@link InfoFieldHelper#getOrDeriveId(StorableId id, KapuaId scopeId, String clientId, String channel)} + * + * @param id + * @param channelInfoCreator + * @return + */ + public static String getOrDeriveId(StorableId id, ChannelInfoCreator channelInfoCreator) { + return getOrDeriveId(id, + channelInfoCreator.getScopeId(), + channelInfoCreator.getClientId(), + channelInfoCreator.getName()); + } + + /** + * Get the channel identifier getting parameters from the channelInfo. Then it calls {@link InfoFieldHelper#getOrDeriveId(StorableId id, KapuaId scopeId, String clientId, String channel)} + * + * @param id + * @param channelInfo + * @return + */ + public static String getOrDeriveId(StorableId id, ChannelInfo channelInfo) { + return getOrDeriveId(id, + channelInfo.getScopeId(), + channelInfo.getClientId(), + channelInfo.getName()); + } + + /** + * Get the metric identifier (return the hash code of the string obtained by combining accountName, clientId, channel and the converted metricName and metricType).
        + * If the id is null then it is generated. + * + * @param id + * @param scopeId + * @param clientId + * @param channel + * @param metricName + * @param metricType + * @return + */ + private static String getOrDeriveId(StorableId id, KapuaId scopeId, String clientId, String channel, String metricName, Class metricType) { + if (id == null) { + //TODO: FIXME: REMOVE: A collaborator in a data class? Behaviour should not be part of a data class! + final DatastoreUtils datastoreUtils = KapuaLocator.getInstance().getComponent(DatastoreUtils.class); + String metricMappedName = datastoreUtils.getMetricValueQualifier(metricName, datastoreUtils.convertToClientMetricType(metricType)); + + return datastoreUtils.getHashCode(scopeId.toCompactId(), clientId, channel, metricMappedName); + } else { + return id.toString(); + } + } + + /** + * Get the metric identifier getting parameters from the metricInfoCreator. Then it calls + * {@link InfoFieldHelper#getOrDeriveId(StorableId id, KapuaId scopeId, String clientId, String channel, String metricName, Class metricType)} + * + * @param id + * @param metricInfoCreator + * @return + */ + public static String getOrDeriveId(StorableId id, MetricInfoCreator metricInfoCreator) { + return getOrDeriveId(id, + metricInfoCreator.getScopeId(), + metricInfoCreator.getClientId(), + metricInfoCreator.getChannel(), + metricInfoCreator.getName(), + metricInfoCreator.getMetricType());// use short me + } + + /** + * Get the metric identifier getting parameters from the metricInfo. Then it calls + * {@link InfoFieldHelper#getOrDeriveId(StorableId id, KapuaId scopeId, String clientId, String channel, String metricName, Class metricType)} + * + * @param id + * @param metricInfo + * @return + */ + public static String getOrDeriveId(StorableId id, MetricInfo metricInfo) { + return getOrDeriveId(id, + metricInfo.getScopeId(), + metricInfo.getClientId(), + metricInfo.getChannel(), + metricInfo.getName(), + metricInfo.getMetricType()); + } +} diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/mediator/MetricInfoField.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/mediator/MetricInfoField.java deleted file mode 100644 index 64d32ad493d..00000000000 --- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/mediator/MetricInfoField.java +++ /dev/null @@ -1,155 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.datastore.internal.mediator; - -import org.eclipse.kapua.locator.KapuaLocator; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.datastore.internal.schema.MetricInfoSchema; -import org.eclipse.kapua.service.datastore.model.MetricInfo; -import org.eclipse.kapua.service.datastore.model.MetricInfoCreator; -import org.eclipse.kapua.service.storable.model.id.StorableId; -import org.eclipse.kapua.service.storable.model.query.StorableField; - -/** - * This enumeration defines the fields names used in the {@link MetricInfo} client schema - * - * @since 1.0.0 - */ -public enum MetricInfoField implements StorableField { - /** - * Account name - * - * @since 1.0.0 - */ - SCOPE_ID(MetricInfoSchema.METRIC_SCOPE_ID), - - /** - * Client identifier - * - * @since 1.0.0 - */ - CLIENT_ID(MetricInfoSchema.METRIC_CLIENT_ID), - - /** - * Channel - * - * @since 1.0.0 - */ - CHANNEL(MetricInfoSchema.METRIC_CHANNEL), - - /** - * Full metric name (so with the metric type suffix) - * - * @since 1.0.0 - */ - NAME_FULL(MetricInfoSchema.METRIC_MTR_NAME_FULL), - - /** - * Metric type full name (not the acronym) - * - * @since 1.0.0 - */ - TYPE_FULL(MetricInfoSchema.METRIC_MTR_TYPE_FULL), - - /** - * Metric timestamp (derived from the message that published the metric) - * - * @since 1.3.0 - */ - TIMESTAMP(MetricInfoSchema.METRIC_MTR_TIMESTAMP), - - /** - * Metric timestamp (derived from the message that published the metric) - * - * @since 1.0.0 - */ - TIMESTAMP_FULL(MetricInfoSchema.METRIC_MTR_TIMESTAMP_FULL), - - - /** - * Message identifier - * - * @since 1.0.0 - */ - MESSAGE_ID_FULL(MetricInfoSchema.METRIC_MTR_MSG_ID_FULL); - - private String field; - - private MetricInfoField(String name) { - this.field = name; - } - - @Override - public String field() { - return field; - } - - /** - * Get the metric identifier (return the hash code of the string obtained by combining accountName, clientId, channel and the converted metricName and metricType).
        - * If the id is null then it is generated. - * - * @param id - * @param scopeId - * @param clientId - * @param channel - * @param metricName - * @param metricType - * @return - */ - private static String getOrDeriveId(StorableId id, KapuaId scopeId, String clientId, String channel, String metricName, Class metricType) { - if (id == null) { - //TODO: FIXME: REMOVE: A collaborator in a data class? Behaviour should not be part of a data class! - final DatastoreUtils datastoreUtils = KapuaLocator.getInstance().getComponent(DatastoreUtils.class); - String metricMappedName = datastoreUtils.getMetricValueQualifier(metricName, datastoreUtils.convertToClientMetricType(metricType)); - - return datastoreUtils.getHashCode(scopeId.toCompactId(), clientId, channel, metricMappedName); - } else { - return id.toString(); - } - } - - /** - * Get the metric identifier getting parameters from the metricInfoCreator. Then it calls {@link MetricInfoField#getOrDeriveId(StorableId id, KapuaId scopeId, String clientId, String channel, String - * metricName, Class metricType)} - * - * @param id - * @param metricInfoCreator - * @return - */ - public static String getOrDeriveId(StorableId id, MetricInfoCreator metricInfoCreator) { - return getOrDeriveId(id, - metricInfoCreator.getScopeId(), - metricInfoCreator.getClientId(), - metricInfoCreator.getChannel(), - metricInfoCreator.getName(), - metricInfoCreator.getMetricType());// use short me - } - - /** - * Get the metric identifier getting parameters from the metricInfo. Then it calls {@link MetricInfoField#getOrDeriveId(StorableId id, KapuaId scopeId, String clientId, String channel, String - * metricName, Class metricType)} - * - * @param id - * @param metricInfo - * @return - */ - public static String getOrDeriveId(StorableId id, MetricInfo metricInfo) { - return getOrDeriveId(id, - metricInfo.getScopeId(), - metricInfo.getClientId(), - metricInfo.getChannel(), - metricInfo.getName(), - metricInfo.getMetricType()); - } - -} diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/model/ChannelInfoCreatorImpl.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/model/ChannelInfoCreatorImpl.java deleted file mode 100644 index 70644bd4302..00000000000 --- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/model/ChannelInfoCreatorImpl.java +++ /dev/null @@ -1,93 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.datastore.internal.model; - -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.datastore.model.ChannelInfoCreator; -import org.eclipse.kapua.service.storable.model.id.StorableId; - -import java.util.Date; - -/** - * {@link ChannelInfoCreator} implementation. - * - * @since 1.0.0 - */ -public class ChannelInfoCreatorImpl implements ChannelInfoCreator { - - private KapuaId scopeId; - private String clientId; - private String name; - private StorableId messageId; - private Date messageTimestamp; - - /** - * Constructor. - * - * @param scopeId The scope {@link KapuaId}. - * @since 1.0.0 - */ - public ChannelInfoCreatorImpl(KapuaId scopeId) { - setScopeId(scopeId); - } - - @Override - public KapuaId getScopeId() { - return scopeId; - } - - @Override - public void setScopeId(KapuaId scopeId) { - this.scopeId = scopeId; - } - - @Override - public String getClientId() { - return this.clientId; - } - - @Override - public void setClientId(String clientId) { - this.clientId = clientId; - } - - @Override - public String getName() { - return name; - } - - @Override - public void setName(String name) { - this.name = name; - } - - @Override - public StorableId getMessageId() { - return messageId; - } - - @Override - public void setMessageId(StorableId messageId) { - this.messageId = messageId; - } - - @Override - public Date getMessageTimestamp() { - return messageTimestamp; - } - - @Override - public void setMessageTimestamp(Date messageTimestamp) { - this.messageTimestamp = messageTimestamp; - } -} diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/model/ChannelInfoListResultImpl.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/model/ChannelInfoListResultImpl.java deleted file mode 100644 index 30ed498d629..00000000000 --- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/model/ChannelInfoListResultImpl.java +++ /dev/null @@ -1,48 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.datastore.internal.model; - -import org.eclipse.kapua.service.datastore.model.ChannelInfo; -import org.eclipse.kapua.service.datastore.model.ChannelInfoListResult; -import org.eclipse.kapua.service.elasticsearch.client.model.ResultList; -import org.eclipse.kapua.service.storable.model.AbstractStorableListResult; - -/** - * {@link ChannelInfoListResult} implementation. - * - * @since 1.0.0 - */ -public class ChannelInfoListResultImpl extends AbstractStorableListResult implements ChannelInfoListResult { - - private static final long serialVersionUID = 1L; - - /** - * Constructor. - * - * @since 1.0.0 - */ - public ChannelInfoListResultImpl() { - super(); - } - - /** - * Constructor. - * - * @param resultList The {@link ResultList} to add. - * @since 1.0.0 - */ - public ChannelInfoListResultImpl(ResultList resultList) { - super(resultList.getResult(), resultList.getTotalCount()); - } - -} diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/model/ClientInfoCreatorImpl.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/model/ClientInfoCreatorImpl.java deleted file mode 100644 index fb401cfd4c1..00000000000 --- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/model/ClientInfoCreatorImpl.java +++ /dev/null @@ -1,82 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.datastore.internal.model; - -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.datastore.model.ClientInfoCreator; -import org.eclipse.kapua.service.storable.model.id.StorableId; - -import java.util.Date; - -/** - * {@link ClientInfoCreator} implementation. - * - * @since 1.0.0 - */ -public class ClientInfoCreatorImpl implements ClientInfoCreator { - - private KapuaId scopeId; - private String clientId; - private StorableId messageId; - private Date messageTimestamp; - - /** - * Construct a client information creator for the given account - * - * @param scopeId The scope {@link KapuaId} - * @since 1.0.0 - */ - public ClientInfoCreatorImpl(KapuaId scopeId) { - setScopeId(scopeId); - } - - @Override - public KapuaId getScopeId() { - return scopeId; - } - - @Override - public void setScopeId(KapuaId scopeId) { - this.scopeId = scopeId; - } - - @Override - public String getClientId() { - return clientId; - } - - @Override - public void setClientId(String clientId) { - this.clientId = clientId; - } - - @Override - public StorableId getMessageId() { - return messageId; - } - - @Override - public void setMessageId(StorableId messageId) { - this.messageId = messageId; - } - - @Override - public Date getMessageTimestamp() { - return messageTimestamp; - } - - @Override - public void setMessageTimestamp(Date messageTimestamp) { - this.messageTimestamp = messageTimestamp; - } -} diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/model/ClientInfoListResultImpl.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/model/ClientInfoListResultImpl.java deleted file mode 100644 index dde2b067981..00000000000 --- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/model/ClientInfoListResultImpl.java +++ /dev/null @@ -1,48 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.datastore.internal.model; - -import org.eclipse.kapua.service.datastore.model.ClientInfo; -import org.eclipse.kapua.service.datastore.model.ClientInfoListResult; -import org.eclipse.kapua.service.elasticsearch.client.model.ResultList; -import org.eclipse.kapua.service.storable.model.AbstractStorableListResult; - -/** - * {@link ClientInfoListResult} implementation. - * - * @since 1.0.0 - */ -public class ClientInfoListResultImpl extends AbstractStorableListResult implements ClientInfoListResult { - - private static final long serialVersionUID = -1398721444405133343L; - - /** - * Constructor. - * - * @since 1.0.0 - */ - public ClientInfoListResultImpl() { - super(); - } - - /** - * Constructor. - * - * @param resultList The {@link ResultList} to add. - * @since 1.0.0 - */ - public ClientInfoListResultImpl(ResultList resultList) { - super(resultList.getResult(), resultList.getTotalCount()); - } - -} diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/model/MessageListResultImpl.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/model/MessageListResultImpl.java deleted file mode 100644 index f63af368f1e..00000000000 --- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/model/MessageListResultImpl.java +++ /dev/null @@ -1,48 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.datastore.internal.model; - -import org.eclipse.kapua.service.datastore.model.DatastoreMessage; -import org.eclipse.kapua.service.datastore.model.MessageListResult; -import org.eclipse.kapua.service.elasticsearch.client.model.ResultList; -import org.eclipse.kapua.service.storable.model.AbstractStorableListResult; - -/** - * {@link MessageListResult} implementation. - * - * @since 1.0.0 - */ -public class MessageListResultImpl extends AbstractStorableListResult implements MessageListResult { - - private static final long serialVersionUID = 1L; - - /** - * Constructor. - * - * @since 1.0.0 - */ - public MessageListResultImpl() { - super(); - } - - /** - * Constructor. - * - * @param resultList The {@link ResultList} to add. - * @since 1.0.0 - */ - public MessageListResultImpl(ResultList resultList) { - super(resultList.getResult(), resultList.getTotalCount()); - } - -} diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/model/MetricInfoCreatorImpl.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/model/MetricInfoCreatorImpl.java deleted file mode 100644 index 8ced8847636..00000000000 --- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/model/MetricInfoCreatorImpl.java +++ /dev/null @@ -1,117 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.datastore.internal.model; - -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.datastore.model.MetricInfoCreator; -import org.eclipse.kapua.service.storable.model.id.StorableId; - -import java.util.Date; - -/** - * {@link MetricInfoCreator} implementation. - * - * @since 1.0.0 - */ -public class MetricInfoCreatorImpl implements MetricInfoCreator { - - private KapuaId scopeId; - private String clientId; - private String channel; - - private String name; - private Class metricType; - - private StorableId messageId; - private Date messageTimestamp; - - /** - * Constructor. - * - * @param scopeId The scope {@link KapuaId} - * @since 1.0.0 - */ - public MetricInfoCreatorImpl(KapuaId scopeId) { - setScopeId(scopeId); - } - - @Override - public KapuaId getScopeId() { - return scopeId; - } - - @Override - public void setScopeId(KapuaId scopeId) { - this.scopeId = scopeId; - } - - @Override - public String getClientId() { - return this.clientId; - } - - @Override - public void setClientId(String clientId) { - this.clientId = clientId; - } - - @Override - public String getChannel() { - return channel; - } - - @Override - public void setChannel(String channel) { - this.channel = channel; - } - - @Override - public String getName() { - return name; - } - - @Override - public void setName(String name) { - this.name = name; - } - - @Override - public Class getMetricType() { - return metricType; - } - - @Override - public void setMetricType(Class metricType) { - this.metricType = metricType; - } - - @Override - public StorableId getMessageId() { - return messageId; - } - - @Override - public void setMessageId(StorableId messageId) { - this.messageId = messageId; - } - - @Override - public Date getMessageTimestamp() { - return messageTimestamp; - } - - @Override - public void setMessageTimestamp(Date messageTimestamp) { - this.messageTimestamp = messageTimestamp; - } -} diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/model/MetricInfoListResultImpl.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/model/MetricInfoListResultImpl.java deleted file mode 100644 index a738f2990f3..00000000000 --- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/model/MetricInfoListResultImpl.java +++ /dev/null @@ -1,48 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.datastore.internal.model; - -import org.eclipse.kapua.service.datastore.model.MetricInfo; -import org.eclipse.kapua.service.datastore.model.MetricInfoListResult; -import org.eclipse.kapua.service.elasticsearch.client.model.ResultList; -import org.eclipse.kapua.service.storable.model.AbstractStorableListResult; - -/** - * {@link MetricInfoListResult} implementation. - * - * @since 1.0.0 - */ -public class MetricInfoListResultImpl extends AbstractStorableListResult implements MetricInfoListResult { - - private static final long serialVersionUID = 9057086672566426909L; - - /** - * Constructor. - * - * @since 1.0.0 - */ - public MetricInfoListResultImpl() { - super(); - } - - /** - * Constructor. - * - * @param resultList The {@link ResultList} to add. - * @since 1.0.0 - */ - public MetricInfoListResultImpl(ResultList resultList) { - super(resultList.getResult(), resultList.getTotalCount()); - } - -} diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/model/query/ChannelInfoQueryImpl.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/model/query/ChannelInfoQueryImpl.java deleted file mode 100644 index 9418a41dbeb..00000000000 --- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/model/query/ChannelInfoQueryImpl.java +++ /dev/null @@ -1,63 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.datastore.internal.model.query; - -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.datastore.internal.mediator.ChannelInfoField; -import org.eclipse.kapua.service.datastore.internal.schema.ChannelInfoSchema; -import org.eclipse.kapua.service.datastore.model.query.ChannelInfoQuery; -import org.eclipse.kapua.service.storable.model.query.AbstractStorableQuery; -import org.eclipse.kapua.service.storable.model.query.SortField; -import org.eclipse.kapua.service.storable.model.query.StorableFetchStyle; - -import java.util.Collections; - -/** - * {@link ChannelInfoQuery} implementation. - * - * @since 1.0.0 - */ -public class ChannelInfoQueryImpl extends AbstractStorableQuery implements ChannelInfoQuery { - - /** - * Constructor. - * - * @param scopeId The scope {@link KapuaId}. - * @since 1.0.0 - */ - public ChannelInfoQueryImpl(KapuaId scopeId) { - super(scopeId); - - setSortFields(Collections.singletonList(SortField.ascending(ChannelInfoSchema.CHANNEL_NAME))); - } - - @Override - public String[] getIncludes(StorableFetchStyle fetchStyle) { - return new String[]{"*"}; - } - - @Override - public String[] getExcludes(StorableFetchStyle fetchStyle) { - return new String[]{""}; - } - - @Override - public String[] getFields() { - return new String[]{ChannelInfoField.SCOPE_ID.field(), - ChannelInfoField.CHANNEL.field(), - ChannelInfoField.TIMESTAMP.field(), - ChannelInfoField.MESSAGE_ID.field(), - ChannelInfoField.CLIENT_ID.field()}; - } - -} diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/model/query/ClientInfoQueryImpl.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/model/query/ClientInfoQueryImpl.java deleted file mode 100644 index 216887e0f48..00000000000 --- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/model/query/ClientInfoQueryImpl.java +++ /dev/null @@ -1,62 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.datastore.internal.model.query; - -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.datastore.internal.mediator.ClientInfoField; -import org.eclipse.kapua.service.datastore.internal.schema.ClientInfoSchema; -import org.eclipse.kapua.service.datastore.model.query.ClientInfoQuery; -import org.eclipse.kapua.service.storable.model.query.AbstractStorableQuery; -import org.eclipse.kapua.service.storable.model.query.SortField; -import org.eclipse.kapua.service.storable.model.query.StorableFetchStyle; - -import java.util.Collections; - -/** - * {@link ClientInfoQuery} implementation. - * - * @since 1.0.0 - */ -public class ClientInfoQueryImpl extends AbstractStorableQuery implements ClientInfoQuery { - - /** - * Constructor. - * - * @param scopeId The scope {@link KapuaId}. - * @since 1.0.0 - */ - public ClientInfoQueryImpl(KapuaId scopeId) { - super(scopeId); - - setSortFields(Collections.singletonList(SortField.ascending(ClientInfoSchema.CLIENT_ID))); - } - - @Override - public String[] getIncludes(StorableFetchStyle fetchStyle) { - return new String[]{"*"}; - } - - @Override - public String[] getExcludes(StorableFetchStyle fetchStyle) { - return new String[]{""}; - } - - @Override - public String[] getFields() { - return new String[]{ClientInfoField.SCOPE_ID.field(), - ClientInfoField.CLIENT_ID.field(), - ClientInfoField.TIMESTAMP.field(), - ClientInfoField.MESSAGE_ID.field()}; - } - -} diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/model/query/MessageQueryImpl.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/model/query/MessageQueryImpl.java deleted file mode 100644 index 028af66e442..00000000000 --- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/model/query/MessageQueryImpl.java +++ /dev/null @@ -1,89 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.datastore.internal.model.query; - -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.datastore.internal.mediator.MessageField; -import org.eclipse.kapua.service.datastore.internal.schema.MessageSchema; -import org.eclipse.kapua.service.datastore.model.query.MessageQuery; -import org.eclipse.kapua.service.storable.model.query.AbstractStorableQuery; -import org.eclipse.kapua.service.storable.model.query.SortField; -import org.eclipse.kapua.service.storable.model.query.StorableFetchStyle; - -import java.util.Collections; - -/** - * {@link MessageQuery} implementation - * - * @since 1.0.0 - */ -public class MessageQueryImpl extends AbstractStorableQuery implements MessageQuery { - - /** - * Constructor. - * - * @param scopeId The scope {@link KapuaId}. - * @since 1.0.0 - */ - public MessageQueryImpl(KapuaId scopeId) { - super(scopeId); - - setSortFields(Collections.singletonList(SortField.descending(MessageSchema.MESSAGE_TIMESTAMP))); - } - - @Override - public String[] getIncludes(StorableFetchStyle fetchStyle) { - // Fetch mode - String[] includeSource = null; - switch (fetchStyle) { - case FIELDS: - includeSource = getFields(); - break; - case SOURCE_SELECT: - includeSource = new String[]{MessageSchema.MESSAGE_CAPTURED_ON, MessageSchema.MESSAGE_POSITION + ".*", MessageSchema.MESSAGE_METRICS + ".*"}; - break; - case SOURCE_FULL: - includeSource = new String[]{"*"}; - } - return includeSource; - } - - @Override - public String[] getExcludes(StorableFetchStyle fetchStyle) { - // Fetch mode - String[] excludeSource = null; - switch (fetchStyle) { - case FIELDS: - excludeSource = new String[]{""}; - break; - case SOURCE_SELECT: - excludeSource = new String[]{MessageSchema.MESSAGE_BODY}; - break; - case SOURCE_FULL: - excludeSource = new String[]{""}; - } - return excludeSource; - } - - @Override - public String[] getFields() { - return new String[]{ - MessageField.MESSAGE_ID.field(), - MessageField.SCOPE_ID.field(), - MessageField.DEVICE_ID.field(), - MessageField.CLIENT_ID.field(), - MessageField.CHANNEL.field(), - MessageField.TIMESTAMP.field()}; - } - -} diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/model/query/MetricInfoQueryImpl.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/model/query/MetricInfoQueryImpl.java deleted file mode 100644 index f03f391c761..00000000000 --- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/model/query/MetricInfoQueryImpl.java +++ /dev/null @@ -1,65 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.datastore.internal.model.query; - -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.datastore.internal.mediator.MetricInfoField; -import org.eclipse.kapua.service.datastore.internal.schema.MetricInfoSchema; -import org.eclipse.kapua.service.datastore.model.query.MetricInfoQuery; -import org.eclipse.kapua.service.storable.model.query.AbstractStorableQuery; -import org.eclipse.kapua.service.storable.model.query.SortField; -import org.eclipse.kapua.service.storable.model.query.StorableFetchStyle; - -import java.util.Collections; - -/** - * {@link MetricInfoQuery} implementation. - * - * @since 1.0.0 - */ -public class MetricInfoQueryImpl extends AbstractStorableQuery implements MetricInfoQuery { - - /** - * Constructor. - * - * @param scopeId The scope {@link KapuaId}. - * @since 1.0.0 - */ - public MetricInfoQueryImpl(KapuaId scopeId) { - super(scopeId); - - setSortFields(Collections.singletonList(SortField.ascending(MetricInfoSchema.METRIC_MTR_NAME_FULL))); - } - - @Override - public String[] getIncludes(StorableFetchStyle fetchStyle) { - return new String[]{"*"}; - } - - @Override - public String[] getExcludes(StorableFetchStyle fetchStyle) { - return new String[]{""}; - } - - @Override - public String[] getFields() { - return new String[]{MetricInfoField.SCOPE_ID.field(), - MetricInfoField.CLIENT_ID.field(), - MetricInfoField.CHANNEL.field(), - MetricInfoField.NAME_FULL.field(), - MetricInfoField.TYPE_FULL.field(), - MetricInfoField.TIMESTAMP_FULL.field(), - MetricInfoField.MESSAGE_ID_FULL.field()}; - } - -} diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/model/query/predicate/ChannelMatchPredicateImpl.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/model/query/predicate/ChannelMatchPredicateImpl.java index 63b601c516f..659503bfb6a 100644 --- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/model/query/predicate/ChannelMatchPredicateImpl.java +++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/model/query/predicate/ChannelMatchPredicateImpl.java @@ -12,8 +12,7 @@ *******************************************************************************/ package org.eclipse.kapua.service.datastore.internal.model.query.predicate; -import com.fasterxml.jackson.databind.node.ObjectNode; -import org.eclipse.kapua.service.datastore.internal.mediator.MessageField; +import org.eclipse.kapua.service.datastore.model.query.MessageField; import org.eclipse.kapua.service.datastore.model.query.predicate.ChannelMatchPredicate; import org.eclipse.kapua.service.storable.exception.MappingException; import org.eclipse.kapua.service.storable.model.query.StorableField; @@ -22,6 +21,8 @@ import org.eclipse.kapua.service.storable.model.query.predicate.StorablePredicateImpl; import org.eclipse.kapua.service.storable.model.utils.KeyValueEntry; +import com.fasterxml.jackson.databind.node.ObjectNode; + /** * {@link ChannelMatchPredicate} implementation. * @@ -35,7 +36,8 @@ public class ChannelMatchPredicateImpl extends StorablePredicateImpl implements /** * Constructor. * - * @param expression the channel expression (may use wildcard) + * @param expression + * the channel expression (may use wildcard) * @since 1.0.0 */ public ChannelMatchPredicateImpl(String expression) { @@ -45,8 +47,10 @@ public ChannelMatchPredicateImpl(String expression) { /** * Constructor. * - * @param field the field name - * @param expression the channel expression (may use wildcard) + * @param field + * the field name + * @param expression + * the channel expression (may use wildcard) * @since 1.0.0 */ public ChannelMatchPredicateImpl(StorableField field, String expression) { @@ -80,7 +84,7 @@ public MatchPredicate setExpression(String expression) { @Override public ObjectNode toSerializedMap() throws MappingException { - ObjectNode expressionNode = newObjectNode(new KeyValueEntry[]{new KeyValueEntry(getField().field(), getExpression())}); + ObjectNode expressionNode = newObjectNode(new KeyValueEntry[] { new KeyValueEntry(getField().field(), getExpression()) }); ObjectNode rootNode = newObjectNode(); rootNode.set(PredicateConstants.PREFIX_KEY, expressionNode); diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/model/query/predicate/MetricExistsPredicateImpl.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/model/query/predicate/MetricExistsPredicateImpl.java index 494688afb7f..312c1ccea04 100644 --- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/model/query/predicate/MetricExistsPredicateImpl.java +++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/model/query/predicate/MetricExistsPredicateImpl.java @@ -12,9 +12,8 @@ *******************************************************************************/ package org.eclipse.kapua.service.datastore.internal.model.query.predicate; -import com.fasterxml.jackson.databind.node.ObjectNode; import org.eclipse.kapua.service.datastore.internal.mediator.DatastoreUtils; -import org.eclipse.kapua.service.datastore.internal.mediator.MessageField; +import org.eclipse.kapua.service.datastore.model.query.MessageField; import org.eclipse.kapua.service.datastore.model.query.predicate.MetricExistsPredicate; import org.eclipse.kapua.service.storable.exception.MappingException; import org.eclipse.kapua.service.storable.model.query.predicate.ExistsPredicateImpl; @@ -22,6 +21,8 @@ import org.eclipse.kapua.service.storable.model.utils.KeyValueEntry; import org.eclipse.kapua.service.storable.model.utils.MappingUtils; +import com.fasterxml.jackson.databind.node.ObjectNode; + /** * {@link MetricExistsPredicate} implementation. * @@ -76,7 +77,7 @@ public ObjectNode toSerializedMap() throws MappingException { .append(datastoreUtils.getClientMetricFromAcronym(type.getSimpleName().toLowerCase())); } - ObjectNode termNode = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(PredicateConstants.FIELD_KEY, fieldNameSb.toString())}); + ObjectNode termNode = MappingUtils.newObjectNode(new KeyValueEntry[] { new KeyValueEntry(PredicateConstants.FIELD_KEY, fieldNameSb.toString()) }); ObjectNode rootNode = MappingUtils.newObjectNode(); rootNode.set(PredicateConstants.EXISTS_KEY, termNode); diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/model/query/predicate/MetricPredicateImpl.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/model/query/predicate/MetricPredicateImpl.java index 2583029fa81..a8e19816806 100644 --- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/model/query/predicate/MetricPredicateImpl.java +++ b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/model/query/predicate/MetricPredicateImpl.java @@ -12,15 +12,16 @@ *******************************************************************************/ package org.eclipse.kapua.service.datastore.internal.model.query.predicate; -import com.fasterxml.jackson.databind.node.ObjectNode; import org.eclipse.kapua.service.datastore.internal.mediator.DatastoreUtils; -import org.eclipse.kapua.service.datastore.internal.mediator.MessageField; +import org.eclipse.kapua.service.datastore.model.query.MessageField; import org.eclipse.kapua.service.datastore.model.query.predicate.MetricPredicate; import org.eclipse.kapua.service.storable.exception.MappingException; import org.eclipse.kapua.service.storable.model.query.predicate.PredicateConstants; import org.eclipse.kapua.service.storable.model.query.predicate.RangePredicateImpl; import org.eclipse.kapua.service.storable.model.utils.MappingUtils; +import com.fasterxml.jackson.databind.node.ObjectNode; + /** * {@link MetricPredicate} implementation * diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/schema/ChannelInfoSchema.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/schema/ChannelInfoSchema.java deleted file mode 100644 index c046ee7cd5a..00000000000 --- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/schema/ChannelInfoSchema.java +++ /dev/null @@ -1,110 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.datastore.internal.schema; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.node.ObjectNode; -import org.eclipse.kapua.service.datastore.internal.mediator.DatastoreUtils; -import org.eclipse.kapua.service.datastore.model.ChannelInfo; -import org.eclipse.kapua.service.elasticsearch.client.SchemaKeys; -import org.eclipse.kapua.service.storable.exception.MappingException; -import org.eclipse.kapua.service.storable.model.utils.KeyValueEntry; -import org.eclipse.kapua.service.storable.model.utils.MappingUtils; - -/** - * {@link ChannelInfo} schema definition. - * - * @since 1.0.0 - */ -public class ChannelInfoSchema { - - /** - * @since 1.0.0 - */ - private ChannelInfoSchema() { - } - - /** - * Channel information schema name - * - * @since 1.0.0 - */ - public static final String CHANNEL_TYPE_NAME = "channel"; - /** - * Channel information - channel - * - * @since 1.0.0 - */ - public static final String CHANNEL_NAME = "channel"; - /** - * Channel information - client identifier - * - * @since 1.0.0 - */ - public static final String CHANNEL_CLIENT_ID = "client_id"; - /** - * Channel information - scope id - * - * @since 1.0.0 - */ - public static final String CHANNEL_SCOPE_ID = "scope_id"; - /** - * Channel information - message timestamp (of the first message published in this channel) - * - * @since 1.0.0 - */ - public static final String CHANNEL_TIMESTAMP = "timestamp"; - /** - * Channel information - message identifier (of the first message published in this channel) - * - * @since 1.0.0 - */ - public static final String CHANNEL_MESSAGE_ID = "message_id"; - - /** - * Create and return the Json representation of the channel info schema - * - * @return - * @throws MappingException - * @since 1.0.0 - */ - public static JsonNode getChannelTypeSchema() throws MappingException { - ObjectNode channelNode = MappingUtils.newObjectNode(); - - { - ObjectNode sourceChannel = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_ENABLED, true)}); - channelNode.set(SchemaKeys.KEY_SOURCE, sourceChannel); - - ObjectNode propertiesNode = MappingUtils.newObjectNode(); - { - ObjectNode channelScopeId = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE)}); - propertiesNode.set(CHANNEL_SCOPE_ID, channelScopeId); - - ObjectNode channelClientId = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE)}); - propertiesNode.set(CHANNEL_CLIENT_ID, channelClientId); - - ObjectNode channelName = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE)}); - propertiesNode.set(CHANNEL_NAME, channelName); - - ObjectNode channelTimestamp = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_DATE), new KeyValueEntry(SchemaKeys.KEY_FORMAT, DatastoreUtils.DATASTORE_DATE_FORMAT)}); - propertiesNode.set(CHANNEL_TIMESTAMP, channelTimestamp); - - ObjectNode channelMessageId = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE)}); - propertiesNode.set(CHANNEL_MESSAGE_ID, channelMessageId); - } - channelNode.set(SchemaKeys.FIELD_NAME_PROPERTIES, propertiesNode); - } - return channelNode; - } - -} diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/schema/ClientInfoSchema.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/schema/ClientInfoSchema.java deleted file mode 100644 index 90cbb8427f0..00000000000 --- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/schema/ClientInfoSchema.java +++ /dev/null @@ -1,106 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.datastore.internal.schema; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.node.ObjectNode; -import org.eclipse.kapua.service.datastore.internal.mediator.DatastoreUtils; -import org.eclipse.kapua.service.datastore.model.ClientInfo; -import org.eclipse.kapua.service.elasticsearch.client.SchemaKeys; -import org.eclipse.kapua.service.storable.exception.MappingException; -import org.eclipse.kapua.service.storable.model.utils.KeyValueEntry; -import org.eclipse.kapua.service.storable.model.utils.MappingUtils; - -/** - * {@link ClientInfo} schema definition. - * - * @since 1.0.0 - */ -public class ClientInfoSchema { - - /** - * @since 1.0.0 - */ - private ClientInfoSchema() { - } - - /** - * Client information schema name. - * - * @since 1.0.0 - */ - public static final String CLIENT_TYPE_NAME = "client"; - - /** - * Client information - client identifier - * - * @since 1.0.0 - */ - public static final String CLIENT_ID = "client_id"; - - /** - * Client information - scope id - * - * @since 1.0.0 - */ - public static final String CLIENT_SCOPE_ID = "scope_id"; - - /** - * Client information - message timestamp (of the first message published in this channel) - * - * @since 1.0.0 - */ - public static final String CLIENT_TIMESTAMP = "timestamp"; - - /** - * Client information - message identifier (of the first message published in this channel) - * - * @since 1.0.0 - */ - public static final String CLIENT_MESSAGE_ID = "message_id"; - - /** - * Create and return the Json representation of the client info schema - * - * @return - * @throws MappingException - * @since 1.0.0 - */ - public static JsonNode getClientTypeSchema() throws MappingException { - - ObjectNode clientNode = MappingUtils.newObjectNode(); - { - ObjectNode sourceClient = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_ENABLED, true)}); - clientNode.set(SchemaKeys.KEY_SOURCE, sourceClient); - - ObjectNode propertiesNode = MappingUtils.newObjectNode(); - { - ObjectNode clientId = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE)}); - propertiesNode.set(CLIENT_ID, clientId); - - ObjectNode clientTimestamp = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_DATE), new KeyValueEntry(SchemaKeys.KEY_FORMAT, DatastoreUtils.DATASTORE_DATE_FORMAT)}); - propertiesNode.set(CLIENT_TIMESTAMP, clientTimestamp); - - ObjectNode clientScopeId = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE)}); - propertiesNode.set(CLIENT_SCOPE_ID, clientScopeId); - - ObjectNode clientMessageId = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE)}); - propertiesNode.set(CLIENT_MESSAGE_ID, clientMessageId); - } - clientNode.set(SchemaKeys.FIELD_NAME_PROPERTIES, propertiesNode); - } - - return clientNode; - } - -} diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/schema/MessageSchema.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/schema/MessageSchema.java deleted file mode 100644 index 251922a4e34..00000000000 --- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/schema/MessageSchema.java +++ /dev/null @@ -1,361 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.datastore.internal.schema; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.node.ObjectNode; -import org.eclipse.kapua.message.Message; -import org.eclipse.kapua.service.datastore.internal.mediator.DatastoreUtils; -import org.eclipse.kapua.service.elasticsearch.client.SchemaKeys; -import org.eclipse.kapua.service.storable.exception.MappingException; -import org.eclipse.kapua.service.storable.model.utils.KeyValueEntry; -import org.eclipse.kapua.service.storable.model.utils.MappingUtils; - -/** - * {@link Message} schema definition. - * - * @since 1.0.0 - */ -public class MessageSchema { - - /** - * @since 1.0.0 - */ - private MessageSchema() { - } - - /** - * Message schema name - * - * @since 1.0.0 - */ - public static final String MESSAGE_TYPE_NAME = "message"; - - /** - * Message id - * - * @since 1.0.0 - */ - public static final String MESSAGE_ID = "message_id"; - - /** - * Message timestamp - * - * @since 1.0.0 - */ - public static final String MESSAGE_TIMESTAMP = "timestamp"; - - /** - * Message received on timestamp - * - * @since 1.0.0 - */ - public static final String MESSAGE_RECEIVED_ON = "received_on"; - - /** - * Message received by address - * - * @since 1.0.0 - */ - public static final String MESSAGE_IP_ADDRESS = "ip_address"; - - /** - * Message scope id - * - * @since 1.0.0 - */ - public static final String MESSAGE_SCOPE_ID = "scope_id"; - - /** - * Message device identifier - * - * @since 1.0.0 - */ - public static final String MESSAGE_DEVICE_ID = "device_id"; - - /** - * Message client identifier - * - * @since 1.0.0 - */ - public static final String MESSAGE_CLIENT_ID = "client_id"; - - /** - * Message channel - * - * @since 1.0.0 - */ - public static final String MESSAGE_CHANNEL = "channel"; - - /** - * Message channel parts - * - * @since 1.0.0 - */ - public static final String MESSAGE_CHANNEL_PARTS = "channel_parts"; - - /** - * Message captured on timestamp - * - * @since 1.0.0 - */ - public static final String MESSAGE_CAPTURED_ON = "captured_on"; - - /** - * Message sent on timestamp - * - * @since 1.0.0 - */ - public static final String MESSAGE_SENT_ON = "sent_on"; - - /** - * Message position - (composed object) - * - * @since 1.0.0 - */ - public static final String MESSAGE_POSITION = "position"; - - /** - * Message position - location (field name relative to the position object) - * - * @since 1.0.0 - */ - public static final String MESSAGE_POS_LOCATION = "location"; - - /** - * Message position - location (full field name) - * - * @since 1.0.0 - */ - public static final String MESSAGE_POS_LOCATION_FULL = "position.location"; - - /** - * Message position - altitude (field name relative to the position object) - * - * @since 1.0.0 - */ - public static final String MESSAGE_POS_ALT = "alt"; - - /** - * Message position - altitude (full field name) - * - * @since 1.0.0 - */ - public static final String MESSAGE_POS_ALT_FULL = "position.alt"; - - /** - * Message position - precision (field name relative to the position object) - * - * @since 1.0.0 - */ - public static final String MESSAGE_POS_PRECISION = "precision"; - - /** - * Message position - precision (full field name) - * - * @since 1.0.0 - */ - public static final String MESSAGE_POS_PRECISION_FULL = "position.precision"; - - /** - * Message position - heading (field name relative to the position object) - * - * @since 1.0.0 - */ - public static final String MESSAGE_POS_HEADING = "heading"; - - /** - * Message position - heading (full field name) - * - * @since 1.0.0 - */ - public static final String MESSAGE_POS_HEADING_FULL = "position.heading"; - - /** - * Message position - speed (field name relative to the position object) - * - * @since 1.0.0 - */ - public static final String MESSAGE_POS_SPEED = "speed"; - - /** - * Message position - speed (full field name) - * - * @since 1.0.0 - */ - public static final String MESSAGE_POS_SPEED_FULL = "position.speed"; - - /** - * Message position - timestamp (field name relative to the position object) - * - * @since 1.0.0 - */ - public static final String MESSAGE_POS_TIMESTAMP = "timestamp"; - - /** - * Message position - timestamp (full field name) - * - * @since 1.0.0 - */ - public static final String MESSAGE_POS_TIMESTAMP_FULL = "position.timestamp"; - - /** - * Message position - satellites (field name relative to the position object) - * - * @since 1.0.0 - */ - public static final String MESSAGE_POS_SATELLITES = "satellites"; - - /** - * Message position - satellites (full field name) - * - * @since 1.0.0 - */ - public static final String MESSAGE_POS_SATELLITES_FULL = "position.satellites"; - - /** - * Message position - status (field name relative to the position object) - * - * @since 1.0.0 - */ - public static final String MESSAGE_POS_STATUS = "status"; - - /** - * Message position - status (full field name) - * - * @since 1.0.0 - */ - public static final String MESSAGE_POS_STATUS_FULL = "position.status"; - - /** - * Message metrics - * - * @since 1.0.0 - */ - public static final String MESSAGE_METRICS = "metrics"; - - /** - * Message body - * - * @since 1.0.0 - */ - public static final String MESSAGE_BODY = "body"; - - // position internal fields - /** - * Position latitude inner field - * - * @since 1.0.0 - */ - public static final String MESSAGE_POSITION_LATITUDE = "lat"; - - /** - * Position longitude inner field - * - * @since 1.0.0 - */ - public static final String MESSAGE_POSITION_LONGITUDE = "lon"; - - /** - * Create and return the Json representation of the message schema - * - * @return - * @throws MappingException - * @since 1.0.0 - */ - public static JsonNode getMessageTypeSchema() throws MappingException { - ObjectNode messageNode = MappingUtils.newObjectNode(); - { - ObjectNode sourceMessage = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_ENABLED, true)}); - messageNode.set(SchemaKeys.KEY_SOURCE, sourceMessage); - - ObjectNode propertiesNode = MappingUtils.newObjectNode(); - { - ObjectNode messageId = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE)}); - propertiesNode.set(MESSAGE_ID, messageId); - - ObjectNode messageTimestamp = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_DATE), new KeyValueEntry(SchemaKeys.KEY_FORMAT, DatastoreUtils.DATASTORE_DATE_FORMAT)}); - propertiesNode.set(MESSAGE_TIMESTAMP, messageTimestamp); - - ObjectNode messageReceivedOn = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_DATE), new KeyValueEntry(SchemaKeys.KEY_FORMAT, DatastoreUtils.DATASTORE_DATE_FORMAT)}); - propertiesNode.set(MESSAGE_RECEIVED_ON, messageReceivedOn); - - ObjectNode messageIp = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_IP)}); - propertiesNode.set(MESSAGE_IP_ADDRESS, messageIp); - - ObjectNode messageScopeId = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE)}); - propertiesNode.set(MESSAGE_SCOPE_ID, messageScopeId); - - ObjectNode messageDeviceId = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE)}); - propertiesNode.set(MESSAGE_DEVICE_ID, messageDeviceId); - - ObjectNode messageClientId = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE)}); - propertiesNode.set(MESSAGE_CLIENT_ID, messageClientId); - - ObjectNode messageChannel = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE)}); - propertiesNode.set(MESSAGE_CHANNEL, messageChannel); - - ObjectNode messageCapturedOn = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_DATE), new KeyValueEntry(SchemaKeys.KEY_FORMAT, DatastoreUtils.DATASTORE_DATE_FORMAT)}); - propertiesNode.set(MESSAGE_CAPTURED_ON, messageCapturedOn); - - ObjectNode messageSentOn = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_DATE), new KeyValueEntry(SchemaKeys.KEY_FORMAT, DatastoreUtils.DATASTORE_DATE_FORMAT)}); - propertiesNode.set(MESSAGE_SENT_ON, messageSentOn); - - ObjectNode positionNode = MappingUtils.newObjectNode( - new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_OBJECT), new KeyValueEntry(SchemaKeys.KEY_ENABLED, true), - new KeyValueEntry(SchemaKeys.KEY_DYNAMIC, false)}); - - ObjectNode positionPropertiesNode = MappingUtils.newObjectNode(); - { - ObjectNode messagePositionPropLocation = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_GEO_POINT)}); - positionPropertiesNode.set(MESSAGE_POS_LOCATION, messagePositionPropLocation); - - ObjectNode messagePositionPropAlt = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_DOUBLE)}); - positionPropertiesNode.set(MESSAGE_POS_ALT, messagePositionPropAlt); - - ObjectNode messagePositionPropPrec = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_DOUBLE)}); - positionPropertiesNode.set(MESSAGE_POS_PRECISION, messagePositionPropPrec); - - ObjectNode messagePositionPropHead = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_DOUBLE)}); - positionPropertiesNode.set(MESSAGE_POS_HEADING, messagePositionPropHead); - - ObjectNode messagePositionPropSpeed = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_DOUBLE)}); - positionPropertiesNode.set(MESSAGE_POS_SPEED, messagePositionPropSpeed); - - ObjectNode messagePositionPropTime = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_DATE), new KeyValueEntry(SchemaKeys.KEY_FORMAT, DatastoreUtils.DATASTORE_DATE_FORMAT)}); - positionPropertiesNode.set(MESSAGE_POS_TIMESTAMP, messagePositionPropTime); - - ObjectNode messagePositionPropSat = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_INTEGER)}); - positionPropertiesNode.set(MESSAGE_POS_SATELLITES, messagePositionPropSat); - - ObjectNode messagePositionPropStat = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_INTEGER)}); - positionPropertiesNode.set(MESSAGE_POS_STATUS, messagePositionPropStat); - } - positionNode.set(SchemaKeys.FIELD_NAME_PROPERTIES, positionPropertiesNode); - - propertiesNode.set(SchemaKeys.FIELD_NAME_POSITION, positionNode); - } - messageNode.set(SchemaKeys.FIELD_NAME_PROPERTIES, propertiesNode); - - ObjectNode messageMetrics = MappingUtils.newObjectNode( - new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_OBJECT), new KeyValueEntry(SchemaKeys.KEY_ENABLED, true), - new KeyValueEntry(SchemaKeys.KEY_DYNAMIC, true)}); - propertiesNode.set(MESSAGE_METRICS, messageMetrics); - - ObjectNode messageBody = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_BINARY), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_FALSE)}); - propertiesNode.set(MESSAGE_BODY, messageBody); - } - return messageNode; - } - -} diff --git a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/schema/MetricInfoSchema.java b/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/schema/MetricInfoSchema.java deleted file mode 100644 index cc0933583e1..00000000000 --- a/service/datastore/internal/src/main/java/org/eclipse/kapua/service/datastore/internal/schema/MetricInfoSchema.java +++ /dev/null @@ -1,196 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.datastore.internal.schema; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.node.ObjectNode; -import org.eclipse.kapua.service.datastore.internal.mediator.DatastoreUtils; -import org.eclipse.kapua.service.datastore.model.MetricInfo; -import org.eclipse.kapua.service.elasticsearch.client.SchemaKeys; -import org.eclipse.kapua.service.storable.exception.MappingException; -import org.eclipse.kapua.service.storable.model.utils.KeyValueEntry; -import org.eclipse.kapua.service.storable.model.utils.MappingUtils; - -/** - * {@link MetricInfo} schema definition. - * - * @since 1.0.0 - */ -public class MetricInfoSchema { - - /** - * @since 1.0.0 - */ - private MetricInfoSchema() { - } - - /** - * Metric information schema name - * - * @since 1.0.0 - */ - public static final String METRIC_TYPE_NAME = "metric"; - - /** - * Metric information - channel - * - * @since 1.0.0 - */ - public static final String METRIC_CHANNEL = "channel"; - - /** - * Metric information - client identifier - * - * @since 1.0.0 - */ - public static final String METRIC_CLIENT_ID = "client_id"; - - /** - * Metric information - scope id - * - * @since 1.0.0 - */ - public static final String METRIC_SCOPE_ID = "scope_id"; - - /** - * Metric information - metric map prefix - * - * @since 1.0.0 - */ - public static final String METRIC_MTR = "metric"; - - /** - * Metric information - name - * - * @since 1.0.0 - */ - public static final String METRIC_MTR_NAME = "name"; - - /** - * Metric information - full name (so with the metric type suffix) - * - * @since 1.0.0 - */ - public static final String METRIC_MTR_NAME_FULL = "metric.name"; - - /** - * Metric information - type - * - * @since 1.0.0 - */ - public static final String METRIC_MTR_TYPE = "type"; - - /** - * Metric information - full type (so with the metric type suffix) - * - * @since 1.0.0 - */ - public static final String METRIC_MTR_TYPE_FULL = "metric.type"; - - /** - * Metric information - value - * - * @since 1.0.0 - */ - public static final String METRIC_MTR_VALUE = "value"; - - /** - * Metric information - full value (so with the metric type suffix) - * - * @since 1.0.0 - */ - public static final String METRIC_MTR_VALUE_FULL = "metric.value"; - - /** - * Metric information - message timestamp (of the first message published in this channel) - * - * @since 1.0.0 - */ - public static final String METRIC_MTR_TIMESTAMP = "timestamp"; - - /** - * Metric information - message timestamp (of the first message published in this channel, with the metric type suffix) - * - * @since 1.0.0 - */ - public static final String METRIC_MTR_TIMESTAMP_FULL = "metric.timestamp"; - - /** - * Metric information - message identifier (of the first message published in this channel) - * - * @since 1.0.0 - */ - public static final String METRIC_MTR_MSG_ID = "message_id"; - - /** - * Metric information - full message identifier (of the first message published in this channel, with the metric type suffix) - * - * @since 1.0.0 - */ - public static final String METRIC_MTR_MSG_ID_FULL = "metric.message_id"; - - /** - * Create and return the Json representation of the metric info schema - * - * @return - * @throws MappingException - * @since 1.0.0 - */ - public static JsonNode getMetricTypeSchema() throws MappingException { - - ObjectNode metricNode = MappingUtils.newObjectNode(); - - ObjectNode sourceMetric = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_ENABLED, true)}); - metricNode.set(SchemaKeys.KEY_SOURCE, sourceMetric); - - ObjectNode propertiesNode = MappingUtils.newObjectNode(); - { - ObjectNode metricAccount = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE)}); - propertiesNode.set(METRIC_SCOPE_ID, metricAccount); - - ObjectNode metricClientId = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE)}); - propertiesNode.set(METRIC_CLIENT_ID, metricClientId); - - ObjectNode metricChannel = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE)}); - propertiesNode.set(METRIC_CHANNEL, metricChannel); - - ObjectNode metricMtrNode = MappingUtils.newObjectNode( - new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_OBJECT), new KeyValueEntry(SchemaKeys.KEY_ENABLED, true), - new KeyValueEntry(SchemaKeys.KEY_DYNAMIC, false)}); - ObjectNode metricMtrPropertiesNode = MappingUtils.newObjectNode(); - { - ObjectNode metricMtrNameNode = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE)}); - metricMtrPropertiesNode.set(METRIC_MTR_NAME, metricMtrNameNode); - - ObjectNode metricMtrTypeNode = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE)}); - metricMtrPropertiesNode.set(METRIC_MTR_TYPE, metricMtrTypeNode); - - ObjectNode metricMtrValueNode = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE)}); - metricMtrPropertiesNode.set(METRIC_MTR_VALUE, metricMtrValueNode); - - ObjectNode metricMtrTimestampNode = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_DATE), new KeyValueEntry(SchemaKeys.KEY_FORMAT, DatastoreUtils.DATASTORE_DATE_FORMAT)}); - metricMtrPropertiesNode.set(METRIC_MTR_TIMESTAMP, metricMtrTimestampNode); - - ObjectNode metricMtrMsgIdNode = MappingUtils.newObjectNode(new KeyValueEntry[]{new KeyValueEntry(SchemaKeys.KEY_TYPE, SchemaKeys.TYPE_KEYWORD), new KeyValueEntry(SchemaKeys.KEY_INDEX, SchemaKeys.VALUE_TRUE)}); - metricMtrPropertiesNode.set(METRIC_MTR_MSG_ID, metricMtrMsgIdNode); - } - metricMtrNode.set(SchemaKeys.FIELD_NAME_PROPERTIES, metricMtrPropertiesNode); - - propertiesNode.set(METRIC_MTR, metricMtrNode); - } - metricNode.set(SchemaKeys.FIELD_NAME_PROPERTIES, propertiesNode); - - return metricNode; - } - -} diff --git a/service/datastore/pom.xml b/service/datastore/pom.xml index c5778e1498c..5ffe3440301 100644 --- a/service/datastore/pom.xml +++ b/service/datastore/pom.xml @@ -19,7 +19,7 @@ org.eclipse.kapua kapua-service - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-datastore diff --git a/service/datastore/test-steps/pom.xml b/service/datastore/test-steps/pom.xml index 309183a7add..83befb754f8 100644 --- a/service/datastore/test-steps/pom.xml +++ b/service/datastore/test-steps/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-datastore - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-datastore-test-steps diff --git a/service/datastore/test-steps/src/main/java/org/eclipse/kapua/service/datastore/steps/DatastoreSteps.java b/service/datastore/test-steps/src/main/java/org/eclipse/kapua/service/datastore/steps/DatastoreSteps.java index dbcef294c9a..89e582e535d 100755 --- a/service/datastore/test-steps/src/main/java/org/eclipse/kapua/service/datastore/steps/DatastoreSteps.java +++ b/service/datastore/test-steps/src/main/java/org/eclipse/kapua/service/datastore/steps/DatastoreSteps.java @@ -12,15 +12,27 @@ *******************************************************************************/ package org.eclipse.kapua.service.datastore.steps; -import com.google.inject.Singleton; -import io.cucumber.java.After; -import io.cucumber.java.Before; -import io.cucumber.java.DataTableType; -import io.cucumber.java.Scenario; -import io.cucumber.java.en.And; -import io.cucumber.java.en.Given; -import io.cucumber.java.en.Then; -import io.cucumber.java.en.When; +import java.io.IOException; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Calendar; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TimeZone; +import java.util.function.Function; +import java.util.stream.Collectors; + +import javax.inject.Inject; + import org.apache.commons.lang.ArrayUtils; import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.commons.util.KapuaDateUtils; @@ -55,20 +67,11 @@ import org.eclipse.kapua.service.datastore.internal.DatastoreCacheManager; import org.eclipse.kapua.service.datastore.internal.MessageStoreFacade; import org.eclipse.kapua.service.datastore.internal.MetricEntry; -import org.eclipse.kapua.service.datastore.internal.mediator.ChannelInfoField; -import org.eclipse.kapua.service.datastore.internal.mediator.ClientInfoField; import org.eclipse.kapua.service.datastore.internal.mediator.DatastoreChannel; import org.eclipse.kapua.service.datastore.internal.mediator.DatastoreUtils; -import org.eclipse.kapua.service.datastore.internal.mediator.MessageField; import org.eclipse.kapua.service.datastore.internal.mediator.MessageStoreConfiguration; -import org.eclipse.kapua.service.datastore.internal.mediator.MetricInfoField; import org.eclipse.kapua.service.datastore.internal.model.DataIndexBy; import org.eclipse.kapua.service.datastore.internal.model.metric.MetricsIndexBy; -import org.eclipse.kapua.service.datastore.internal.model.query.MessageQueryImpl; -import org.eclipse.kapua.service.datastore.internal.schema.ChannelInfoSchema; -import org.eclipse.kapua.service.datastore.internal.schema.ClientInfoSchema; -import org.eclipse.kapua.service.datastore.internal.schema.MessageSchema; -import org.eclipse.kapua.service.datastore.internal.schema.MetricInfoSchema; import org.eclipse.kapua.service.datastore.internal.setting.DatastoreSettingsKey; import org.eclipse.kapua.service.datastore.model.ChannelInfo; import org.eclipse.kapua.service.datastore.model.ChannelInfoListResult; @@ -78,10 +81,18 @@ import org.eclipse.kapua.service.datastore.model.MessageListResult; import org.eclipse.kapua.service.datastore.model.MetricInfo; import org.eclipse.kapua.service.datastore.model.MetricInfoListResult; +import org.eclipse.kapua.service.datastore.model.query.ChannelInfoField; import org.eclipse.kapua.service.datastore.model.query.ChannelInfoQuery; +import org.eclipse.kapua.service.datastore.model.query.ChannelInfoSchema; +import org.eclipse.kapua.service.datastore.model.query.ClientInfoField; import org.eclipse.kapua.service.datastore.model.query.ClientInfoQuery; +import org.eclipse.kapua.service.datastore.model.query.ClientInfoSchema; +import org.eclipse.kapua.service.datastore.model.query.MessageField; import org.eclipse.kapua.service.datastore.model.query.MessageQuery; +import org.eclipse.kapua.service.datastore.model.query.MessageSchema; +import org.eclipse.kapua.service.datastore.model.query.MetricInfoField; import org.eclipse.kapua.service.datastore.model.query.MetricInfoQuery; +import org.eclipse.kapua.service.datastore.model.query.MetricInfoSchema; import org.eclipse.kapua.service.datastore.model.query.predicate.ChannelMatchPredicate; import org.eclipse.kapua.service.datastore.model.query.predicate.DatastorePredicateFactory; import org.eclipse.kapua.service.device.registry.Device; @@ -108,25 +119,16 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.inject.Inject; -import java.io.IOException; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.time.Instant; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Calendar; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TimeZone; -import java.util.function.Function; -import java.util.stream.Collectors; +import com.google.inject.Singleton; + +import io.cucumber.java.After; +import io.cucumber.java.Before; +import io.cucumber.java.DataTableType; +import io.cucumber.java.Scenario; +import io.cucumber.java.en.And; +import io.cucumber.java.en.Given; +import io.cucumber.java.en.Then; +import io.cucumber.java.en.When; @Singleton public class DatastoreSteps extends TestBase { @@ -167,26 +169,26 @@ public void iSetTheFollowingMetricsFromTheList(String lstKey, List me tmpMsg.setPayload(dataMessageFactory.newKapuaDataPayload()); switch (tmpMet.getType().trim().toLowerCase()) { - case "string": { - tmpMsg.getPayload().getMetrics().put(tmpMet.getMetric(), tmpMet.getValue()); - break; - } - case "int": { - tmpMsg.getPayload().getMetrics().put(tmpMet.getMetric(), Integer.valueOf(tmpMet.getValue())); - break; - } - case DOUBLE: { - tmpMsg.getPayload().getMetrics().put(tmpMet.getMetric(), Double.valueOf(tmpMet.getValue())); - break; - } - case "bool": { - tmpMsg.getPayload().getMetrics().put(tmpMet.getMetric(), Boolean.valueOf(tmpMet.getValue().trim().toUpperCase())); - break; - } - default: { - Assert.fail(String.format("Unknown metric type [%s]", tmpMet.getType())); - break; - } + case "string": { + tmpMsg.getPayload().getMetrics().put(tmpMet.getMetric(), tmpMet.getValue()); + break; + } + case "int": { + tmpMsg.getPayload().getMetrics().put(tmpMet.getMetric(), Integer.valueOf(tmpMet.getValue())); + break; + } + case DOUBLE: { + tmpMsg.getPayload().getMetrics().put(tmpMet.getMetric(), Double.valueOf(tmpMet.getValue())); + break; + } + case "bool": { + tmpMsg.getPayload().getMetrics().put(tmpMet.getMetric(), Boolean.valueOf(tmpMet.getValue().trim().toUpperCase())); + break; + } + default: { + Assert.fail(String.format("Unknown metric type [%s]", tmpMet.getType())); + break; + } } } } @@ -379,7 +381,7 @@ public void publishMetric(String topic, List metrics) { @Then("I expect the number of messages for this device to be {long}") public void expectNumberOfMessages(long numberOfMessages) throws Exception { session.withLogin(() -> With.withUserAccount(currentDevice.getAccountName(), account -> { - MessageQuery query = messageStoreFactory.newQuery(account.getId()); + MessageQuery query = new MessageQuery(account.getId()); query.setPredicate(datastorePredicateFactory.newTermPredicate(MessageField.CLIENT_ID, currentDevice.getClientId())); query.setAskTotalCount(true); query.setLimit((int) numberOfMessages); @@ -394,7 +396,7 @@ public void expectNumberOfMessages(long numberOfMessages) throws Exception { @Then("I delete the messages for this device") public void deleteMessages() throws Exception { session.withLogin(() -> With.withUserAccount(currentDevice.getAccountName(), account -> { - MessageQuery query = messageStoreFactory.newQuery(account.getId()); + MessageQuery query = new MessageQuery(account.getId()); query.setPredicate(datastorePredicateFactory.newTermPredicate(MessageField.CLIENT_ID, currentDevice.getClientId())); query.setAskTotalCount(true); query.setLimit(100); @@ -405,7 +407,7 @@ public void deleteMessages() throws Exception { @Then("I expect the latest captured message on channel {string} to have the metrics") public void testMessageData(String topic, List expectedMetrics) throws Exception { session.withLogin(() -> With.withUserAccount(currentDevice.getAccountName(), account -> { - MessageQuery query = messageStoreFactory.newQuery(account.getId()); + MessageQuery query = new MessageQuery(account.getId()); AndPredicate and = datastorePredicateFactory.newAndPredicate(); and.getPredicates().add(datastorePredicateFactory.newTermPredicate(MessageField.CLIENT_ID, currentDevice.getClientId())); and.getPredicates().add(datastorePredicateFactory.newTermPredicate(MessageField.CHANNEL, topic)); @@ -518,26 +520,26 @@ public void appendMetricsToSelectedMessage(int idx, String lstKey, List toData(List metrics) { final String type = entry.getType(); switch (type.toUpperCase()) { - case "STRING": - data.put(key, stringValue); - break; - case "INT32": - data.put(key, Integer.valueOf(stringValue)); - break; - case "INT64": - data.put(key, Long.valueOf(stringValue)); - break; - case "DOUBLE": - data.put(key, Double.parseDouble(stringValue)); - break; - case "BOOLEAN": - data.put(key, Boolean.valueOf(stringValue)); - break; - default: - throw new IllegalArgumentException(String.format("Unknown type: %s", type)); + case "STRING": + data.put(key, stringValue); + break; + case "INT32": + data.put(key, Integer.valueOf(stringValue)); + break; + case "INT64": + data.put(key, Long.valueOf(stringValue)); + break; + case "DOUBLE": + data.put(key, Double.parseDouble(stringValue)); + break; + case "BOOLEAN": + data.put(key, Boolean.valueOf(stringValue)); + break; + default: + throw new IllegalArgumentException(String.format("Unknown type: %s", type)); } } return data; @@ -2156,8 +2159,7 @@ private static T getValue(Object object, String field, Class clazz) { } /** - * Return the suffix field name to compose (in a different method) the getter name. - * It removes the _ and append the remaining part capitalizing the first letter (if capitalizeFirstLetter = true) + * Return the suffix field name to compose (in a different method) the getter name. It removes the _ and append the remaining part capitalizing the first letter (if capitalizeFirstLetter = true) * * @param field * @return @@ -2251,7 +2253,8 @@ private static Field getField(Class objectClass, final String field) { * @param storageEnabled * @throws KapuaException */ - private void updateConfiguration(MessageStoreService messageStoreService, KapuaId scopeId, KapuaId parentId, DataIndexBy dataIndexBy, MetricsIndexBy metricsIndexBy, int dataTTL, boolean storageEnabled) + private void updateConfiguration(MessageStoreService messageStoreService, KapuaId scopeId, KapuaId parentId, DataIndexBy dataIndexBy, MetricsIndexBy metricsIndexBy, int dataTTL, + boolean storageEnabled) throws KapuaException { Map config = messageStoreService.getConfigValues(scopeId); @@ -2285,13 +2288,15 @@ private void theListHaveLimitExceedValue(Class /** * Creating query for data messages with reasonable defaults. * - * @param scopeId scope - * @param limit limit results + * @param scopeId + * scope + * @param limit + * limit results * @return query */ public MessageQuery createBaseMessageQuery(KapuaId scopeId, int limit) { - MessageQuery query = new MessageQueryImpl(scopeId); + MessageQuery query = new MessageQuery(scopeId); query.setAskTotalCount(true); query.setFetchStyle(StorableFetchStyle.SOURCE_FULL); query.setLimit(limit); @@ -2307,14 +2312,17 @@ public MessageQuery createBaseMessageQuery(KapuaId scopeId, int limit) { /** * Creating query for data messages with reasonable defaults and user specified ordering. * - * @param scopeId scope - * @param limit limit results - * @param order the required result ordering + * @param scopeId + * scope + * @param limit + * limit results + * @param order + * the required result ordering * @return query */ public MessageQuery createBaseMessageQuery(KapuaId scopeId, int limit, List order) { - MessageQuery query = new MessageQueryImpl(scopeId); + MessageQuery query = new MessageQuery(scopeId); query.setAskTotalCount(true); query.setFetchStyle(StorableFetchStyle.SOURCE_FULL); query.setLimit(limit); @@ -2327,13 +2335,15 @@ public MessageQuery createBaseMessageQuery(KapuaId scopeId, int limit, List org.eclipse.kapua kapua-datastore - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-datastore-test diff --git a/service/device/api/pom.xml b/service/device/api/pom.xml index c31b1606eca..2c19623ad45 100644 --- a/service/device/api/pom.xml +++ b/service/device/api/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-device - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-device-api diff --git a/service/device/authentication/pom.xml b/service/device/authentication/pom.xml index 994416661b0..4ff7f1a8e14 100644 --- a/service/device/authentication/pom.xml +++ b/service/device/authentication/pom.xml @@ -19,7 +19,7 @@ org.eclipse.kapua kapua-device - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-device-authentication diff --git a/service/device/authentication/src/main/java/org/eclipse/kapua/service/device/authentication/DeviceAuthenticationModule.java b/service/device/authentication/src/main/java/org/eclipse/kapua/service/device/authentication/DeviceAuthenticationModule.java index eb5d917b57f..af6f5e92931 100644 --- a/service/device/authentication/src/main/java/org/eclipse/kapua/service/device/authentication/DeviceAuthenticationModule.java +++ b/service/device/authentication/src/main/java/org/eclipse/kapua/service/device/authentication/DeviceAuthenticationModule.java @@ -12,12 +12,12 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.authentication; -import com.google.inject.multibindings.ProvidesIntoMap; -import com.google.inject.multibindings.StringMapKey; import org.eclipse.kapua.commons.core.AbstractKapuaModule; -import org.eclipse.kapua.service.authentication.CredentialsFactory; import org.eclipse.kapua.service.device.authentication.api.DeviceConnectionCredentialAdapter; +import com.google.inject.multibindings.ProvidesIntoMap; +import com.google.inject.multibindings.StringMapKey; + /** * kapua-device-authentication {@link AbstractKapuaModule}. * @@ -31,7 +31,7 @@ protected void configureModule() { @ProvidesIntoMap @StringMapKey("USER_PASS") - public DeviceConnectionCredentialAdapter userPassDeviceConnectionAuthHandler(CredentialsFactory credentialFactory) { - return new UserPassDeviceConnectionCredentialAdapter(credentialFactory); + public DeviceConnectionCredentialAdapter userPassDeviceConnectionAuthHandler() { + return new UserPassDeviceConnectionCredentialAdapter(); } } diff --git a/service/device/authentication/src/main/java/org/eclipse/kapua/service/device/authentication/UserPassDeviceConnectionCredentialAdapter.java b/service/device/authentication/src/main/java/org/eclipse/kapua/service/device/authentication/UserPassDeviceConnectionCredentialAdapter.java index 3297c6857a7..abaafcdd7cc 100644 --- a/service/device/authentication/src/main/java/org/eclipse/kapua/service/device/authentication/UserPassDeviceConnectionCredentialAdapter.java +++ b/service/device/authentication/src/main/java/org/eclipse/kapua/service/device/authentication/UserPassDeviceConnectionCredentialAdapter.java @@ -13,13 +13,10 @@ package org.eclipse.kapua.service.device.authentication; import org.eclipse.kapua.client.security.bean.AuthRequest; -import org.eclipse.kapua.service.authentication.CredentialsFactory; import org.eclipse.kapua.service.authentication.LoginCredentials; import org.eclipse.kapua.service.authentication.UsernamePasswordCredentials; import org.eclipse.kapua.service.device.authentication.api.DeviceConnectionCredentialAdapter; -import javax.inject.Inject; - /** * {@link UsernamePasswordCredentials} {@link DeviceConnectionCredentialAdapter} * @@ -27,16 +24,9 @@ */ public class UserPassDeviceConnectionCredentialAdapter implements DeviceConnectionCredentialAdapter { - private CredentialsFactory credentialsFactory; - - @Inject - public UserPassDeviceConnectionCredentialAdapter(CredentialsFactory credentialsFactory) { - this.credentialsFactory = credentialsFactory; - } - @Override public LoginCredentials mapToCredential(AuthRequest authRequest) { - return credentialsFactory.newUsernamePasswordCredentials( + return new UsernamePasswordCredentials( authRequest.getUsername(), authRequest.getPassword()); } diff --git a/service/device/call/api/pom.xml b/service/device/call/api/pom.xml index 7109dc7c587..4821b04f8ef 100644 --- a/service/device/call/api/pom.xml +++ b/service/device/call/api/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-device-call - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-device-call-api diff --git a/service/device/call/kura/pom.xml b/service/device/call/kura/pom.xml index eb1b91e0117..140db1904c0 100644 --- a/service/device/call/kura/pom.xml +++ b/service/device/call/kura/pom.xml @@ -19,7 +19,7 @@ org.eclipse.kapua kapua-device-call - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-device-call-kura diff --git a/service/device/call/pom.xml b/service/device/call/pom.xml index e30359f57c3..6714377cc85 100644 --- a/service/device/call/pom.xml +++ b/service/device/call/pom.xml @@ -19,7 +19,7 @@ org.eclipse.kapua kapua-device - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT pom diff --git a/service/device/commons/pom.xml b/service/device/commons/pom.xml index 1a921d5b9d9..943995be7a7 100644 --- a/service/device/commons/pom.xml +++ b/service/device/commons/pom.xml @@ -19,7 +19,7 @@ org.eclipse.kapua kapua-device - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-device-commons diff --git a/service/device/commons/src/main/java/org/eclipse/kapua/service/device/management/commons/AbstractDeviceManagementServiceImpl.java b/service/device/commons/src/main/java/org/eclipse/kapua/service/device/management/commons/AbstractDeviceManagementServiceImpl.java index a8d0d4d8fa5..c55233238bf 100644 --- a/service/device/commons/src/main/java/org/eclipse/kapua/service/device/management/commons/AbstractDeviceManagementServiceImpl.java +++ b/service/device/commons/src/main/java/org/eclipse/kapua/service/device/management/commons/AbstractDeviceManagementServiceImpl.java @@ -12,6 +12,15 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.commons; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.concurrent.Callable; + +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Null; + import org.eclipse.kapua.KapuaEntityNotFoundException; import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.commons.security.KapuaSecurityUtils; @@ -43,17 +52,8 @@ import org.eclipse.kapua.service.device.registry.connection.DeviceConnection; import org.eclipse.kapua.service.device.registry.connection.DeviceConnectionStatus; import org.eclipse.kapua.service.device.registry.event.DeviceEventCreator; -import org.eclipse.kapua.service.device.registry.event.DeviceEventFactory; import org.eclipse.kapua.service.device.registry.event.DeviceEventService; -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Null; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.Map; -import java.util.concurrent.Callable; - /** * Utility {@code abstract} {@link Class} used to provide utility methods to all implementation of {@link DeviceManagementService}s. * @@ -66,7 +66,6 @@ public abstract class AbstractDeviceManagementServiceImpl { protected final KapuaLocator kapuaLocator = KapuaLocator.getInstance(); private final DeviceEventService kapuaLocatorService = kapuaLocator.getService(DeviceEventService.class); - private final DeviceEventFactory deviceEventFactory = kapuaLocator.getFactory(DeviceEventFactory.class); private final DeviceRegistryService deviceRegistryService = kapuaLocator.getService(DeviceRegistryService.class); @@ -83,17 +82,22 @@ public abstract class AbstractDeviceManagementServiceImpl { * This operation is performed using {@link KapuaSecurityUtils#doPrivileged(ThrowingRunnable)} since {@link org.eclipse.kapua.commons.model.domains.Domains#DEVICE_EVENT} isn't a required * permission to use any of the Device Management Services. * - * @param scopeId The scopeId in which to create the {@link org.eclipse.kapua.service.device.registry.event.DeviceEvent} - * @param deviceId The {@link org.eclipse.kapua.service.device.registry.Device} id for which the {@link org.eclipse.kapua.service.device.registry.event.DeviceEvent} is created - * @param requestMessage The {@link KapuaRequestMessage} of the DeviceManagementService operation from which to extract data. - * @param responseMessage The {@link KapuaResponseMessage} of the DeviceManagementService operation from which to extract data. - * @throws KapuaException If the creation of the {@link org.eclipse.kapua.service.device.registry.event.DeviceEvent} fails for some reasons + * @param scopeId + * The scopeId in which to create the {@link org.eclipse.kapua.service.device.registry.event.DeviceEvent} + * @param deviceId + * The {@link org.eclipse.kapua.service.device.registry.Device} id for which the {@link org.eclipse.kapua.service.device.registry.event.DeviceEvent} is created + * @param requestMessage + * The {@link KapuaRequestMessage} of the DeviceManagementService operation from which to extract data. + * @param responseMessage + * The {@link KapuaResponseMessage} of the DeviceManagementService operation from which to extract data. + * @throws KapuaException + * If the creation of the {@link org.eclipse.kapua.service.device.registry.event.DeviceEvent} fails for some reasons * @since 1.0.0 */ protected void createDeviceEvent(KapuaId scopeId, KapuaId deviceId, KapuaRequestMessage requestMessage, KapuaResponseMessage responseMessage) throws KapuaException { DeviceEventCreator deviceEventCreator = - deviceEventFactory.newCreator( + new DeviceEventCreator( scopeId, deviceId, responseMessage != null ? responseMessage.getReceivedOn() : requestMessage.getSentOn(), @@ -111,9 +115,12 @@ protected void createDeviceEvent(KapuaId scopeId, KapuaId deviceId, KapuaRequest /** * Checks whether the {@link Device} exists and if it is connected. * - * @param scopeId The {@link Device#getScopeId()}. - * @param deviceId The {@link Device#getId()}. - * @return {@code true} if {@link Device} exists, has a {@link Device#getConnection()} and the {@link DeviceConnection#getStatus()} is {@link DeviceConnectionStatus#CONNECTED}, {@code false} otherwise. + * @param scopeId + * The {@link Device#getScopeId()}. + * @param deviceId + * The {@link Device#getId()}. + * @return {@code true} if {@link Device} exists, has a {@link Device#getConnection()} and the {@link DeviceConnection#getStatus()} is {@link DeviceConnectionStatus#CONNECTED}, {@code false} + * otherwise. * @throws KapuaException */ public boolean isDeviceConnected(KapuaId scopeId, KapuaId deviceId) throws KapuaException { @@ -142,7 +149,7 @@ public boolean isDeviceConnected(KapuaId scopeId, KapuaId deviceId) throws Kapua protected KapuaId createManagementOperation(KapuaId scopeId, KapuaId deviceId, KapuaId operationId, KapuaRequestMessage requestMessage) throws KapuaException { - DeviceManagementOperationCreator deviceManagementOperationCreator = deviceManagementOperationFactory.newCreator(scopeId); + DeviceManagementOperationCreator deviceManagementOperationCreator = new DeviceManagementOperationCreator(scopeId); deviceManagementOperationCreator.setDeviceId(deviceId); deviceManagementOperationCreator.setOperationId(operationId); deviceManagementOperationCreator.setStartedOn(new Date()); @@ -179,7 +186,6 @@ protected void closeManagementOperation(KapuaId scopeId, KapuaId deviceId, Kapua KapuaSecurityUtils.doPrivileged(() -> deviceManagementOperationRegistryService.update(deviceManagementOperation)); } - // // Response handling // @@ -187,8 +193,10 @@ protected void closeManagementOperation(KapuaId scopeId, KapuaId deviceId, Kapua /** * Checks the {@link KapuaResponseMessage#getResponseCode()} if it is {@link KapuaResponseCode#ACCEPTED} or throws the proper {@link DeviceManagementResponseCodeException}. * - * @param responseMessage The {@link KapuaResponseMessage} to check. - * @throws DeviceManagementResponseCodeException if {@link KapuaResponseMessage#getResponseCode()} is not {@link KapuaResponseCode#ACCEPTED}. + * @param responseMessage + * The {@link KapuaResponseMessage} to check. + * @throws DeviceManagementResponseCodeException + * if {@link KapuaResponseMessage#getResponseCode()} is not {@link KapuaResponseCode#ACCEPTED}. * @since 1.5.0 */ protected void checkResponseAcceptedOrThrowError(@NotNull KapuaResponseMessage responseMessage) throws DeviceManagementResponseCodeException { @@ -204,15 +212,21 @@ protected void checkResponseAcceptedOrThrowError(@NotNull KapuaResponseMessage * If {@link Callable} is not provided the returned result will be {@code null}. * - * @param responseMessage The {@link KapuaResponseMessage} to check. - * @param resultGetter The {@link Callable} that gets the result. - * @param The type of the result. + * @param responseMessage + * The {@link KapuaResponseMessage} to check. + * @param resultGetter + * The {@link Callable} that gets the result. + * @param + * The type of the result. * @return The result from the {@link KapuaResponseMessage} if {@link KapuaResponseMessage#getResponseCode()} is {@link KapuaResponseCode#ACCEPTED}. - * @throws DeviceManagementResponseCodeException if {@link KapuaResponseMessage#getResponseCode()} is not {@link KapuaResponseCode#ACCEPTED}. - * @throws DeviceManagementResponseContentException if getting the result causes any {@link Exception}. + * @throws DeviceManagementResponseCodeException + * if {@link KapuaResponseMessage#getResponseCode()} is not {@link KapuaResponseCode#ACCEPTED}. + * @throws DeviceManagementResponseContentException + * if getting the result causes any {@link Exception}. * @since 1.5.0 */ - protected R checkResponseAcceptedOrThrowError(@NotNull KapuaResponseMessage responseMessage, @Null Callable resultGetter) throws DeviceManagementResponseCodeException, DeviceManagementResponseContentException { + protected R checkResponseAcceptedOrThrowError(@NotNull KapuaResponseMessage responseMessage, @Null Callable resultGetter) + throws DeviceManagementResponseCodeException, DeviceManagementResponseContentException { if (responseMessage.getResponseCode().isAccepted()) { if (resultGetter != null) { try { @@ -231,7 +245,8 @@ protected R checkResponseAcceptedOrThrowError(@NotNull KapuaResponseMessage< /** * Builds the {@link DeviceManagementResponseCodeException} from the {@link KapuaResponseMessage}. * - * @param kapuaResponseMessage The {@link KapuaResponseMessage} to build from. + * @param kapuaResponseMessage + * The {@link KapuaResponseMessage} to build from. * @return The proper {@link DeviceManagementResponseCodeException} for the {@link KapuaResponseMessage#getResponseCode()} * @since 1.5.0 */ @@ -240,15 +255,15 @@ protected DeviceManagementResponseCodeException buildExceptionFromDeviceResponse KapuaResponsePayload responsePayload = kapuaResponseMessage.getPayload(); switch (kapuaResponseMessage.getResponseCode()) { - case BAD_REQUEST: - return new DeviceManagementResponseBadRequestException(kapuaResponseMessage.getResponseCode(), responsePayload.getExceptionMessage(), responsePayload.getExceptionMessage()); - case NOT_FOUND: - return new DeviceManagementResponseNotFoundException(kapuaResponseMessage.getResponseCode(), responsePayload.getExceptionMessage(), responsePayload.getExceptionMessage()); - case INTERNAL_ERROR: - return new DeviceManagementResponseInternalErrorException(kapuaResponseMessage.getResponseCode(), responsePayload.getExceptionMessage(), responsePayload.getExceptionMessage()); - case ACCEPTED: - default: - return new DeviceManagementResponseUnknownCodeException(kapuaResponseMessage.getResponseCode(), responsePayload.getExceptionMessage(), responsePayload.getExceptionMessage()); + case BAD_REQUEST: + return new DeviceManagementResponseBadRequestException(kapuaResponseMessage.getResponseCode(), responsePayload.getExceptionMessage(), responsePayload.getExceptionMessage()); + case NOT_FOUND: + return new DeviceManagementResponseNotFoundException(kapuaResponseMessage.getResponseCode(), responsePayload.getExceptionMessage(), responsePayload.getExceptionMessage()); + case INTERNAL_ERROR: + return new DeviceManagementResponseInternalErrorException(kapuaResponseMessage.getResponseCode(), responsePayload.getExceptionMessage(), responsePayload.getExceptionMessage()); + case ACCEPTED: + default: + return new DeviceManagementResponseUnknownCodeException(kapuaResponseMessage.getResponseCode(), responsePayload.getExceptionMessage(), responsePayload.getExceptionMessage()); } } diff --git a/service/device/commons/src/main/java/org/eclipse/kapua/service/device/management/commons/AbstractDeviceManagementTransactionalServiceImpl.java b/service/device/commons/src/main/java/org/eclipse/kapua/service/device/management/commons/AbstractDeviceManagementTransactionalServiceImpl.java index 4924be3c218..265490f1c5a 100644 --- a/service/device/commons/src/main/java/org/eclipse/kapua/service/device/management/commons/AbstractDeviceManagementTransactionalServiceImpl.java +++ b/service/device/commons/src/main/java/org/eclipse/kapua/service/device/management/commons/AbstractDeviceManagementTransactionalServiceImpl.java @@ -12,6 +12,12 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.commons; +import java.util.Optional; +import java.util.concurrent.Callable; + +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Null; + import org.eclipse.kapua.KapuaEntityNotFoundException; import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.commons.security.KapuaSecurityUtils; @@ -19,7 +25,6 @@ import org.eclipse.kapua.commons.util.ThrowingRunnable; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; import org.eclipse.kapua.service.device.management.DeviceManagementService; import org.eclipse.kapua.service.device.management.exception.DeviceManagementResponseBadRequestException; import org.eclipse.kapua.service.device.management.exception.DeviceManagementResponseCodeException; @@ -40,11 +45,6 @@ import org.eclipse.kapua.service.device.registry.event.DeviceEventService; import org.eclipse.kapua.storage.TxManager; -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Null; -import java.util.Optional; -import java.util.concurrent.Callable; - /** * Utility {@code abstract} {@link Class} used to provide utility methods to all implementation of {@link DeviceManagementService}s. * @@ -54,7 +54,6 @@ public abstract class AbstractDeviceManagementTransactionalServiceImpl { protected final TxManager txManager; protected final AuthorizationService authorizationService; - protected final PermissionFactory permissionFactory; protected final DeviceEventService deviceEventService; protected final DeviceEventFactory deviceEventFactory; @@ -64,13 +63,11 @@ public abstract class AbstractDeviceManagementTransactionalServiceImpl { public AbstractDeviceManagementTransactionalServiceImpl( TxManager txManager, AuthorizationService authorizationService, - PermissionFactory permissionFactory, DeviceEventService deviceEventService, DeviceEventFactory deviceEventFactory, DeviceRegistryService deviceRegistryService) { this.txManager = txManager; this.authorizationService = authorizationService; - this.permissionFactory = permissionFactory; this.deviceEventService = deviceEventService; this.deviceEventFactory = deviceEventFactory; this.deviceRegistryService = deviceRegistryService; @@ -83,17 +80,22 @@ public AbstractDeviceManagementTransactionalServiceImpl( * This operation is performed using {@link KapuaSecurityUtils#doPrivileged(ThrowingRunnable)} since {@link org.eclipse.kapua.commons.model.domains.Domains#DEVICE_EVENT} isn't a required * permission to use any of the Device Management Services. * - * @param scopeId The scopeId in which to create the {@link org.eclipse.kapua.service.device.registry.event.DeviceEvent} - * @param deviceId The {@link org.eclipse.kapua.service.device.registry.Device} id for which the {@link org.eclipse.kapua.service.device.registry.event.DeviceEvent} is created - * @param requestMessage The {@link KapuaRequestMessage} of the DeviceManagementService operation from which to extract data. - * @param responseMessage The {@link KapuaResponseMessage} of the DeviceManagementService operation from which to extract data. - * @throws KapuaException If the creation of the {@link org.eclipse.kapua.service.device.registry.event.DeviceEvent} fails for some reasons + * @param scopeId + * The scopeId in which to create the {@link org.eclipse.kapua.service.device.registry.event.DeviceEvent} + * @param deviceId + * The {@link org.eclipse.kapua.service.device.registry.Device} id for which the {@link org.eclipse.kapua.service.device.registry.event.DeviceEvent} is created + * @param requestMessage + * The {@link KapuaRequestMessage} of the DeviceManagementService operation from which to extract data. + * @param responseMessage + * The {@link KapuaResponseMessage} of the DeviceManagementService operation from which to extract data. + * @throws KapuaException + * If the creation of the {@link org.eclipse.kapua.service.device.registry.event.DeviceEvent} fails for some reasons * @since 1.0.0 */ protected void createDeviceEvent(KapuaId scopeId, KapuaId deviceId, KapuaRequestMessage requestMessage, KapuaResponseMessage responseMessage) throws KapuaException { DeviceEventCreator deviceEventCreator = - deviceEventFactory.newCreator( + new DeviceEventCreator( scopeId, deviceId, responseMessage != null ? responseMessage.getReceivedOn() : requestMessage.getSentOn(), @@ -111,9 +113,12 @@ protected void createDeviceEvent(KapuaId scopeId, KapuaId deviceId, KapuaRequest /** * Checks whether the {@link Device} exists and if it is connected. * - * @param scopeId The {@link Device#getScopeId()}. - * @param deviceId The {@link Device#getId()}. - * @return {@code true} if {@link Device} exists, has a {@link Device#getConnection()} and the {@link DeviceConnection#getStatus()} is {@link DeviceConnectionStatus#CONNECTED}, {@code false} otherwise. + * @param scopeId + * The {@link Device#getScopeId()}. + * @param deviceId + * The {@link Device#getId()}. + * @return {@code true} if {@link Device} exists, has a {@link Device#getConnection()} and the {@link DeviceConnection#getStatus()} is {@link DeviceConnectionStatus#CONNECTED}, {@code false} + * otherwise. * @throws KapuaException */ public boolean isDeviceConnected(KapuaId scopeId, KapuaId deviceId) throws KapuaException { @@ -134,8 +139,10 @@ public boolean isDeviceConnected(KapuaId scopeId, KapuaId deviceId) throws Kapua /** * Checks the {@link KapuaResponseMessage#getResponseCode()} if it is {@link KapuaResponseCode#ACCEPTED} or throws the proper {@link DeviceManagementResponseCodeException}. * - * @param responseMessage The {@link KapuaResponseMessage} to check. - * @throws DeviceManagementResponseCodeException if {@link KapuaResponseMessage#getResponseCode()} is not {@link KapuaResponseCode#ACCEPTED}. + * @param responseMessage + * The {@link KapuaResponseMessage} to check. + * @throws DeviceManagementResponseCodeException + * if {@link KapuaResponseMessage#getResponseCode()} is not {@link KapuaResponseCode#ACCEPTED}. * @since 1.5.0 */ protected void checkResponseAcceptedOrThrowError(@NotNull KapuaResponseMessage responseMessage) throws DeviceManagementResponseCodeException { @@ -151,15 +158,21 @@ protected void checkResponseAcceptedOrThrowError(@NotNull KapuaResponseMessage * If {@link Callable} is not provided the returned result will be {@code null}. * - * @param responseMessage The {@link KapuaResponseMessage} to check. - * @param resultGetter The {@link Callable} that gets the result. - * @param The type of the result. + * @param responseMessage + * The {@link KapuaResponseMessage} to check. + * @param resultGetter + * The {@link Callable} that gets the result. + * @param + * The type of the result. * @return The result from the {@link KapuaResponseMessage} if {@link KapuaResponseMessage#getResponseCode()} is {@link KapuaResponseCode#ACCEPTED}. - * @throws DeviceManagementResponseCodeException if {@link KapuaResponseMessage#getResponseCode()} is not {@link KapuaResponseCode#ACCEPTED}. - * @throws DeviceManagementResponseContentException if getting the result causes any {@link Exception}. + * @throws DeviceManagementResponseCodeException + * if {@link KapuaResponseMessage#getResponseCode()} is not {@link KapuaResponseCode#ACCEPTED}. + * @throws DeviceManagementResponseContentException + * if getting the result causes any {@link Exception}. * @since 1.5.0 */ - protected R checkResponseAcceptedOrThrowError(@NotNull KapuaResponseMessage responseMessage, @Null Callable resultGetter) throws DeviceManagementResponseCodeException, DeviceManagementResponseContentException { + protected R checkResponseAcceptedOrThrowError(@NotNull KapuaResponseMessage responseMessage, @Null Callable resultGetter) + throws DeviceManagementResponseCodeException, DeviceManagementResponseContentException { if (responseMessage.getResponseCode().isAccepted()) { if (resultGetter != null) { try { @@ -178,7 +191,8 @@ protected R checkResponseAcceptedOrThrowError(@NotNull KapuaResponseMessage< /** * Builds the {@link DeviceManagementResponseCodeException} from the {@link KapuaResponseMessage}. * - * @param kapuaResponseMessage The {@link KapuaResponseMessage} to build from. + * @param kapuaResponseMessage + * The {@link KapuaResponseMessage} to build from. * @return The proper {@link DeviceManagementResponseCodeException} for the {@link KapuaResponseMessage#getResponseCode()} * @since 1.5.0 */ @@ -187,15 +201,15 @@ protected DeviceManagementResponseCodeException buildExceptionFromDeviceResponse KapuaResponsePayload responsePayload = kapuaResponseMessage.getPayload(); switch (kapuaResponseMessage.getResponseCode()) { - case BAD_REQUEST: - return new DeviceManagementResponseBadRequestException(kapuaResponseMessage.getResponseCode(), responsePayload.getExceptionMessage(), responsePayload.getExceptionMessage()); - case NOT_FOUND: - return new DeviceManagementResponseNotFoundException(kapuaResponseMessage.getResponseCode(), responsePayload.getExceptionMessage(), responsePayload.getExceptionMessage()); - case INTERNAL_ERROR: - return new DeviceManagementResponseInternalErrorException(kapuaResponseMessage.getResponseCode(), responsePayload.getExceptionMessage(), responsePayload.getExceptionMessage()); - case ACCEPTED: - default: - return new DeviceManagementResponseUnknownCodeException(kapuaResponseMessage.getResponseCode(), responsePayload.getExceptionMessage(), responsePayload.getExceptionMessage()); + case BAD_REQUEST: + return new DeviceManagementResponseBadRequestException(kapuaResponseMessage.getResponseCode(), responsePayload.getExceptionMessage(), responsePayload.getExceptionMessage()); + case NOT_FOUND: + return new DeviceManagementResponseNotFoundException(kapuaResponseMessage.getResponseCode(), responsePayload.getExceptionMessage(), responsePayload.getExceptionMessage()); + case INTERNAL_ERROR: + return new DeviceManagementResponseInternalErrorException(kapuaResponseMessage.getResponseCode(), responsePayload.getExceptionMessage(), responsePayload.getExceptionMessage()); + case ACCEPTED: + default: + return new DeviceManagementResponseUnknownCodeException(kapuaResponseMessage.getResponseCode(), responsePayload.getExceptionMessage(), responsePayload.getExceptionMessage()); } } } diff --git a/service/device/management/all/api/pom.xml b/service/device/management/all/api/pom.xml index b2e7ca09e61..907f231e394 100644 --- a/service/device/management/all/api/pom.xml +++ b/service/device/management/all/api/pom.xml @@ -19,7 +19,7 @@ kapua-device-management-all org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-device-management-all-api diff --git a/service/device/management/all/internal/pom.xml b/service/device/management/all/internal/pom.xml index 6a2228bfacb..a512accd4f2 100644 --- a/service/device/management/all/internal/pom.xml +++ b/service/device/management/all/internal/pom.xml @@ -19,7 +19,7 @@ kapua-device-management-all org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-device-management-all-internal diff --git a/service/device/management/all/job/pom.xml b/service/device/management/all/job/pom.xml index 8d93265ac07..eb971d1c982 100644 --- a/service/device/management/all/job/pom.xml +++ b/service/device/management/all/job/pom.xml @@ -19,7 +19,7 @@ kapua-device-management-all org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-device-management-all-job diff --git a/service/device/management/all/pom.xml b/service/device/management/all/pom.xml index e128485df2c..a01d80a32f9 100644 --- a/service/device/management/all/pom.xml +++ b/service/device/management/all/pom.xml @@ -19,7 +19,7 @@ kapua-device-management org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT pom diff --git a/service/device/management/api/pom.xml b/service/device/management/api/pom.xml index fac6e087150..20a4e70607e 100644 --- a/service/device/management/api/pom.xml +++ b/service/device/management/api/pom.xml @@ -19,7 +19,7 @@ kapua-device-management org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-device-management-api diff --git a/service/device/management/asset-store/api/pom.xml b/service/device/management/asset-store/api/pom.xml index c4eb4a6bd71..b0e3f1e3b1e 100644 --- a/service/device/management/asset-store/api/pom.xml +++ b/service/device/management/asset-store/api/pom.xml @@ -19,7 +19,7 @@ org.eclipse.kapua kapua-device-management-asset-store - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-device-management-asset-store-api diff --git a/service/device/management/asset-store/dummy/pom.xml b/service/device/management/asset-store/dummy/pom.xml index e8e6362414d..8abe32502d2 100644 --- a/service/device/management/asset-store/dummy/pom.xml +++ b/service/device/management/asset-store/dummy/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-device-management-asset-store - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-device-management-asset-store-dummy diff --git a/service/device/management/asset-store/dummy/src/main/java/org/eclipse/kapua/service/device/management/asset/store/dummy/DeviceAssetStoreServiceDummy.java b/service/device/management/asset-store/dummy/src/main/java/org/eclipse/kapua/service/device/management/asset/store/dummy/DeviceAssetStoreServiceDummy.java index b8df0cf5965..2bb5aeae1a0 100644 --- a/service/device/management/asset-store/dummy/src/main/java/org/eclipse/kapua/service/device/management/asset/store/dummy/DeviceAssetStoreServiceDummy.java +++ b/service/device/management/asset-store/dummy/src/main/java/org/eclipse/kapua/service/device/management/asset/store/dummy/DeviceAssetStoreServiceDummy.java @@ -18,7 +18,6 @@ import org.eclipse.kapua.commons.service.internal.KapuaServiceDisabledException; import org.eclipse.kapua.message.device.data.KapuaDataMessage; -import org.eclipse.kapua.model.config.metatype.EmptyTocd; import org.eclipse.kapua.model.config.metatype.KapuaTocd; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.device.management.asset.DeviceAssets; @@ -60,7 +59,7 @@ public void storeAssetValues(KapuaDataMessage message) throws KapuaServiceDisabl @Override public KapuaTocd getConfigMetadata(KapuaId scopeId) { - return new EmptyTocd(); + return KapuaTocd.empty(); } @Override diff --git a/service/device/management/asset-store/pom.xml b/service/device/management/asset-store/pom.xml index d0174ff0d1f..56c3f8caebe 100644 --- a/service/device/management/asset-store/pom.xml +++ b/service/device/management/asset-store/pom.xml @@ -19,7 +19,7 @@ org.eclipse.kapua kapua-device-management - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-device-management-asset-store diff --git a/service/device/management/asset/api/pom.xml b/service/device/management/asset/api/pom.xml index f5e0aa9d9d9..b0700a0800e 100644 --- a/service/device/management/asset/api/pom.xml +++ b/service/device/management/asset/api/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-device-management-asset - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-device-management-asset-api diff --git a/service/device/management/asset/api/src/main/java/org/eclipse/kapua/service/device/management/asset/DeviceAsset.java b/service/device/management/asset/api/src/main/java/org/eclipse/kapua/service/device/management/asset/DeviceAsset.java index 7e0185f5a59..254c17ab5c1 100644 --- a/service/device/management/asset/api/src/main/java/org/eclipse/kapua/service/device/management/asset/DeviceAsset.java +++ b/service/device/management/asset/api/src/main/java/org/eclipse/kapua/service/device/management/asset/DeviceAsset.java @@ -12,7 +12,8 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.asset; -import org.eclipse.kapua.service.device.management.asset.xml.DeviceAssetChannelXmlAdapter; +import java.util.ArrayList; +import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; @@ -21,7 +22,8 @@ import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; -import java.util.List; + +import org.eclipse.kapua.service.device.management.asset.xml.DeviceAssetChannelXmlAdapter; /** * {@link DeviceAsset} definition. @@ -32,8 +34,11 @@ */ @XmlRootElement(name = "deviceAsset") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = DeviceAssetXmlRegistry.class, factoryMethod = "newDeviceAsset") -public interface DeviceAsset { +@XmlType +public class DeviceAsset { + + private String name; + private List channels; /** * Gets the name. @@ -42,15 +47,20 @@ public interface DeviceAsset { * @since 1.0.0 */ @XmlElement(name = "name") - String getName(); + public String getName() { + return name; + } /** * Sets the name. * - * @param name The name. + * @param name + * The name. * @since 1.0.0 */ - void setName(String name); + public void setName(String name) { + this.name = name; + } /** * Gets the {@link DeviceAssetChannel} available. @@ -61,13 +71,23 @@ public interface DeviceAsset { @XmlElementWrapper(name = "channels") @XmlElement(name = "channel") @XmlJavaTypeAdapter(DeviceAssetChannelXmlAdapter.class) - List getChannels(); + public List getChannels() { + if (channels == null) { + channels = new ArrayList<>(); + } + + return channels; + } /** * Sets the {@link DeviceAssetChannel} available. * - * @param channels The {@link DeviceAssetChannel} available. + * @param channels + * The {@link DeviceAssetChannel} available. * @since 1.0.0 */ - void setChannels(List channels); + public void setChannels(List channels) { + this.channels = channels; + } + } diff --git a/service/device/management/asset/api/src/main/java/org/eclipse/kapua/service/device/management/asset/DeviceAssetChannel.java b/service/device/management/asset/api/src/main/java/org/eclipse/kapua/service/device/management/asset/DeviceAssetChannel.java index a720272c570..af9cab25abe 100644 --- a/service/device/management/asset/api/src/main/java/org/eclipse/kapua/service/device/management/asset/DeviceAssetChannel.java +++ b/service/device/management/asset/api/src/main/java/org/eclipse/kapua/service/device/management/asset/DeviceAssetChannel.java @@ -21,7 +21,14 @@ * * @since 1.0.0 */ -public interface DeviceAssetChannel { +public class DeviceAssetChannel { + + private String name; + private Class clazz; + private DeviceAssetChannelMode mode; + private Object value; + private String error; + private Date timestamp; /** * Gets the name. @@ -29,15 +36,20 @@ public interface DeviceAssetChannel { * @return The name. * @since 1.0.0 */ - String getName(); + public String getName() { + return name; + } /** * Gets the name. * - * @param name The name. + * @param name + * The name. * @since 1.0.0 */ - void setName(String name); + public void setName(String name) { + this.name = name; + } /** * Gets the {@link Class} type. @@ -47,17 +59,20 @@ public interface DeviceAssetChannel { * @return The channel value type. * @since 1.0.0 */ - Class getType(); + public Class getType() { + return clazz; + } /** - * Sets the {@link Class} type. - * This type must be coherent with the value given to {@link #setValue(Object)}. - * If not, errors will occur during the interaction with the device. + * Sets the {@link Class} type. This type must be coherent with the value given to {@link #setValue(Object)}. If not, errors will occur during the interaction with the device. * - * @param type The {@link Class} type. + * @param type + * The {@link Class} type. * @since 1.0.0 */ - void setType(Class type); + public void setType(Class type) { + this.clazz = type; + } /** * Gets the {@link DeviceAssetChannelMode}. @@ -65,58 +80,74 @@ public interface DeviceAssetChannel { * @return The {@link DeviceAssetChannelMode}. * @since 1.0.0 */ - DeviceAssetChannelMode getMode(); + public DeviceAssetChannelMode getMode() { + return mode; + } /** * Sets the {@link DeviceAssetChannelMode}. * - * @param deviceAssetChannelMode The {@link DeviceAssetChannelMode}. + * @param deviceAssetChannelMode + * The {@link DeviceAssetChannelMode}. * @since 1.0.0 */ - void setMode(DeviceAssetChannelMode deviceAssetChannelMode); + public void setMode(DeviceAssetChannelMode deviceAssetChannelMode) { + this.mode = deviceAssetChannelMode; + } /** * Gets the value channel. *

        - * Depending on the {@link DeviceAssetChannelMode} this can be a value {@link DeviceAssetChannelMode#READ} from the channel or - * to {@link DeviceAssetChannelMode#WRITE} into the channel. - * This is mutually exclusive with {@link #getError()} + * Depending on the {@link DeviceAssetChannelMode} this can be a value {@link DeviceAssetChannelMode#READ} from the channel or to {@link DeviceAssetChannelMode#WRITE} into the channel. This is + * mutually exclusive with {@link #getError()} * * @return The value channel. * @since 1.0.0 */ - Object getValue(); + public Object getValue() { + return value; + } /** * Sets the value channel. *

        - * Depending on the {@link DeviceAssetChannelMode} this can be a value {@link DeviceAssetChannelMode#READ} from the channel or - * to {@link DeviceAssetChannelMode#WRITE} into the channel. + * Depending on the {@link DeviceAssetChannelMode} this can be a value {@link DeviceAssetChannelMode#READ} from the channel or to {@link DeviceAssetChannelMode#WRITE} into the channel. * - * @param value The value channel. + * @param value + * The value channel. * @since 1.0.0 */ - void setValue(Object value); + public void setValue(Object value) { + this.value = value; + + if (value != null) { + setType(value.getClass()); + } + } /** * Gets the error message. *

        - * When reading from or writing to a channel, if any error occurs it will be reported here. - * This is mutually exclusive with {@link #getValue()} + * When reading from or writing to a channel, if any error occurs it will be reported here. This is mutually exclusive with {@link #getValue()} * * @return The error message, if error has occurred. * @since 1.0.0 */ - String getError(); + public String getError() { + return error; + } /** * Sets the error message. *

        * This must be set if error has occurred during reading from/wrtiting to * - * @param error The error message. + * @param error + * The error message. */ - void setError(String error); + public void setError(String error) { + this.error = error; + } /** * Gets the {@link Date} of the time when the value was read from the channel. @@ -124,13 +155,19 @@ public interface DeviceAssetChannel { * @return The {@link Date} of the time when the value was read from the channel. * @since 1.0.0 */ - Date getTimestamp(); + public Date getTimestamp() { + return timestamp; + } /** * Sets the {@link Date} of the time when the value was read from the channel. * - * @param timestamp The {@link Date} of the time when the value was read from the channel. + * @param timestamp + * The {@link Date} of the time when the value was read from the channel. * @since 1.0.0 */ - void setTimestamp(Date timestamp); + public void setTimestamp(Date timestamp) { + this.timestamp = timestamp; + } + } diff --git a/service/device/management/asset/api/src/main/java/org/eclipse/kapua/service/device/management/asset/DeviceAssetFactory.java b/service/device/management/asset/api/src/main/java/org/eclipse/kapua/service/device/management/asset/DeviceAssetFactory.java deleted file mode 100644 index 2898dc9e806..00000000000 --- a/service/device/management/asset/api/src/main/java/org/eclipse/kapua/service/device/management/asset/DeviceAssetFactory.java +++ /dev/null @@ -1,48 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.asset; - -import org.eclipse.kapua.model.KapuaObjectFactory; - -/** - * {@link DeviceAsset} {@link KapuaObjectFactory} definition. - * - * @see org.eclipse.kapua.model.KapuaObjectFactory - * @since 1.0.0 - */ -public interface DeviceAssetFactory extends KapuaObjectFactory { - - /** - * Instantiates a new {@link DeviceAssets} instance. - * - * @return The newly instantiated {@link DeviceAssets}. - * @since 1.0.0 - */ - DeviceAssets newAssetListResult(); - - /** - * Instantiates a new {@link DeviceAsset} instance. - * - * @return The newly instantiated {@link DeviceAsset}. - * @since 1.0.0 - */ - DeviceAsset newDeviceAsset(); - - /** - * Instantiates a new {@link DeviceAssetChannel} instance. - * - * @return The newly instantiated {@link DeviceAssetChannel} - * @since 1.0.0 - */ - DeviceAssetChannel newDeviceAssetChannel(); -} diff --git a/service/device/management/asset/api/src/main/java/org/eclipse/kapua/service/device/management/asset/DeviceAssetXmlRegistry.java b/service/device/management/asset/api/src/main/java/org/eclipse/kapua/service/device/management/asset/DeviceAssetXmlRegistry.java deleted file mode 100644 index 3756d7c6ae8..00000000000 --- a/service/device/management/asset/api/src/main/java/org/eclipse/kapua/service/device/management/asset/DeviceAssetXmlRegistry.java +++ /dev/null @@ -1,58 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2017, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.asset; - -import org.eclipse.kapua.locator.KapuaLocator; - -import javax.xml.bind.annotation.XmlRegistry; - -/** - * {@link DeviceAsset} XML factory class - * - * @since 1.0.0 - */ -@XmlRegistry -public class DeviceAssetXmlRegistry { - - private final DeviceAssetFactory deviceAssetFactory = KapuaLocator.getInstance().getFactory(DeviceAssetFactory.class); - - /** - * Instantiate a new {@link DeviceAssets}. - * - * @return The newly instantiate {@link DeviceAssets}. - * @since 1.0.0 - */ - public DeviceAssets newAssetListResult() { - return deviceAssetFactory.newAssetListResult(); - } - - /** - * Instantiate a new {@link DeviceAsset}. - * - * @return The newly instantiated {@link DeviceAsset}. - * @since 1.0.0 - */ - public DeviceAsset newDeviceAsset() { - return deviceAssetFactory.newDeviceAsset(); - } - - /** - * Instantiate a new {@link DeviceAssetChannel}. - * - * @return The newly instantiated {@link DeviceAssetChannel}. - * @since 1.0.0 - */ - public DeviceAssetChannel newDeviceAssetChannel() { - return deviceAssetFactory.newDeviceAssetChannel(); - } -} diff --git a/service/device/management/asset/api/src/main/java/org/eclipse/kapua/service/device/management/asset/DeviceAssets.java b/service/device/management/asset/api/src/main/java/org/eclipse/kapua/service/device/management/asset/DeviceAssets.java index c5519a59607..5cd77306707 100644 --- a/service/device/management/asset/api/src/main/java/org/eclipse/kapua/service/device/management/asset/DeviceAssets.java +++ b/service/device/management/asset/api/src/main/java/org/eclipse/kapua/service/device/management/asset/DeviceAssets.java @@ -12,14 +12,16 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.asset; -import org.eclipse.kapua.KapuaSerializable; +import java.util.ArrayList; +import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; -import java.util.List; + +import org.eclipse.kapua.KapuaSerializable; /** * {@link DeviceAssets} definition. @@ -28,8 +30,12 @@ */ @XmlRootElement(name = "deviceAssets") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = DeviceAssetXmlRegistry.class, factoryMethod = "newAssetListResult") -public interface DeviceAssets extends KapuaSerializable { +@XmlType +public class DeviceAssets implements KapuaSerializable { + + private static final long serialVersionUID = -6657213220333406876L; + + private List assets; /** * Get the {@link DeviceAsset} {@link List} @@ -38,13 +44,22 @@ public interface DeviceAssets extends KapuaSerializable { * @since 1.0.0 */ @XmlElement(name = "deviceAsset") - List getAssets(); + public List getAssets() { + if (assets == null) { + assets = new ArrayList<>(); + } + + return assets; + } /** * Sets the {@link DeviceAsset} {@link List}. * - * @param assets The {@link DeviceAsset} {@link List}. + * @param assets + * The {@link DeviceAsset} {@link List}. * @since 1.0.0 */ - void setAssets(List assets); + public void setAssets(List assets) { + this.assets = assets; + } } diff --git a/service/device/management/asset/api/src/main/java/org/eclipse/kapua/service/device/management/asset/xml/DeviceAssetChannelXmlAdapter.java b/service/device/management/asset/api/src/main/java/org/eclipse/kapua/service/device/management/asset/xml/DeviceAssetChannelXmlAdapter.java index 7d81f6cff21..ffadbc2d8bd 100644 --- a/service/device/management/asset/api/src/main/java/org/eclipse/kapua/service/device/management/asset/xml/DeviceAssetChannelXmlAdapter.java +++ b/service/device/management/asset/api/src/main/java/org/eclipse/kapua/service/device/management/asset/xml/DeviceAssetChannelXmlAdapter.java @@ -12,12 +12,10 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.asset.xml; -import org.eclipse.kapua.locator.KapuaLocator; +import javax.xml.bind.annotation.adapters.XmlAdapter; + import org.eclipse.kapua.model.type.ObjectValueConverter; import org.eclipse.kapua.service.device.management.asset.DeviceAssetChannel; -import org.eclipse.kapua.service.device.management.asset.DeviceAssetFactory; - -import javax.xml.bind.annotation.adapters.XmlAdapter; /** * {@link DeviceAssetChannel} {@link XmlAdapter} implementation. @@ -27,8 +25,6 @@ */ public class DeviceAssetChannelXmlAdapter extends XmlAdapter { - private final DeviceAssetFactory deviceAssetFactory = KapuaLocator.getInstance().getFactory(DeviceAssetFactory.class); - @Override public XmlAdaptedDeviceAssetChannel marshal(DeviceAssetChannel deviceAssetChannel) throws Exception { @@ -46,7 +42,7 @@ public XmlAdaptedDeviceAssetChannel marshal(DeviceAssetChannel deviceAssetChanne @Override public DeviceAssetChannel unmarshal(XmlAdaptedDeviceAssetChannel xmlAdaptedDeviceAssetChannel) throws Exception { - DeviceAssetChannel adaptedDeviceAssetChannel = deviceAssetFactory.newDeviceAssetChannel(); + DeviceAssetChannel adaptedDeviceAssetChannel = new DeviceAssetChannel(); adaptedDeviceAssetChannel.setName(xmlAdaptedDeviceAssetChannel.getName()); adaptedDeviceAssetChannel.setType(xmlAdaptedDeviceAssetChannel.getValueType()); adaptedDeviceAssetChannel.setValue(ObjectValueConverter.fromString(xmlAdaptedDeviceAssetChannel.getValue(), adaptedDeviceAssetChannel.getType())); diff --git a/service/device/management/asset/internal/pom.xml b/service/device/management/asset/internal/pom.xml index 51102f7d007..5161bc0d943 100644 --- a/service/device/management/asset/internal/pom.xml +++ b/service/device/management/asset/internal/pom.xml @@ -19,7 +19,7 @@ org.eclipse.kapua kapua-device-management-asset - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-device-management-asset-internal diff --git a/service/device/management/asset/internal/src/main/java/org/eclipse/kapua/service/device/management/asset/internal/DeviceAssetChannelImpl.java b/service/device/management/asset/internal/src/main/java/org/eclipse/kapua/service/device/management/asset/internal/DeviceAssetChannelImpl.java deleted file mode 100644 index cd35241a5cd..00000000000 --- a/service/device/management/asset/internal/src/main/java/org/eclipse/kapua/service/device/management/asset/internal/DeviceAssetChannelImpl.java +++ /dev/null @@ -1,105 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.asset.internal; - -import org.eclipse.kapua.service.device.management.asset.DeviceAssetChannel; -import org.eclipse.kapua.service.device.management.asset.DeviceAssetChannelMode; - -import java.util.Date; - -/** - * {@link DeviceAssetChannel} implementation. - * - * @since 1.0.0 - */ -public class DeviceAssetChannelImpl implements DeviceAssetChannel { - - private String name; - private Class clazz; - private DeviceAssetChannelMode mode; - private Object value; - private String error; - private Date timestamp; - - /** - * Constructor. - * - * @since 1.0.0 - */ - public DeviceAssetChannelImpl() { - } - - @Override - public String getName() { - return name; - } - - @Override - public void setName(String name) { - this.name = name; - } - - @Override - public Class getType() { - return clazz; - } - - @Override - public void setType(Class clazz) { - this.clazz = clazz; - } - - @Override - public DeviceAssetChannelMode getMode() { - return mode; - } - - @Override - public void setMode(DeviceAssetChannelMode mode) { - this.mode = mode; - } - - @Override - public Object getValue() { - return value; - } - - @Override - public void setValue(Object value) { - this.value = value; - - if (value != null) { - setType(value.getClass()); - } - } - - @Override - public String getError() { - return error; - } - - @Override - public void setError(String error) { - this.error = error; - } - - @Override - public Date getTimestamp() { - return timestamp; - } - - @Override - public void setTimestamp(Date timestamp) { - this.timestamp = timestamp; - } -} diff --git a/service/device/management/asset/internal/src/main/java/org/eclipse/kapua/service/device/management/asset/internal/DeviceAssetFactoryImpl.java b/service/device/management/asset/internal/src/main/java/org/eclipse/kapua/service/device/management/asset/internal/DeviceAssetFactoryImpl.java deleted file mode 100644 index 50dc4e9a9b7..00000000000 --- a/service/device/management/asset/internal/src/main/java/org/eclipse/kapua/service/device/management/asset/internal/DeviceAssetFactoryImpl.java +++ /dev/null @@ -1,44 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.asset.internal; - -import org.eclipse.kapua.service.device.management.asset.DeviceAsset; -import org.eclipse.kapua.service.device.management.asset.DeviceAssetChannel; -import org.eclipse.kapua.service.device.management.asset.DeviceAssetFactory; -import org.eclipse.kapua.service.device.management.asset.DeviceAssets; - -import javax.inject.Singleton; - -/** - * {@link DeviceAssetFactory} implementation. - * - * @since 1.0.0 - */ -@Singleton -public class DeviceAssetFactoryImpl implements DeviceAssetFactory { - - @Override - public DeviceAssets newAssetListResult() { - return new DeviceAssetsImpl(); - } - - @Override - public DeviceAsset newDeviceAsset() { - return new DeviceAssetImpl(); - } - - @Override - public DeviceAssetChannel newDeviceAssetChannel() { - return new DeviceAssetChannelImpl(); - } -} diff --git a/service/device/management/asset/internal/src/main/java/org/eclipse/kapua/service/device/management/asset/internal/DeviceAssetImpl.java b/service/device/management/asset/internal/src/main/java/org/eclipse/kapua/service/device/management/asset/internal/DeviceAssetImpl.java deleted file mode 100644 index a0ac7a61cb1..00000000000 --- a/service/device/management/asset/internal/src/main/java/org/eclipse/kapua/service/device/management/asset/internal/DeviceAssetImpl.java +++ /dev/null @@ -1,62 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.asset.internal; - -import org.eclipse.kapua.service.device.management.asset.DeviceAsset; -import org.eclipse.kapua.service.device.management.asset.DeviceAssetChannel; - -import java.util.ArrayList; -import java.util.List; - -/** - * {@link DeviceAsset} implementation. - * - * @since 1.0.0 - */ -public class DeviceAssetImpl implements DeviceAsset { - - private String name; - private List channels; - - /** - * Constructor. - * - * @since 1.0.0 - */ - public DeviceAssetImpl() { - } - - @Override - public String getName() { - return name; - } - - @Override - public void setName(String name) { - this.name = name; - } - - @Override - public List getChannels() { - if (channels == null) { - channels = new ArrayList<>(); - } - - return channels; - } - - @Override - public void setChannels(List channels) { - this.channels = channels; - } -} diff --git a/service/device/management/asset/internal/src/main/java/org/eclipse/kapua/service/device/management/asset/internal/DeviceAssetManagementServiceImpl.java b/service/device/management/asset/internal/src/main/java/org/eclipse/kapua/service/device/management/asset/internal/DeviceAssetManagementServiceImpl.java index a0ef5363703..d65097d48f7 100644 --- a/service/device/management/asset/internal/src/main/java/org/eclipse/kapua/service/device/management/asset/internal/DeviceAssetManagementServiceImpl.java +++ b/service/device/management/asset/internal/src/main/java/org/eclipse/kapua/service/device/management/asset/internal/DeviceAssetManagementServiceImpl.java @@ -12,14 +12,17 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.asset.internal; +import java.util.Date; + +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.commons.model.domains.Domains; import org.eclipse.kapua.commons.util.ArgumentValidator; import org.eclipse.kapua.model.domain.Actions; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; -import org.eclipse.kapua.service.device.management.asset.DeviceAssetFactory; +import org.eclipse.kapua.service.authorization.permission.Permission; import org.eclipse.kapua.service.device.management.asset.DeviceAssetManagementService; import org.eclipse.kapua.service.device.management.asset.DeviceAssets; import org.eclipse.kapua.service.device.management.asset.message.internal.AssetRequestChannel; @@ -39,9 +42,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.inject.Singleton; -import java.util.Date; - /** * {@link DeviceAssetManagementService} implementation. * @@ -57,24 +57,20 @@ public class DeviceAssetManagementServiceImpl extends AbstractDeviceManagementTr private static final String DEVICE_ASSETS = "deviceAssets"; private final DeviceAssetStoreService deviceAssetStoreService; - private final DeviceAssetFactory deviceAssetFactory; public DeviceAssetManagementServiceImpl( TxManager txManager, AuthorizationService authorizationService, - PermissionFactory permissionFactory, DeviceEventService deviceEventService, DeviceEventFactory deviceEventFactory, DeviceRegistryService deviceRegistryService, - DeviceAssetStoreService deviceAssetStoreService, DeviceAssetFactory deviceAssetFactory) { + DeviceAssetStoreService deviceAssetStoreService) { super(txManager, authorizationService, - permissionFactory, deviceEventService, deviceEventFactory, deviceRegistryService); this.deviceAssetStoreService = deviceAssetStoreService; - this.deviceAssetFactory = deviceAssetFactory; } @Override @@ -85,7 +81,7 @@ public DeviceAssets get(KapuaId scopeId, KapuaId deviceId, DeviceAssets deviceAs ArgumentValidator.notNull(deviceId, DEVICE_ID); ArgumentValidator.notNull(deviceAssets, DEVICE_ASSETS); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE_MANAGEMENT, Actions.read, scopeId)); + authorizationService.checkPermission(new Permission(Domains.DEVICE_MANAGEMENT, Actions.read, scopeId)); // Prepare the request AssetRequestChannel assetRequestChannel = new AssetRequestChannel(); assetRequestChannel.setAppName(DeviceAssetAppProperties.APP_NAME); @@ -126,7 +122,7 @@ public DeviceAssets get(KapuaId scopeId, KapuaId deviceId, DeviceAssets deviceAs // Create event createDeviceEvent(scopeId, deviceId, assetRequestMessage, responseMessage); // Check response - DeviceAssets onlineDeviceAssets = checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getDeviceAssets().orElse(deviceAssetFactory.newAssetListResult())); + DeviceAssets onlineDeviceAssets = checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getDeviceAssets().orElse(new DeviceAssets())); // Store value and return if (deviceAssetStoreService.isServiceEnabled(scopeId) && deviceAssetStoreService.isApplicationEnabled(scopeId, deviceId)) { @@ -150,7 +146,7 @@ public DeviceAssets read(KapuaId scopeId, KapuaId deviceId, DeviceAssets deviceA ArgumentValidator.notNull(deviceId, DEVICE_ID); ArgumentValidator.notNull(deviceAssets, DEVICE_ASSETS); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE_MANAGEMENT, Actions.read, scopeId)); + authorizationService.checkPermission(new Permission(Domains.DEVICE_MANAGEMENT, Actions.read, scopeId)); // Prepare the request AssetRequestChannel assetRequestChannel = new AssetRequestChannel(); assetRequestChannel.setAppName(DeviceAssetAppProperties.APP_NAME); @@ -192,7 +188,7 @@ public DeviceAssets read(KapuaId scopeId, KapuaId deviceId, DeviceAssets deviceA // Create event createDeviceEvent(scopeId, deviceId, assetRequestMessage, responseMessage); // Check response - DeviceAssets onlineDeviceAssets = checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getDeviceAssets().orElse(deviceAssetFactory.newAssetListResult())); + DeviceAssets onlineDeviceAssets = checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getDeviceAssets().orElse(new DeviceAssets())); // Store value and return if (deviceAssetStoreService.isServiceEnabled(scopeId) && deviceAssetStoreService.isApplicationEnabled(scopeId, deviceId)) { @@ -217,7 +213,7 @@ public DeviceAssets write(KapuaId scopeId, KapuaId deviceId, DeviceAssets device ArgumentValidator.notNull(deviceId, DEVICE_ID); ArgumentValidator.notNull(deviceAssets, DEVICE_ASSETS); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE_MANAGEMENT, Actions.write, scopeId)); + authorizationService.checkPermission(new Permission(Domains.DEVICE_MANAGEMENT, Actions.write, scopeId)); // Prepare the request AssetRequestChannel assetRequestChannel = new AssetRequestChannel(); assetRequestChannel.setAppName(DeviceAssetAppProperties.APP_NAME); @@ -258,6 +254,6 @@ public DeviceAssets write(KapuaId scopeId, KapuaId deviceId, DeviceAssets device // Create event createDeviceEvent(scopeId, deviceId, assetRequestMessage, responseMessage); // Check response - return checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getDeviceAssets().orElse(deviceAssetFactory.newAssetListResult())); + return checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getDeviceAssets().orElse(new DeviceAssets())); } } diff --git a/service/device/management/asset/internal/src/main/java/org/eclipse/kapua/service/device/management/asset/internal/DeviceAssetsImpl.java b/service/device/management/asset/internal/src/main/java/org/eclipse/kapua/service/device/management/asset/internal/DeviceAssetsImpl.java deleted file mode 100644 index 997e09c0bf5..00000000000 --- a/service/device/management/asset/internal/src/main/java/org/eclipse/kapua/service/device/management/asset/internal/DeviceAssetsImpl.java +++ /dev/null @@ -1,45 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.asset.internal; - -import org.eclipse.kapua.service.device.management.asset.DeviceAsset; -import org.eclipse.kapua.service.device.management.asset.DeviceAssets; - -import java.util.ArrayList; -import java.util.List; - -/** - * {@link DeviceAssets} implementation. - * - * @since 1.0.0 - */ -public class DeviceAssetsImpl implements DeviceAssets { - - private static final long serialVersionUID = -6657213220333406876L; - - private List assets; - - @Override - public List getAssets() { - if (assets == null) { - assets = new ArrayList<>(); - } - - return assets; - } - - @Override - public void setAssets(List assets) { - this.assets = assets; - } -} diff --git a/service/device/management/asset/internal/src/main/java/org/eclipse/kapua/service/device/management/asset/internal/DeviceManagementAssetModule.java b/service/device/management/asset/internal/src/main/java/org/eclipse/kapua/service/device/management/asset/internal/DeviceManagementAssetModule.java index f008d48bd73..e00f80e2a3e 100644 --- a/service/device/management/asset/internal/src/main/java/org/eclipse/kapua/service/device/management/asset/internal/DeviceManagementAssetModule.java +++ b/service/device/management/asset/internal/src/main/java/org/eclipse/kapua/service/device/management/asset/internal/DeviceManagementAssetModule.java @@ -17,8 +17,6 @@ import org.eclipse.kapua.commons.core.SimpleJaxbClassProvider; import org.eclipse.kapua.commons.jpa.KapuaJpaTxManagerFactory; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; -import org.eclipse.kapua.service.device.management.asset.DeviceAssetFactory; import org.eclipse.kapua.service.device.management.asset.DeviceAssetManagementService; import org.eclipse.kapua.service.device.management.asset.store.DeviceAssetStoreService; import org.eclipse.kapua.service.device.management.message.request.KapuaRequestMessage; @@ -36,7 +34,6 @@ public class DeviceManagementAssetModule extends AbstractKapuaModule { @Override protected void configureModule() { - bind(DeviceAssetFactory.class).to(DeviceAssetFactoryImpl.class); final Multibinder jaxbClassProviderMultibinder = Multibinder.newSetBinder(binder(), JaxbClassProvider.class); jaxbClassProviderMultibinder.addBinding() .toInstance(new SimpleJaxbClassProvider( @@ -50,21 +47,17 @@ protected void configureModule() { @Provides @Singleton DeviceAssetManagementService deviceAssetManagementService(AuthorizationService authorizationService, - PermissionFactory permissionFactory, DeviceEventService deviceEventService, DeviceEventFactory deviceEventFactory, DeviceRegistryService deviceRegistryService, DeviceAssetStoreService deviceAssetStoreService, - KapuaJpaTxManagerFactory jpaTxManagerFactory, - DeviceAssetFactory deviceAssetFactory) { + KapuaJpaTxManagerFactory jpaTxManagerFactory) { return new DeviceAssetManagementServiceImpl( jpaTxManagerFactory.create("kapua-device_management_operation_registry"), authorizationService, - permissionFactory, deviceEventService, deviceEventFactory, deviceRegistryService, - deviceAssetStoreService, - deviceAssetFactory); + deviceAssetStoreService); } } diff --git a/service/device/management/asset/job/pom.xml b/service/device/management/asset/job/pom.xml index a0d42a046f7..5ef58ededbf 100644 --- a/service/device/management/asset/job/pom.xml +++ b/service/device/management/asset/job/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-device-management-asset - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-device-management-asset-job diff --git a/service/device/management/asset/pom.xml b/service/device/management/asset/pom.xml index 74fad02b933..9908e693727 100644 --- a/service/device/management/asset/pom.xml +++ b/service/device/management/asset/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-device-management - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT pom diff --git a/service/device/management/bundle/api/pom.xml b/service/device/management/bundle/api/pom.xml index be5878a2869..8d443cc3331 100644 --- a/service/device/management/bundle/api/pom.xml +++ b/service/device/management/bundle/api/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-device-management-bundle - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-device-management-bundle-api diff --git a/service/device/management/bundle/api/src/main/java/org/eclipse/kapua/service/device/management/bundle/DeviceBundle.java b/service/device/management/bundle/api/src/main/java/org/eclipse/kapua/service/device/management/bundle/DeviceBundle.java index efd1cfd726d..4485dc4cab5 100644 --- a/service/device/management/bundle/api/src/main/java/org/eclipse/kapua/service/device/management/bundle/DeviceBundle.java +++ b/service/device/management/bundle/api/src/main/java/org/eclipse/kapua/service/device/management/bundle/DeviceBundle.java @@ -26,9 +26,14 @@ * @since 1.0.0 */ @XmlRootElement(name = "bundle") -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(factoryClass = DeviceBundleXmlRegistry.class, factoryMethod = "newDeviceBundle") -public interface DeviceBundle { +@XmlAccessorType(XmlAccessType.PROPERTY) +@XmlType +public class DeviceBundle { + + public long id; + public String name; + public String version; + public String state; /** * Gets the bundle identifier. @@ -37,15 +42,20 @@ public interface DeviceBundle { * @since 1.0.0 */ @XmlElement(name = "id") - long getId(); + public long getId() { + return id; + } /** * Sets the bundle identifier. * - * @param id The bundle identifier. + * @param id + * The bundle identifier. * @since 1.0.0 */ - void setId(long id); + public void setId(long id) { + this.id = id; + } /** * Gets the name. @@ -54,15 +64,20 @@ public interface DeviceBundle { * @since 1.0.0 */ @XmlElement(name = "name") - String getName(); + public String getName() { + return name; + } /** * Sets the name. * - * @param name The name. + * @param name + * The name. * @since 1.0.0 */ - void setName(String name); + public void setName(String name) { + this.name = name; + } /** * Gets the state. @@ -71,15 +86,20 @@ public interface DeviceBundle { * @since 1.0.0 */ @XmlElement(name = "state") - String getState(); + public String getState() { + return state; + } /** * Sets the state. * - * @param state The state. + * @param state + * The state. * @since 1.0.0 */ - void setState(String state); + public void setState(String state) { + this.state = state; + } /** * Gets the bundle version. @@ -88,14 +108,19 @@ public interface DeviceBundle { * @since 1.0.0 */ @XmlElement(name = "version") - String getVersion(); + public String getVersion() { + return version; + } /** * Sets the version. * - * @param version The version. + * @param version + * The version. * @since 1.0.0 */ - void setVersion(String version); + public void setVersion(String version) { + this.version = version; + } } diff --git a/service/device/management/bundle/api/src/main/java/org/eclipse/kapua/service/device/management/bundle/DeviceBundleFactory.java b/service/device/management/bundle/api/src/main/java/org/eclipse/kapua/service/device/management/bundle/DeviceBundleFactory.java deleted file mode 100644 index 4c1d7f75406..00000000000 --- a/service/device/management/bundle/api/src/main/java/org/eclipse/kapua/service/device/management/bundle/DeviceBundleFactory.java +++ /dev/null @@ -1,37 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.bundle; - -import org.eclipse.kapua.model.KapuaObjectFactory; - -/** - * Device bundle entity service factory definition. - * - * @since 1.0 - */ -public interface DeviceBundleFactory extends KapuaObjectFactory { - - /** - * Creates a new device bundle list - * - * @return - */ - DeviceBundles newBundleListResult(); - - /** - * Create a new {@link DeviceBundle} - * - * @return - */ - DeviceBundle newDeviceBundle(); -} diff --git a/service/device/management/bundle/api/src/main/java/org/eclipse/kapua/service/device/management/bundle/DeviceBundleXmlRegistry.java b/service/device/management/bundle/api/src/main/java/org/eclipse/kapua/service/device/management/bundle/DeviceBundleXmlRegistry.java deleted file mode 100644 index 7f3f23f15b5..00000000000 --- a/service/device/management/bundle/api/src/main/java/org/eclipse/kapua/service/device/management/bundle/DeviceBundleXmlRegistry.java +++ /dev/null @@ -1,44 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.bundle; - -import org.eclipse.kapua.locator.KapuaLocator; - -/** - * Device bundle xml factory class - * - * @since 1.0 - */ -public class DeviceBundleXmlRegistry { - - private final KapuaLocator locator = KapuaLocator.getInstance(); - private final DeviceBundleFactory factory = locator.getFactory(DeviceBundleFactory.class); - - /** - * Creates a new device bundles list - * - * @return - */ - public DeviceBundles newBundleListResult() { - return factory.newBundleListResult(); - } - - /** - * Creates a new device bundle - * - * @return - */ - public DeviceBundle newDeviceBundle() { - return factory.newDeviceBundle(); - } -} diff --git a/service/device/management/bundle/api/src/main/java/org/eclipse/kapua/service/device/management/bundle/DeviceBundles.java b/service/device/management/bundle/api/src/main/java/org/eclipse/kapua/service/device/management/bundle/DeviceBundles.java index ad0f9e00e83..1f9b71f40d9 100644 --- a/service/device/management/bundle/api/src/main/java/org/eclipse/kapua/service/device/management/bundle/DeviceBundles.java +++ b/service/device/management/bundle/api/src/main/java/org/eclipse/kapua/service/device/management/bundle/DeviceBundles.java @@ -13,21 +13,27 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.bundle; -import org.eclipse.kapua.KapuaSerializable; +import java.util.ArrayList; +import java.util.List; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; -import java.util.List; + +import org.eclipse.kapua.KapuaSerializable; /** * {@link DeviceBundles} definition. * * @since 1.0.0 */ -@XmlType(factoryClass = DeviceBundleXmlRegistry.class, factoryMethod = "newBundleListResult") +@XmlType @XmlRootElement(name = "bundles") -public interface DeviceBundles extends KapuaSerializable { +public class DeviceBundles implements KapuaSerializable { + + private static final long serialVersionUID = 734716753080998855L; + + private List bundles; /** * Gets the {@link List} of {@link DeviceBundle} @@ -36,5 +42,11 @@ public interface DeviceBundles extends KapuaSerializable { * @since 1.0.0 */ @XmlElement(name = "bundle") - List getBundles(); + public List getBundles() { + if (bundles == null) { + bundles = new ArrayList<>(); + } + + return bundles; + } } diff --git a/service/device/management/bundle/internal/pom.xml b/service/device/management/bundle/internal/pom.xml index 35dde25a651..dca60e6a0bb 100644 --- a/service/device/management/bundle/internal/pom.xml +++ b/service/device/management/bundle/internal/pom.xml @@ -19,7 +19,7 @@ org.eclipse.kapua kapua-device-management-bundle - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-device-management-bundle-internal diff --git a/service/device/management/bundle/internal/src/main/java/org/eclipse/kapua/service/device/management/bundle/internal/DeviceBundleFactoryImpl.java b/service/device/management/bundle/internal/src/main/java/org/eclipse/kapua/service/device/management/bundle/internal/DeviceBundleFactoryImpl.java deleted file mode 100644 index d2d89d150a5..00000000000 --- a/service/device/management/bundle/internal/src/main/java/org/eclipse/kapua/service/device/management/bundle/internal/DeviceBundleFactoryImpl.java +++ /dev/null @@ -1,40 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.bundle.internal; - -import org.eclipse.kapua.service.device.management.bundle.DeviceBundle; -import org.eclipse.kapua.service.device.management.bundle.DeviceBundleFactory; -import org.eclipse.kapua.service.device.management.bundle.DeviceBundles; - -import javax.inject.Singleton; - -/** - * Device bundle entity service factory implementation. - * - * @since 1.0 - * - */ -@Singleton -public class DeviceBundleFactoryImpl implements DeviceBundleFactory { - - @Override - public DeviceBundles newBundleListResult() { - return new DeviceBundlesImpl(); - } - - @Override - public DeviceBundle newDeviceBundle() { - return new DeviceBundleImpl(); - } - -} diff --git a/service/device/management/bundle/internal/src/main/java/org/eclipse/kapua/service/device/management/bundle/internal/DeviceBundleImpl.java b/service/device/management/bundle/internal/src/main/java/org/eclipse/kapua/service/device/management/bundle/internal/DeviceBundleImpl.java deleted file mode 100644 index bb6a5af5ca7..00000000000 --- a/service/device/management/bundle/internal/src/main/java/org/eclipse/kapua/service/device/management/bundle/internal/DeviceBundleImpl.java +++ /dev/null @@ -1,76 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.bundle.internal; - -import org.eclipse.kapua.service.device.management.bundle.DeviceBundle; - -/** - * {@link DeviceBundle} implementation. - * - * @since 1.0.0 - */ -public class DeviceBundleImpl implements DeviceBundle { - - public long id; - public String name; - public String version; - public String state; - - /** - * Constructor. - * - * @since 1.0.0 - */ - public DeviceBundleImpl() { - } - - @Override - public long getId() { - return id; - } - - @Override - public void setId(long id) { - this.id = id; - } - - @Override - public String getName() { - return name; - } - - @Override - public void setName(String name) { - this.name = name; - } - - @Override - public String getVersion() { - return version; - } - - @Override - public void setVersion(String version) { - this.version = version; - } - - @Override - public String getState() { - return state; - } - - @Override - public void setState(String state) { - this.state = state; - } -} diff --git a/service/device/management/bundle/internal/src/main/java/org/eclipse/kapua/service/device/management/bundle/internal/DeviceBundleManagementServiceImpl.java b/service/device/management/bundle/internal/src/main/java/org/eclipse/kapua/service/device/management/bundle/internal/DeviceBundleManagementServiceImpl.java index 7b8055747a8..647b408745e 100644 --- a/service/device/management/bundle/internal/src/main/java/org/eclipse/kapua/service/device/management/bundle/internal/DeviceBundleManagementServiceImpl.java +++ b/service/device/management/bundle/internal/src/main/java/org/eclipse/kapua/service/device/management/bundle/internal/DeviceBundleManagementServiceImpl.java @@ -13,14 +13,17 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.bundle.internal; +import java.util.Date; + +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.commons.model.domains.Domains; import org.eclipse.kapua.commons.util.ArgumentValidator; import org.eclipse.kapua.model.domain.Actions; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; -import org.eclipse.kapua.service.device.management.bundle.DeviceBundleFactory; +import org.eclipse.kapua.service.authorization.permission.Permission; import org.eclipse.kapua.service.device.management.bundle.DeviceBundleManagementService; import org.eclipse.kapua.service.device.management.bundle.DeviceBundles; import org.eclipse.kapua.service.device.management.bundle.message.internal.BundleRequestChannel; @@ -37,9 +40,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.inject.Singleton; -import java.util.Date; - /** * DeviceBundleManagementService implementation. * @@ -53,21 +53,16 @@ public class DeviceBundleManagementServiceImpl extends AbstractDeviceManagementT private static final String SCOPE_ID = "scopeId"; private static final String DEVICE_ID = "deviceId"; - private final DeviceBundleFactory deviceBundleFactory; - public DeviceBundleManagementServiceImpl(TxManager txManager, - AuthorizationService authorizationService, - PermissionFactory permissionFactory, - DeviceEventService deviceEventService, - DeviceEventFactory deviceEventFactory, - DeviceRegistryService deviceRegistryService, DeviceBundleFactory deviceBundleFactory) { + AuthorizationService authorizationService, + DeviceEventService deviceEventService, + DeviceEventFactory deviceEventFactory, + DeviceRegistryService deviceRegistryService) { super(txManager, authorizationService, - permissionFactory, deviceEventService, deviceEventFactory, deviceRegistryService); - this.deviceBundleFactory = deviceBundleFactory; } @Override @@ -77,7 +72,7 @@ public DeviceBundles get(KapuaId scopeId, KapuaId deviceId, Long timeout) ArgumentValidator.notNull(scopeId, SCOPE_ID); ArgumentValidator.notNull(deviceId, DEVICE_ID); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE_MANAGEMENT, Actions.read, scopeId)); + authorizationService.checkPermission(new Permission(Domains.DEVICE_MANAGEMENT, Actions.read, scopeId)); // Prepare the request BundleRequestChannel bundleRequestChannel = new BundleRequestChannel(); bundleRequestChannel.setAppName(DeviceBundleAppProperties.APP_NAME); @@ -113,7 +108,7 @@ public DeviceBundles get(KapuaId scopeId, KapuaId deviceId, Long timeout) // Create event createDeviceEvent(scopeId, deviceId, bundleRequestMessage, responseMessage); // Check response - return checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getDeviceBundles().orElse(deviceBundleFactory.newBundleListResult())); + return checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getDeviceBundles().orElse(new DeviceBundles())); } @Override @@ -124,7 +119,7 @@ public void start(KapuaId scopeId, KapuaId deviceId, String bundleId, Long timeo ArgumentValidator.notNull(deviceId, DEVICE_ID); ArgumentValidator.notEmptyOrNull(bundleId, "bundleId"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE_MANAGEMENT, Actions.execute, scopeId)); + authorizationService.checkPermission(new Permission(Domains.DEVICE_MANAGEMENT, Actions.execute, scopeId)); // Prepare the request BundleRequestChannel bundleRequestChannel = new BundleRequestChannel(); bundleRequestChannel.setAppName(DeviceBundleAppProperties.APP_NAME); @@ -172,7 +167,7 @@ public void stop(KapuaId scopeId, KapuaId deviceId, String bundleId, Long timeou ArgumentValidator.notNull(deviceId, DEVICE_ID); ArgumentValidator.notEmptyOrNull(bundleId, "bundleId"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE_MANAGEMENT, Actions.execute, scopeId)); + authorizationService.checkPermission(new Permission(Domains.DEVICE_MANAGEMENT, Actions.execute, scopeId)); // Prepare the request BundleRequestChannel bundleRequestChannel = new BundleRequestChannel(); bundleRequestChannel.setAppName(DeviceBundleAppProperties.APP_NAME); diff --git a/service/device/management/bundle/internal/src/main/java/org/eclipse/kapua/service/device/management/bundle/internal/DeviceBundlesImpl.java b/service/device/management/bundle/internal/src/main/java/org/eclipse/kapua/service/device/management/bundle/internal/DeviceBundlesImpl.java deleted file mode 100644 index d6fb276dbbd..00000000000 --- a/service/device/management/bundle/internal/src/main/java/org/eclipse/kapua/service/device/management/bundle/internal/DeviceBundlesImpl.java +++ /dev/null @@ -1,41 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - * Red Hat Inc - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.bundle.internal; - -import org.eclipse.kapua.service.device.management.bundle.DeviceBundle; -import org.eclipse.kapua.service.device.management.bundle.DeviceBundles; - -import java.util.ArrayList; -import java.util.List; - -/** - * {@link DeviceBundles} implementation. - * - * @since 1.0.0 - */ -public class DeviceBundlesImpl implements DeviceBundles { - - private static final long serialVersionUID = 734716753080998855L; - - private List bundles; - - @Override - public List getBundles() { - if (bundles == null) { - bundles = new ArrayList<>(); - } - - return bundles; - } -} diff --git a/service/device/management/bundle/internal/src/main/java/org/eclipse/kapua/service/device/management/bundle/internal/DeviceManagementBundleModule.java b/service/device/management/bundle/internal/src/main/java/org/eclipse/kapua/service/device/management/bundle/internal/DeviceManagementBundleModule.java index 9afc230f641..c8a9d0767e3 100644 --- a/service/device/management/bundle/internal/src/main/java/org/eclipse/kapua/service/device/management/bundle/internal/DeviceManagementBundleModule.java +++ b/service/device/management/bundle/internal/src/main/java/org/eclipse/kapua/service/device/management/bundle/internal/DeviceManagementBundleModule.java @@ -12,8 +12,8 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.bundle.internal; -import com.google.inject.Provides; -import com.google.inject.multibindings.ProvidesIntoSet; +import javax.inject.Singleton; + import org.eclipse.kapua.commons.core.AbstractKapuaModule; import org.eclipse.kapua.commons.jpa.KapuaJpaTxManagerFactory; import org.eclipse.kapua.commons.model.domains.Domains; @@ -21,20 +21,19 @@ import org.eclipse.kapua.model.domain.Domain; import org.eclipse.kapua.model.domain.DomainEntry; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; import org.eclipse.kapua.service.device.management.DeviceManagementService; -import org.eclipse.kapua.service.device.management.bundle.DeviceBundleFactory; import org.eclipse.kapua.service.device.management.bundle.DeviceBundleManagementService; import org.eclipse.kapua.service.device.registry.DeviceRegistryService; import org.eclipse.kapua.service.device.registry.event.DeviceEventFactory; import org.eclipse.kapua.service.device.registry.event.DeviceEventService; -import javax.inject.Singleton; +import com.google.inject.Provides; +import com.google.inject.multibindings.ProvidesIntoSet; public class DeviceManagementBundleModule extends AbstractKapuaModule { + @Override protected void configureModule() { - bind(DeviceBundleFactory.class).to(DeviceBundleFactoryImpl.class); } @ProvidesIntoSet @@ -46,19 +45,16 @@ public Domain deviceManagementModule() { @Singleton DeviceBundleManagementService deviceBundleManagementService( AuthorizationService authorizationService, - PermissionFactory permissionFactory, DeviceEventService deviceEventService, DeviceEventFactory deviceEventFactory, DeviceRegistryService deviceRegistryService, - KapuaJpaTxManagerFactory jpaTxManagerFactory, - DeviceBundleFactory deviceBundleFactory) { + KapuaJpaTxManagerFactory jpaTxManagerFactory) { return new DeviceBundleManagementServiceImpl( jpaTxManagerFactory.create("kapua-device_management_operation_registry"), authorizationService, - permissionFactory, deviceEventService, deviceEventFactory, - deviceRegistryService, - deviceBundleFactory); + deviceRegistryService + ); } } diff --git a/service/device/management/bundle/job/pom.xml b/service/device/management/bundle/job/pom.xml index 445f44576a1..2cef4effe85 100644 --- a/service/device/management/bundle/job/pom.xml +++ b/service/device/management/bundle/job/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-device-management-bundle - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-device-management-bundle-job diff --git a/service/device/management/bundle/pom.xml b/service/device/management/bundle/pom.xml index 10374e816fe..7ce446dd342 100644 --- a/service/device/management/bundle/pom.xml +++ b/service/device/management/bundle/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-device-management - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT pom diff --git a/service/device/management/command/api/pom.xml b/service/device/management/command/api/pom.xml index fee3316fee6..89a926bd449 100644 --- a/service/device/management/command/api/pom.xml +++ b/service/device/management/command/api/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-device-management-command - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-device-management-command-api diff --git a/service/device/management/command/api/src/main/java/org/eclipse/kapua/service/device/management/command/DeviceCommandFactory.java b/service/device/management/command/api/src/main/java/org/eclipse/kapua/service/device/management/command/DeviceCommandFactory.java deleted file mode 100644 index 612f18a7688..00000000000 --- a/service/device/management/command/api/src/main/java/org/eclipse/kapua/service/device/management/command/DeviceCommandFactory.java +++ /dev/null @@ -1,39 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.command; - -import org.eclipse.kapua.model.KapuaObjectFactory; - -/** - * {@link DeviceCommand} {@link KapuaObjectFactory} definition. - * - * @since 1.0.0 - */ -public interface DeviceCommandFactory extends KapuaObjectFactory { - - /** - * Instantiates a new {@link DeviceCommandInput}. - * - * @return The newly instantiated {@link DeviceCommandInput}. - * @since 1.0.0 - */ - DeviceCommandInput newCommandInput(); - - /** - * Instantiates a new {@link DeviceCommandOutput}. - * - * @return The newly instantiated {@link DeviceCommandOutput}. - * @since 1.0.0 - */ - DeviceCommandOutput newCommandOutput(); -} diff --git a/service/device/management/command/api/src/main/java/org/eclipse/kapua/service/device/management/command/DeviceCommandInput.java b/service/device/management/command/api/src/main/java/org/eclipse/kapua/service/device/management/command/DeviceCommandInput.java index 936c375d5c2..008e3bbe2f8 100644 --- a/service/device/management/command/api/src/main/java/org/eclipse/kapua/service/device/management/command/DeviceCommandInput.java +++ b/service/device/management/command/api/src/main/java/org/eclipse/kapua/service/device/management/command/DeviceCommandInput.java @@ -36,8 +36,20 @@ "environment", "runAsynch", "stdin" -}, factoryClass = DeviceCommandXmlRegistry.class, factoryMethod = "newCommandInput") -public interface DeviceCommandInput extends DeviceCommand { +}) +public class DeviceCommandInput implements DeviceCommand { + + private static final long serialVersionUID = -2141178091281947848L; + + private String command; + private String password; + private String[] arguments; + private Integer timeout; + private String workingDir; + private byte[] body; + private String[] envVars; + private boolean runAsync; + private String stdIn; /** * Get the device command @@ -45,14 +57,18 @@ public interface DeviceCommandInput extends DeviceCommand { * @return */ @XmlElement(name = "command") - String getCommand(); + public String getCommand() { + return command; + } /** * Set the device command * * @param command */ - void setCommand(String command); + public void setCommand(String command) { + this.command = command; + } /** * Get the device password @@ -60,14 +76,18 @@ public interface DeviceCommandInput extends DeviceCommand { * @return */ @XmlElement(name = "password") - String getPassword(); + public String getPassword() { + return password; + } /** * Set the device password * * @param password */ - void setPassword(String password); + public void setPassword(String password) { + this.password = password; + } /** * Get command arguments @@ -76,14 +96,18 @@ public interface DeviceCommandInput extends DeviceCommand { */ @XmlElementWrapper(name = "arguments") @XmlElement(name = "argument") - String[] getArguments(); + public String[] getArguments() { + return arguments; + } /** * Set command arguments * * @param arguments */ - void setArguments(String[] arguments); + public void setArguments(String[] arguments) { + this.arguments = arguments; + } /** * Get the command timeout @@ -91,14 +115,18 @@ public interface DeviceCommandInput extends DeviceCommand { * @return */ @XmlElement(name = "timeout") - Integer getTimeout(); + public Integer getTimeout() { + return timeout; + } /** * Set the command timeout * * @param timeout */ - void setTimeout(Integer timeout); + public void setTimeout(Integer timeout) { + this.timeout = timeout; + } /** * Get the working directory @@ -106,14 +134,18 @@ public interface DeviceCommandInput extends DeviceCommand { * @return */ @XmlElement(name = "workingDir") - String getWorkingDir(); + public String getWorkingDir() { + return workingDir; + } /** * Set the working directory * * @param workingDir */ - void setWorkingDir(String workingDir); + public void setWorkingDir(String workingDir) { + this.workingDir = workingDir; + } /** * Get the command input body @@ -121,14 +153,18 @@ public interface DeviceCommandInput extends DeviceCommand { * @return */ @XmlElement(name = "body") - byte[] getBody(); + public byte[] getBody() { + return body; + } /** * Set the command input body * * @param bytes */ - void setBody(byte[] bytes); + public void setBody(byte[] bytes) { + this.body = bytes; + } /** * Get the environment attributes @@ -136,14 +172,18 @@ public interface DeviceCommandInput extends DeviceCommand { * @return */ @XmlElement(name = "environment") - String[] getEnvironment(); + public String[] getEnvironment() { + return envVars; + } /** * Set the environment attributes * * @param environment */ - void setEnvironment(String[] environment); + public void setEnvironment(String[] environment) { + this.envVars = environment; + } /** * Get the asynchronous run flag @@ -151,14 +191,18 @@ public interface DeviceCommandInput extends DeviceCommand { * @return */ @XmlElement(name = "runAsynch") - boolean isRunAsynch(); + public boolean isRunAsynch() { + return runAsync; + } /** * Set the asynchronous run flag * * @param runAsync */ - void setRunAsynch(boolean runAsync); + public void setRunAsynch(boolean runAsync) { + this.runAsync = runAsync; + } /** * Get the device standard input @@ -166,12 +210,17 @@ public interface DeviceCommandInput extends DeviceCommand { * @return */ @XmlElement(name = "stdin") - String getStdin(); + public String getStdin() { + return stdIn; + } /** * Set the device standard input * * @param stdin */ - void setStdin(String stdin); + public void setStdin(String stdin) { + this.stdIn = stdin; + } + } diff --git a/service/device/management/command/api/src/main/java/org/eclipse/kapua/service/device/management/command/DeviceCommandOutput.java b/service/device/management/command/api/src/main/java/org/eclipse/kapua/service/device/management/command/DeviceCommandOutput.java index 772f54f718d..eb03db5ee17 100644 --- a/service/device/management/command/api/src/main/java/org/eclipse/kapua/service/device/management/command/DeviceCommandOutput.java +++ b/service/device/management/command/api/src/main/java/org/eclipse/kapua/service/device/management/command/DeviceCommandOutput.java @@ -32,8 +32,17 @@ "exceptionStack", "exitCode", "hasTimedout" -}, factoryClass = DeviceCommandXmlRegistry.class, factoryMethod = "newCommandOutput") -public interface DeviceCommandOutput extends DeviceCommand { +}) +public class DeviceCommandOutput implements DeviceCommand { + + private static final long serialVersionUID = -3987291078035621467L; + + private String stdErr; + private String stdOut; + private String exceptionMessage; + private String exceptionStack; + private Integer exitCode; + private Boolean timedOut; /** * Get the standard error @@ -41,14 +50,18 @@ public interface DeviceCommandOutput extends DeviceCommand { * @return */ @XmlElement(name = "stderr") - String getStderr(); + public String getStderr() { + return stdErr; + } /** * Set the standard error * * @param stderr */ - void setStderr(String stderr); + public void setStderr(String stderr) { + this.stdErr = stderr; + } /** * Get the standard output @@ -56,14 +69,18 @@ public interface DeviceCommandOutput extends DeviceCommand { * @return */ @XmlElement(name = "stdout") - String getStdout(); + public String getStdout() { + return stdOut; + } /** * Set the standard output * * @param stdout */ - void setStdout(String stdout); + public void setStdout(String stdout) { + this.stdOut = stdout; + } /** * Get the command execution exception message @@ -71,14 +88,18 @@ public interface DeviceCommandOutput extends DeviceCommand { * @return */ @XmlElement(name = "exceptionMessage") - String getExceptionMessage(); + public String getExceptionMessage() { + return exceptionMessage; + } /** * Set the command execution exception message * * @param exceptionMessage */ - void setExceptionMessage(String exceptionMessage); + public void setExceptionMessage(String exceptionMessage) { + this.exceptionMessage = exceptionMessage; + } /** * Get the command execution exception stack @@ -86,14 +107,18 @@ public interface DeviceCommandOutput extends DeviceCommand { * @return */ @XmlElement(name = "exceptionStack") - String getExceptionStack(); + public String getExceptionStack() { + return exceptionStack; + } /** * Set the command execution exception stack * * @param exceptionStack */ - void setExceptionStack(String exceptionStack); + public void setExceptionStack(String exceptionStack) { + this.exceptionStack = exceptionStack; + } /** * Get the command execution exit code @@ -101,14 +126,18 @@ public interface DeviceCommandOutput extends DeviceCommand { * @return */ @XmlElement(name = "exitCode") - Integer getExitCode(); + public Integer getExitCode() { + return exitCode; + } /** * Set the command execution exit code * * @param exitCode */ - void setExitCode(Integer exitCode); + public void setExitCode(Integer exitCode) { + this.exitCode = exitCode; + } /** * Get the command execution timed out flag @@ -116,12 +145,17 @@ public interface DeviceCommandOutput extends DeviceCommand { * @return */ @XmlElement(name = "hasTimedout") - Boolean getHasTimedout(); + public Boolean getHasTimedout() { + return timedOut; + } /** * Set the command execution timed out flag * * @param hasTimedout */ - void setHasTimedout(Boolean hasTimedout); + public void setHasTimedout(Boolean hasTimedout) { + this.timedOut = hasTimedout; + } + } diff --git a/service/device/management/command/api/src/main/java/org/eclipse/kapua/service/device/management/command/DeviceCommandXmlRegistry.java b/service/device/management/command/api/src/main/java/org/eclipse/kapua/service/device/management/command/DeviceCommandXmlRegistry.java deleted file mode 100644 index dd70154cdd5..00000000000 --- a/service/device/management/command/api/src/main/java/org/eclipse/kapua/service/device/management/command/DeviceCommandXmlRegistry.java +++ /dev/null @@ -1,50 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.command; - -import org.eclipse.kapua.locator.KapuaLocator; - -import javax.xml.bind.annotation.XmlRegistry; - -/** - * {@link DeviceCommand} XmlFactory implementation. - * - * @since 1.0.0 - */ -@XmlRegistry -public class DeviceCommandXmlRegistry { - - private final KapuaLocator locator = KapuaLocator.getInstance(); - private final DeviceCommandFactory factory = locator.getFactory(DeviceCommandFactory.class); - - /** - * Instantiates a new {@link DeviceCommandInput}. - * - * @return The newly instantiated {@link DeviceCommandInput}. - * @since 1.0.0 - */ - public DeviceCommandInput newCommandInput() { - return factory.newCommandInput(); - } - - /** - * Instantiates a new {@link DeviceCommandOutput}. - * - * @return The newly instantiated {@link DeviceCommandOutput}. - * @since 1.0.0 - */ - public DeviceCommandOutput newCommandOutput() { - return factory.newCommandOutput(); - } - -} diff --git a/service/device/management/command/internal/pom.xml b/service/device/management/command/internal/pom.xml index ae728bc3705..1008f085033 100644 --- a/service/device/management/command/internal/pom.xml +++ b/service/device/management/command/internal/pom.xml @@ -19,7 +19,7 @@ org.eclipse.kapua kapua-device-management-command - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-device-management-command-internal diff --git a/service/device/management/command/internal/src/main/java/org/eclipse/kapua/service/device/management/command/internal/DeviceCommandFactoryImpl.java b/service/device/management/command/internal/src/main/java/org/eclipse/kapua/service/device/management/command/internal/DeviceCommandFactoryImpl.java deleted file mode 100644 index 21bff35b4c1..00000000000 --- a/service/device/management/command/internal/src/main/java/org/eclipse/kapua/service/device/management/command/internal/DeviceCommandFactoryImpl.java +++ /dev/null @@ -1,39 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.command.internal; - -import org.eclipse.kapua.service.device.management.command.DeviceCommandFactory; -import org.eclipse.kapua.service.device.management.command.DeviceCommandInput; -import org.eclipse.kapua.service.device.management.command.DeviceCommandOutput; - -import javax.inject.Singleton; - -/** - * {@link DeviceCommandFactory} implementation. - * - * @since 1.0.0 - */ -@Singleton -public class DeviceCommandFactoryImpl implements DeviceCommandFactory { - - @Override - public DeviceCommandInput newCommandInput() { - return new DeviceCommandInputImpl(); - } - - @Override - public DeviceCommandOutput newCommandOutput() { - return new DeviceCommandOutputImpl(); - } - -} diff --git a/service/device/management/command/internal/src/main/java/org/eclipse/kapua/service/device/management/command/internal/DeviceCommandInputImpl.java b/service/device/management/command/internal/src/main/java/org/eclipse/kapua/service/device/management/command/internal/DeviceCommandInputImpl.java deleted file mode 100644 index cf0eb4c6a62..00000000000 --- a/service/device/management/command/internal/src/main/java/org/eclipse/kapua/service/device/management/command/internal/DeviceCommandInputImpl.java +++ /dev/null @@ -1,125 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.command.internal; - -import org.eclipse.kapua.service.device.management.command.DeviceCommandInput; - -/** - * {@link DeviceCommandInput} implementation. - * - * @since 1.0.0 - */ -public class DeviceCommandInputImpl implements DeviceCommandInput { - - private static final long serialVersionUID = -2141178091281947848L; - - private String command; - private String password; - private String[] arguments; - private Integer timeout; - private String workingDir; - private byte[] body; - private String[] envVars; - private boolean runAsync; - private String stdIn; - - @Override - public void setCommand(String command) { - this.command = command; - } - - @Override - public String getCommand() { - return command; - } - - @Override - public void setPassword(String password) { - this.password = password; - } - - @Override - public String getPassword() { - return password; - } - - @Override - public void setArguments(String[] arguments) { - this.arguments = arguments; - } - - @Override - public String[] getArguments() { - return arguments; - } - - @Override - public void setTimeout(Integer timeout) { - this.timeout = timeout; - } - - @Override - public Integer getTimeout() { - return timeout; - } - - @Override - public void setWorkingDir(String workingDir) { - this.workingDir = workingDir; - } - - @Override - public String getWorkingDir() { - return workingDir; - } - - @Override - public void setBody(byte[] bytes) { - this.body = bytes; - } - - @Override - public byte[] getBody() { - return body; - } - - @Override - public void setEnvironment(String[] environment) { - this.envVars = environment; - } - - @Override - public String[] getEnvironment() { - return envVars; - } - - @Override - public void setRunAsynch(boolean runAsync) { - this.runAsync = runAsync; - } - - @Override - public boolean isRunAsynch() { - return runAsync; - } - - @Override - public void setStdin(String stdIn) { - this.stdIn = stdIn; - } - - @Override - public String getStdin() { - return stdIn; - } -} diff --git a/service/device/management/command/internal/src/main/java/org/eclipse/kapua/service/device/management/command/internal/DeviceCommandManagementServiceImpl.java b/service/device/management/command/internal/src/main/java/org/eclipse/kapua/service/device/management/command/internal/DeviceCommandManagementServiceImpl.java index 68afc10124a..19e7bbe5ff7 100644 --- a/service/device/management/command/internal/src/main/java/org/eclipse/kapua/service/device/management/command/internal/DeviceCommandManagementServiceImpl.java +++ b/service/device/management/command/internal/src/main/java/org/eclipse/kapua/service/device/management/command/internal/DeviceCommandManagementServiceImpl.java @@ -12,13 +12,17 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.command.internal; +import java.util.Date; + +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.commons.model.domains.Domains; import org.eclipse.kapua.commons.util.ArgumentValidator; import org.eclipse.kapua.model.domain.Actions; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; +import org.eclipse.kapua.service.authorization.permission.Permission; import org.eclipse.kapua.service.device.management.command.DeviceCommandInput; import org.eclipse.kapua.service.device.management.command.DeviceCommandManagementService; import org.eclipse.kapua.service.device.management.command.DeviceCommandOutput; @@ -37,9 +41,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.inject.Singleton; -import java.util.Date; - /** * {@link DeviceCommandManagementService} implementation. * @@ -47,16 +48,15 @@ */ @Singleton public class DeviceCommandManagementServiceImpl extends AbstractDeviceManagementTransactionalServiceImpl implements DeviceCommandManagementService { + public DeviceCommandManagementServiceImpl( TxManager txManager, AuthorizationService authorizationService, - PermissionFactory permissionFactory, DeviceEventService deviceEventService, DeviceEventFactory deviceEventFactory, DeviceRegistryService deviceRegistryService) { super(txManager, authorizationService, - permissionFactory, deviceEventService, deviceEventFactory, deviceRegistryService); @@ -73,7 +73,7 @@ public DeviceCommandOutput exec(KapuaId scopeId, KapuaId deviceId, DeviceCommand ArgumentValidator.notNull(commandInput, "commandInput"); ArgumentValidator.notNull(commandInput.getTimeout(), "commandInput.timeout"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE_MANAGEMENT, Actions.execute, scopeId)); + authorizationService.checkPermission(new Permission(Domains.DEVICE_MANAGEMENT, Actions.execute, scopeId)); // Prepare the request CommandRequestChannel commandRequestChannel = new CommandRequestChannel(); commandRequestChannel.setAppName(CommandAppProperties.APP_NAME); @@ -112,7 +112,8 @@ public DeviceCommandOutput exec(KapuaId scopeId, KapuaId deviceId, DeviceCommand responseMessage = commandDeviceCallBuilder.send(); } catch (Exception e) { if (commandInput.getArguments() != null) { - LOG.error("Error while executing DeviceCommand {} with arguments {} for Device {}. Error: {}", commandInput.getCommand(), String.join(" ", commandInput.getArguments()), deviceId, e.getMessage(), e); + LOG.error("Error while executing DeviceCommand {} with arguments {} for Device {}. Error: {}", commandInput.getCommand(), String.join(" ", commandInput.getArguments()), deviceId, + e.getMessage(), e); } else { LOG.error("Error while executing DeviceCommand {} for Device {}. Error: {}", commandInput.getCommand(), deviceId, e.getMessage(), e); } @@ -125,7 +126,7 @@ public DeviceCommandOutput exec(KapuaId scopeId, KapuaId deviceId, DeviceCommand return checkResponseAcceptedOrThrowError(responseMessage, () -> { CommandResponsePayload responsePayload = responseMessage.getPayload(); - DeviceCommandOutput deviceCommandOutput = new DeviceCommandOutputImpl(); + DeviceCommandOutput deviceCommandOutput = new DeviceCommandOutput(); deviceCommandOutput.setExceptionMessage(responsePayload.getExceptionMessage()); deviceCommandOutput.setExceptionStack(responsePayload.getExceptionStack()); deviceCommandOutput.setExitCode(responsePayload.getExitCode()); diff --git a/service/device/management/command/internal/src/main/java/org/eclipse/kapua/service/device/management/command/internal/DeviceCommandOutputImpl.java b/service/device/management/command/internal/src/main/java/org/eclipse/kapua/service/device/management/command/internal/DeviceCommandOutputImpl.java deleted file mode 100644 index 0c2a17becc7..00000000000 --- a/service/device/management/command/internal/src/main/java/org/eclipse/kapua/service/device/management/command/internal/DeviceCommandOutputImpl.java +++ /dev/null @@ -1,93 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.command.internal; - -import org.eclipse.kapua.service.device.management.command.DeviceCommandOutput; - -/** - * {@link DeviceCommandOutput} implementation. - * - * @since 1.0.0 - */ -public class DeviceCommandOutputImpl implements DeviceCommandOutput { - - private static final long serialVersionUID = -3987291078035621467L; - - private String stdErr; - private String stdOut; - private String exceptionMessage; - private String exceptionStack; - private Integer exitCode; - private Boolean timedOut; - - @Override - public String getStderr() { - return stdErr; - } - - @Override - public void setStderr(String stderr) { - this.stdErr = stderr; - } - - @Override - public String getStdout() { - return stdOut; - } - - @Override - public void setStdout(String stdout) { - this.stdOut = stdout; - } - - @Override - public String getExceptionMessage() { - return exceptionMessage; - } - - @Override - public void setExceptionMessage(String exceptionMessage) { - this.exceptionMessage = exceptionMessage; - } - - @Override - public String getExceptionStack() { - return exceptionStack; - } - - @Override - public void setExceptionStack(String exceptionStack) { - this.exceptionStack = exceptionStack; - } - - @Override - public Integer getExitCode() { - return exitCode; - } - - @Override - public void setExitCode(Integer exitCode) { - this.exitCode = exitCode; - } - - @Override - public Boolean getHasTimedout() { - return timedOut; - } - - @Override - public void setHasTimedout(Boolean hasTimedout) { - this.timedOut = hasTimedout; - } - -} diff --git a/service/device/management/command/internal/src/main/java/org/eclipse/kapua/service/device/management/command/internal/DeviceManagementCommandModule.java b/service/device/management/command/internal/src/main/java/org/eclipse/kapua/service/device/management/command/internal/DeviceManagementCommandModule.java index ab6d45fa9c0..79233747f21 100644 --- a/service/device/management/command/internal/src/main/java/org/eclipse/kapua/service/device/management/command/internal/DeviceManagementCommandModule.java +++ b/service/device/management/command/internal/src/main/java/org/eclipse/kapua/service/device/management/command/internal/DeviceManagementCommandModule.java @@ -12,30 +12,28 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.command.internal; -import com.google.inject.Provides; +import javax.inject.Inject; + import org.eclipse.kapua.commons.core.AbstractKapuaModule; import org.eclipse.kapua.commons.jpa.KapuaJpaTxManagerFactory; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; -import org.eclipse.kapua.service.device.management.command.DeviceCommandFactory; import org.eclipse.kapua.service.device.management.command.DeviceCommandManagementService; import org.eclipse.kapua.service.device.registry.DeviceRegistryService; import org.eclipse.kapua.service.device.registry.event.DeviceEventFactory; import org.eclipse.kapua.service.device.registry.event.DeviceEventService; -import javax.inject.Inject; +import com.google.inject.Provides; public class DeviceManagementCommandModule extends AbstractKapuaModule { + @Override protected void configureModule() { - bind(DeviceCommandFactory.class).to(DeviceCommandFactoryImpl.class); } @Provides @Inject DeviceCommandManagementService deviceCommandManagementService( AuthorizationService authorizationService, - PermissionFactory permissionFactory, DeviceEventService deviceEventService, DeviceEventFactory deviceEventFactory, DeviceRegistryService deviceRegistryService, @@ -43,7 +41,6 @@ DeviceCommandManagementService deviceCommandManagementService( return new DeviceCommandManagementServiceImpl( jpaTxManagerFactory.create("kapua-device_management_operation_registry"), authorizationService, - permissionFactory, deviceEventService, deviceEventFactory, deviceRegistryService diff --git a/service/device/management/command/job/pom.xml b/service/device/management/command/job/pom.xml index 9578791fe80..0c6715b31fc 100644 --- a/service/device/management/command/job/pom.xml +++ b/service/device/management/command/job/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-device-management-command - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-device-management-command-job diff --git a/service/device/management/command/pom.xml b/service/device/management/command/pom.xml index 70bd1f0bc2c..c4d20fbfaba 100644 --- a/service/device/management/command/pom.xml +++ b/service/device/management/command/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-device-management - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT pom diff --git a/service/device/management/configuration-store/api/pom.xml b/service/device/management/configuration-store/api/pom.xml index b59bac0a7a2..b7693a989a1 100644 --- a/service/device/management/configuration-store/api/pom.xml +++ b/service/device/management/configuration-store/api/pom.xml @@ -19,7 +19,7 @@ org.eclipse.kapua kapua-device-management-configuration-store - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-device-management-configuration-store-api diff --git a/service/device/management/configuration-store/dummy/pom.xml b/service/device/management/configuration-store/dummy/pom.xml index d9583e5b472..1e3e37a56e4 100644 --- a/service/device/management/configuration-store/dummy/pom.xml +++ b/service/device/management/configuration-store/dummy/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-device-management-configuration-store - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-device-management-configuration-store-dummy diff --git a/service/device/management/configuration-store/dummy/src/main/java/org/eclipse/kapua/service/device/management/configuration/store/dummy/DeviceConfigurationStoreServiceDummy.java b/service/device/management/configuration-store/dummy/src/main/java/org/eclipse/kapua/service/device/management/configuration/store/dummy/DeviceConfigurationStoreServiceDummy.java index 4c57f7d5b33..2277098c469 100644 --- a/service/device/management/configuration-store/dummy/src/main/java/org/eclipse/kapua/service/device/management/configuration/store/dummy/DeviceConfigurationStoreServiceDummy.java +++ b/service/device/management/configuration-store/dummy/src/main/java/org/eclipse/kapua/service/device/management/configuration/store/dummy/DeviceConfigurationStoreServiceDummy.java @@ -17,7 +17,6 @@ import javax.inject.Singleton; import org.eclipse.kapua.commons.service.internal.KapuaServiceDisabledException; -import org.eclipse.kapua.model.config.metatype.EmptyTocd; import org.eclipse.kapua.model.config.metatype.KapuaTocd; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.device.management.configuration.DeviceComponentConfiguration; @@ -55,7 +54,7 @@ public void storeConfigurations(KapuaId scopeId, KapuaId deviceId, DeviceConfigu @Override public KapuaTocd getConfigMetadata(KapuaId scopeId) { - return new EmptyTocd(); + return KapuaTocd.empty(); } @Override diff --git a/service/device/management/configuration-store/pom.xml b/service/device/management/configuration-store/pom.xml index 545dd3dce3e..de109c61e28 100644 --- a/service/device/management/configuration-store/pom.xml +++ b/service/device/management/configuration-store/pom.xml @@ -19,7 +19,7 @@ org.eclipse.kapua kapua-device-management - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-device-management-configuration-store diff --git a/service/device/management/configuration/api/pom.xml b/service/device/management/configuration/api/pom.xml index d721aad23e1..ecff656e9f7 100644 --- a/service/device/management/configuration/api/pom.xml +++ b/service/device/management/configuration/api/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-device-management-configuration - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-device-management-configuration-api diff --git a/service/device/management/configuration/api/src/main/java/org/eclipse/kapua/service/device/management/configuration/DeviceComponentConfiguration.java b/service/device/management/configuration/api/src/main/java/org/eclipse/kapua/service/device/management/configuration/DeviceComponentConfiguration.java index 723541503f0..88e54170467 100644 --- a/service/device/management/configuration/api/src/main/java/org/eclipse/kapua/service/device/management/configuration/DeviceComponentConfiguration.java +++ b/service/device/management/configuration/api/src/main/java/org/eclipse/kapua/service/device/management/configuration/DeviceComponentConfiguration.java @@ -12,7 +12,7 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.configuration; -import org.eclipse.kapua.model.config.metatype.KapuaTocd; +import java.util.Map; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; @@ -21,7 +21,8 @@ import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; -import java.util.Map; + +import org.eclipse.kapua.model.config.metatype.KapuaTocd; /** * Device component configuration entity definition. @@ -30,8 +31,32 @@ */ @XmlRootElement(name = "configuration") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = DeviceConfigurationXmlRegistry.class, factoryMethod = "newComponentConfiguration") -public interface DeviceComponentConfiguration { +@XmlType +public class DeviceComponentConfiguration { + + private String id; + private String name; + private KapuaTocd definition; + private Map properties; + + /** + * Constructor. + * + * @since 1.0.0 + */ + public DeviceComponentConfiguration() { + } + + /** + * Constructor. + * + * @param id + * The {@link DeviceComponentConfiguration#getId()} + * @since 1.0.0 + */ + public DeviceComponentConfiguration(String id) { + this.id = id; + } /** * Get device configuration component identifier @@ -39,14 +64,18 @@ public interface DeviceComponentConfiguration { * @return */ @XmlElement(name = "id") - String getId(); + public String getId() { + return id; + } /** * Set device configuration component identifier * * @param id */ - void setId(String id); + public void setId(String id) { + this.id = id; + } /** * Get device configuration component name @@ -54,14 +83,18 @@ public interface DeviceComponentConfiguration { * @return */ @XmlAttribute(name = "name") - String getName(); + public String getName() { + return name; + } /** * Set device configuration component name * * @param name */ - void setName(String name); + public void setName(String name) { + this.name = name; + } /** * Get device configuration component definition @@ -69,14 +102,18 @@ public interface DeviceComponentConfiguration { * @return */ @XmlElement(name = "definition") - KapuaTocd getDefinition(); + public KapuaTocd getDefinition() { + return definition; + } /** * Set device configuration component definition * * @param definition */ - void setDefinition(KapuaTocd definition); + public void setDefinition(KapuaTocd definition) { + this.definition = definition; + } /** * Get device configuration component properties @@ -85,12 +122,17 @@ public interface DeviceComponentConfiguration { */ @XmlElement(name = "properties") @XmlJavaTypeAdapter(DeviceXmlConfigPropertiesAdapter.class) - Map getProperties(); + public Map getProperties() { + return properties; + } /** * Set device configuration component properties * * @param properties */ - void setProperties(Map properties); + public void setProperties(Map properties) { + this.properties = properties; + } + } diff --git a/service/device/management/configuration/api/src/main/java/org/eclipse/kapua/service/device/management/configuration/DeviceConfiguration.java b/service/device/management/configuration/api/src/main/java/org/eclipse/kapua/service/device/management/configuration/DeviceConfiguration.java index cbbc902fa4f..c7251351852 100644 --- a/service/device/management/configuration/api/src/main/java/org/eclipse/kapua/service/device/management/configuration/DeviceConfiguration.java +++ b/service/device/management/configuration/api/src/main/java/org/eclipse/kapua/service/device/management/configuration/DeviceConfiguration.java @@ -13,14 +13,16 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.configuration; -import org.eclipse.kapua.KapuaSerializable; +import java.util.ArrayList; +import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; -import java.util.List; + +import org.eclipse.kapua.KapuaSerializable; /** * {@link DeviceConfiguration} definition. @@ -29,8 +31,12 @@ */ @XmlRootElement(name = "deviceConfigurations") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = DeviceConfigurationXmlRegistry.class, factoryMethod = "newConfiguration") -public interface DeviceConfiguration extends KapuaSerializable { +@XmlType +public class DeviceConfiguration implements KapuaSerializable { + + private static final long serialVersionUID = -2167999497954676423L; + + private List configurations; /** * Gets the {@link List} of {@link DeviceComponentConfiguration}. @@ -39,22 +45,34 @@ public interface DeviceConfiguration extends KapuaSerializable { * @since 1.0.0 */ @XmlElement(name = "configuration") - List getComponentConfigurations(); + public List getComponentConfigurations() { + if (configurations == null) { + configurations = new ArrayList<>(); + } + + return configurations; + } /** * Adds a {@link DeviceComponentConfiguration} to the {@link List} of {@link DeviceComponentConfiguration}. * - * @param componentConfiguration The {@link DeviceComponentConfiguration} to add. + * @param componentConfiguration + * The {@link DeviceComponentConfiguration} to add. * @since 2.0.0 */ - void addComponentConfiguration(DeviceComponentConfiguration componentConfiguration); + public void addComponentConfiguration(DeviceComponentConfiguration componentConfiguration) { + getComponentConfigurations().add(componentConfiguration); + } /** * Sets the {@link List} of {@link DeviceComponentConfiguration}. * - * @param componentConfigurations The {@link List} of {@link DeviceComponentConfiguration}. + * @param componentConfigurations + * The {@link List} of {@link DeviceComponentConfiguration}. * @since 2.0.0 */ - void setComponentConfigurations(List componentConfigurations); + public void setComponentConfigurations(List componentConfigurations) { + this.configurations = componentConfigurations; + } } diff --git a/service/device/management/configuration/api/src/main/java/org/eclipse/kapua/service/device/management/configuration/DeviceConfigurationFactory.java b/service/device/management/configuration/api/src/main/java/org/eclipse/kapua/service/device/management/configuration/DeviceConfigurationFactory.java deleted file mode 100644 index c6e01f49b9d..00000000000 --- a/service/device/management/configuration/api/src/main/java/org/eclipse/kapua/service/device/management/configuration/DeviceConfigurationFactory.java +++ /dev/null @@ -1,37 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.configuration; - -import org.eclipse.kapua.model.KapuaObjectFactory; - -/** - * Device configuration entity service factory definition. - * - * @since 1.0 - */ -public interface DeviceConfigurationFactory extends KapuaObjectFactory { - - /** - * Creates a new {@link DeviceComponentConfiguration} using the given component configuration identifier - * - * @return - */ - DeviceComponentConfiguration newComponentConfigurationInstance(String componentConfigurationId); - - /** - * Creates a new {@link DeviceConfiguration} - * - * @return - */ - DeviceConfiguration newConfigurationInstance(); -} diff --git a/service/device/management/configuration/api/src/main/java/org/eclipse/kapua/service/device/management/configuration/DeviceConfigurationXmlRegistry.java b/service/device/management/configuration/api/src/main/java/org/eclipse/kapua/service/device/management/configuration/DeviceConfigurationXmlRegistry.java deleted file mode 100644 index df4f1d70f80..00000000000 --- a/service/device/management/configuration/api/src/main/java/org/eclipse/kapua/service/device/management/configuration/DeviceConfigurationXmlRegistry.java +++ /dev/null @@ -1,46 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.configuration; - -import org.eclipse.kapua.locator.KapuaLocator; - -import javax.xml.bind.annotation.XmlRegistry; - -/** - * {@link DeviceConfiguration} xml factory class - * - * @since 1.0 - */ -@XmlRegistry -public class DeviceConfigurationXmlRegistry { - - private final DeviceConfigurationFactory deviceConfigurationFactory = KapuaLocator.getInstance().getFactory(DeviceConfigurationFactory.class); - - /** - * Creates a new device configuration - * - * @return - */ - public DeviceConfiguration newConfiguration() { - return deviceConfigurationFactory.newConfigurationInstance(); - } - - /** - * Creates a new device component configuration - * - * @return - */ - public DeviceComponentConfiguration newComponentConfiguration() { - return deviceConfigurationFactory.newComponentConfigurationInstance(null); - } -} diff --git a/service/device/management/configuration/internal/pom.xml b/service/device/management/configuration/internal/pom.xml index 75ead3a0013..cdf4fcc6703 100644 --- a/service/device/management/configuration/internal/pom.xml +++ b/service/device/management/configuration/internal/pom.xml @@ -19,7 +19,7 @@ org.eclipse.kapua kapua-device-management-configuration - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-device-management-configuration-internal diff --git a/service/device/management/configuration/internal/src/main/java/org/eclipse/kapua/service/device/management/configuration/internal/DeviceComponentConfigurationImpl.java b/service/device/management/configuration/internal/src/main/java/org/eclipse/kapua/service/device/management/configuration/internal/DeviceComponentConfigurationImpl.java deleted file mode 100644 index 9bb37435150..00000000000 --- a/service/device/management/configuration/internal/src/main/java/org/eclipse/kapua/service/device/management/configuration/internal/DeviceComponentConfigurationImpl.java +++ /dev/null @@ -1,90 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.configuration.internal; - -import java.util.Map; - -import org.eclipse.kapua.model.config.metatype.KapuaTocd; -import org.eclipse.kapua.service.device.management.configuration.DeviceComponentConfiguration; - -/** - * Device component configuration entity implementation. - * - * @since 1.0.0 - */ -public class DeviceComponentConfigurationImpl implements DeviceComponentConfiguration { - - private String id; - private String name; - private KapuaTocd definition; - private Map properties; - - /** - * Constructor. - * - * @since 1.0.0 - */ - public DeviceComponentConfigurationImpl() { - } - - /** - * Constructor. - * - * @param id - * The {@link DeviceComponentConfiguration#getId()} - * @since 1.0.0 - */ - public DeviceComponentConfigurationImpl(String id) { - this.id = id; - } - - @Override - public String getId() { - return id; - } - - @Override - public void setId(String id) { - this.id = id; - } - - @Override - public String getName() { - return name; - } - - @Override - public void setName(String name) { - this.name = name; - } - - @Override - public void setDefinition(KapuaTocd definition) { - this.definition = definition; - } - - @Override - public KapuaTocd getDefinition() { - return definition; - } - - @Override - public Map getProperties() { - return properties; - } - - @Override - public void setProperties(Map properties) { - this.properties = properties; - } -} diff --git a/service/device/management/configuration/internal/src/main/java/org/eclipse/kapua/service/device/management/configuration/internal/DeviceConfigurationFactoryImpl.java b/service/device/management/configuration/internal/src/main/java/org/eclipse/kapua/service/device/management/configuration/internal/DeviceConfigurationFactoryImpl.java deleted file mode 100644 index 502f892092e..00000000000 --- a/service/device/management/configuration/internal/src/main/java/org/eclipse/kapua/service/device/management/configuration/internal/DeviceConfigurationFactoryImpl.java +++ /dev/null @@ -1,39 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.configuration.internal; - -import org.eclipse.kapua.service.device.management.configuration.DeviceComponentConfiguration; -import org.eclipse.kapua.service.device.management.configuration.DeviceConfiguration; -import org.eclipse.kapua.service.device.management.configuration.DeviceConfigurationFactory; - -import javax.inject.Singleton; - -/** - * Device configuration entity service factory implementation. - * - * @since 1.0 - */ -@Singleton -public class DeviceConfigurationFactoryImpl implements DeviceConfigurationFactory { - - @Override - public DeviceComponentConfiguration newComponentConfigurationInstance(String componentConfigurationId) { - return new DeviceComponentConfigurationImpl(componentConfigurationId); - } - - @Override - public DeviceConfiguration newConfigurationInstance() { - return new DeviceConfigurationImpl(); - } - -} diff --git a/service/device/management/configuration/internal/src/main/java/org/eclipse/kapua/service/device/management/configuration/internal/DeviceConfigurationImpl.java b/service/device/management/configuration/internal/src/main/java/org/eclipse/kapua/service/device/management/configuration/internal/DeviceConfigurationImpl.java deleted file mode 100644 index 9c3ccc44d1d..00000000000 --- a/service/device/management/configuration/internal/src/main/java/org/eclipse/kapua/service/device/management/configuration/internal/DeviceConfigurationImpl.java +++ /dev/null @@ -1,59 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - * Red Hat Inc - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.configuration.internal; - -import org.eclipse.kapua.service.device.management.configuration.DeviceComponentConfiguration; -import org.eclipse.kapua.service.device.management.configuration.DeviceConfiguration; - -import java.util.ArrayList; -import java.util.List; - -/** - * {@link DeviceConfiguration} implementation. - * - * @since 1.0.0 - */ -public class DeviceConfigurationImpl implements DeviceConfiguration { - - private static final long serialVersionUID = -2167999497954676423L; - - private List configurations; - - /** - * Constructor. - * - * @since 1.0.0 - */ - public DeviceConfigurationImpl() { - } - - @Override - public List getComponentConfigurations() { - if (configurations == null) { - configurations = new ArrayList<>(); - } - - return configurations; - } - - @Override - public void addComponentConfiguration(DeviceComponentConfiguration componentConfiguration) { - getComponentConfigurations().add(componentConfiguration); - } - - @Override - public void setComponentConfigurations(List componentConfigurations) { - this.configurations = componentConfigurations; - } -} diff --git a/service/device/management/configuration/internal/src/main/java/org/eclipse/kapua/service/device/management/configuration/internal/DeviceConfigurationManagementServiceImpl.java b/service/device/management/configuration/internal/src/main/java/org/eclipse/kapua/service/device/management/configuration/internal/DeviceConfigurationManagementServiceImpl.java index 88a5370c4b4..a55a7e19cb3 100644 --- a/service/device/management/configuration/internal/src/main/java/org/eclipse/kapua/service/device/management/configuration/internal/DeviceConfigurationManagementServiceImpl.java +++ b/service/device/management/configuration/internal/src/main/java/org/eclipse/kapua/service/device/management/configuration/internal/DeviceConfigurationManagementServiceImpl.java @@ -25,12 +25,11 @@ import org.eclipse.kapua.model.domain.Actions; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; +import org.eclipse.kapua.service.authorization.permission.Permission; import org.eclipse.kapua.service.device.management.commons.AbstractDeviceManagementTransactionalServiceImpl; import org.eclipse.kapua.service.device.management.commons.call.DeviceCallBuilder; import org.eclipse.kapua.service.device.management.configuration.DeviceComponentConfiguration; import org.eclipse.kapua.service.device.management.configuration.DeviceConfiguration; -import org.eclipse.kapua.service.device.management.configuration.DeviceConfigurationFactory; import org.eclipse.kapua.service.device.management.configuration.DeviceConfigurationManagementService; import org.eclipse.kapua.service.device.management.configuration.message.internal.ConfigurationRequestChannel; import org.eclipse.kapua.service.device.management.configuration.message.internal.ConfigurationRequestMessage; @@ -59,7 +58,6 @@ public class DeviceConfigurationManagementServiceImpl extends AbstractDeviceManagementTransactionalServiceImpl implements DeviceConfigurationManagementService { private static final Logger LOG = LoggerFactory.getLogger(DeviceConfigurationManagementServiceImpl.class); - private final DeviceConfigurationFactory deviceConfigurationFactory; private static final String SCOPE_ID = "scopeId"; private static final String DEVICE_ID = "deviceId"; @@ -69,21 +67,17 @@ public class DeviceConfigurationManagementServiceImpl extends AbstractDeviceMana public DeviceConfigurationManagementServiceImpl(TxManager txManager, AuthorizationService authorizationService, - PermissionFactory permissionFactory, DeviceEventService deviceEventService, DeviceEventFactory deviceEventFactory, DeviceRegistryService deviceRegistryService, - DeviceConfigurationFactory deviceConfigurationFactory, DeviceConfigurationStoreService deviceConfigurationStoreService, XmlUtil xmlUtil) { super(txManager, authorizationService, - permissionFactory, deviceEventService, deviceEventFactory, deviceRegistryService ); - this.deviceConfigurationFactory = deviceConfigurationFactory; this.deviceConfigurationStoreService = deviceConfigurationStoreService; this.xmlUtil = xmlUtil; } @@ -95,7 +89,7 @@ public DeviceConfiguration get(KapuaId scopeId, KapuaId deviceId, String configu ArgumentValidator.notNull(scopeId, SCOPE_ID); ArgumentValidator.notNull(deviceId, DEVICE_ID); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE_MANAGEMENT, Actions.read, scopeId)); + authorizationService.checkPermission(new Permission(Domains.DEVICE_MANAGEMENT, Actions.read, scopeId)); // Prepare the request ConfigurationRequestChannel configurationRequestChannel = new ConfigurationRequestChannel(); configurationRequestChannel.setAppName(DeviceConfigurationAppProperties.APP_NAME); @@ -135,7 +129,7 @@ public DeviceConfiguration get(KapuaId scopeId, KapuaId deviceId, String configu createDeviceEvent(scopeId, deviceId, configurationRequestMessage, responseMessage); // Check response DeviceConfiguration onlineDeviceConfiguration = checkResponseAcceptedOrThrowError(responseMessage, - () -> responseMessage.getPayload().getDeviceConfigurations().orElse(deviceConfigurationFactory.newConfigurationInstance())); + () -> responseMessage.getPayload().getDeviceConfigurations().orElse(new DeviceConfiguration())); // Store config and return if (deviceConfigurationStoreService.isServiceEnabled(scopeId) && deviceConfigurationStoreService.isApplicationEnabled(scopeId, deviceId)) { @@ -155,7 +149,7 @@ public DeviceConfiguration get(KapuaId scopeId, KapuaId deviceId, String configu if (configurationComponentPid == null) { return deviceConfigurationStoreService.getConfigurations(scopeId, deviceId); } else { - DeviceConfiguration deviceConfigurationReturned = deviceConfigurationFactory.newConfigurationInstance(); + DeviceConfiguration deviceConfigurationReturned = new DeviceConfiguration(); DeviceComponentConfiguration componentConfiguration = deviceConfigurationStoreService.getConfigurations(scopeId, deviceId, configurationComponentPid); deviceConfigurationReturned.addComponentConfiguration(componentConfiguration); return deviceConfigurationReturned; @@ -175,7 +169,7 @@ public void put(KapuaId scopeId, KapuaId deviceId, DeviceComponentConfiguration ArgumentValidator.notNull(deviceComponentConfiguration, "componentConfiguration"); ArgumentValidator.notEmptyOrNull(deviceComponentConfiguration.getId(), "componentConfiguration.componentId"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE_MANAGEMENT, Actions.write, scopeId)); + authorizationService.checkPermission(new Permission(Domains.DEVICE_MANAGEMENT, Actions.write, scopeId)); // Prepare the request ConfigurationRequestChannel configurationRequestChannel = new ConfigurationRequestChannel(); configurationRequestChannel.setAppName(DeviceConfigurationAppProperties.APP_NAME); @@ -185,7 +179,7 @@ public void put(KapuaId scopeId, KapuaId deviceId, DeviceComponentConfiguration ConfigurationRequestPayload configurationRequestPayload = new ConfigurationRequestPayload(); - DeviceConfiguration deviceConfiguration = deviceConfigurationFactory.newConfigurationInstance(); + DeviceConfiguration deviceConfiguration = new DeviceConfiguration(); try { deviceConfiguration.getComponentConfigurations().add(deviceComponentConfiguration); @@ -229,7 +223,7 @@ public void put(KapuaId scopeId, KapuaId deviceId, String xmlDeviceConfig, Long try { put(scopeId, deviceId, - xmlUtil.unmarshal(xmlDeviceConfig, DeviceConfigurationImpl.class), + xmlUtil.unmarshal(xmlDeviceConfig, DeviceConfiguration.class), timeout); } catch (JAXBException | SAXException e) { throw new KapuaIllegalArgumentException("xmlDeviceConfig", xmlDeviceConfig); @@ -244,7 +238,7 @@ public void put(KapuaId scopeId, KapuaId deviceId, DeviceConfiguration deviceCon ArgumentValidator.notNull(deviceId, DEVICE_ID); ArgumentValidator.notNull(deviceConfiguration, "componentConfiguration"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE_MANAGEMENT, Actions.write, scopeId)); + authorizationService.checkPermission(new Permission(Domains.DEVICE_MANAGEMENT, Actions.write, scopeId)); // Prepare the request ConfigurationRequestChannel configurationRequestChannel = new ConfigurationRequestChannel(); configurationRequestChannel.setAppName(DeviceConfigurationAppProperties.APP_NAME); diff --git a/service/device/management/configuration/internal/src/main/java/org/eclipse/kapua/service/device/management/configuration/internal/DeviceManagementConfigurationModule.java b/service/device/management/configuration/internal/src/main/java/org/eclipse/kapua/service/device/management/configuration/internal/DeviceManagementConfigurationModule.java index c651661e9bf..9daaa5879ae 100644 --- a/service/device/management/configuration/internal/src/main/java/org/eclipse/kapua/service/device/management/configuration/internal/DeviceManagementConfigurationModule.java +++ b/service/device/management/configuration/internal/src/main/java/org/eclipse/kapua/service/device/management/configuration/internal/DeviceManagementConfigurationModule.java @@ -19,8 +19,6 @@ import org.eclipse.kapua.commons.jpa.KapuaJpaTxManagerFactory; import org.eclipse.kapua.commons.util.xml.XmlUtil; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; -import org.eclipse.kapua.service.device.management.configuration.DeviceConfigurationFactory; import org.eclipse.kapua.service.device.management.configuration.DeviceConfigurationManagementService; import org.eclipse.kapua.service.device.management.configuration.internal.settings.DeviceConfigurationManagementSettings; import org.eclipse.kapua.service.device.management.configuration.store.DeviceConfigurationStoreService; @@ -34,7 +32,6 @@ public class DeviceManagementConfigurationModule extends AbstractKapuaModule { @Override protected void configureModule() { - bind(DeviceConfigurationFactory.class).to(DeviceConfigurationFactoryImpl.class).in(Singleton.class); bind(DeviceConfigurationManagementSettings.class).in(Singleton.class); } @@ -42,22 +39,18 @@ protected void configureModule() { @Inject DeviceConfigurationManagementService deviceConfigurationManagementService( AuthorizationService authorizationService, - PermissionFactory permissionFactory, DeviceEventService deviceEventService, DeviceEventFactory deviceEventFactory, DeviceRegistryService deviceRegistryService, - DeviceConfigurationFactory deviceConfigurationFactory, DeviceConfigurationStoreService deviceConfigurationStoreService, KapuaJpaTxManagerFactory jpaTxManagerFactory, XmlUtil xmlUtil) { return new DeviceConfigurationManagementServiceImpl( jpaTxManagerFactory.create("kapua-device_management_operation_registry"), authorizationService, - permissionFactory, deviceEventService, deviceEventFactory, deviceRegistryService, - deviceConfigurationFactory, deviceConfigurationStoreService, xmlUtil ); diff --git a/service/device/management/configuration/internal/src/main/java/org/eclipse/kapua/service/device/management/snapshot/internal/DeviceManagementSnapshotModule.java b/service/device/management/configuration/internal/src/main/java/org/eclipse/kapua/service/device/management/snapshot/internal/DeviceManagementSnapshotModule.java index da4d6252c4b..a6b81e7b0e0 100644 --- a/service/device/management/configuration/internal/src/main/java/org/eclipse/kapua/service/device/management/snapshot/internal/DeviceManagementSnapshotModule.java +++ b/service/device/management/configuration/internal/src/main/java/org/eclipse/kapua/service/device/management/snapshot/internal/DeviceManagementSnapshotModule.java @@ -12,20 +12,21 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.snapshot.internal; -import com.google.inject.Provides; +import javax.inject.Singleton; + import org.eclipse.kapua.commons.core.AbstractKapuaModule; import org.eclipse.kapua.commons.jpa.KapuaJpaTxManagerFactory; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; import org.eclipse.kapua.service.device.management.snapshot.DeviceSnapshotFactory; import org.eclipse.kapua.service.device.management.snapshot.DeviceSnapshotManagementService; import org.eclipse.kapua.service.device.registry.DeviceRegistryService; import org.eclipse.kapua.service.device.registry.event.DeviceEventFactory; import org.eclipse.kapua.service.device.registry.event.DeviceEventService; -import javax.inject.Singleton; +import com.google.inject.Provides; public class DeviceManagementSnapshotModule extends AbstractKapuaModule { + @Override protected void configureModule() { bind(DeviceSnapshotFactory.class).to(DeviceSnapshotFactoryImpl.class); @@ -35,7 +36,6 @@ protected void configureModule() { @Singleton DeviceSnapshotManagementService deviceSnapshotManagementService( AuthorizationService authorizationService, - PermissionFactory permissionFactory, DeviceEventService deviceEventService, DeviceEventFactory deviceEventFactory, DeviceRegistryService deviceRegistryService, @@ -44,7 +44,6 @@ DeviceSnapshotManagementService deviceSnapshotManagementService( return new DeviceSnapshotManagementServiceImpl( jpaTxManagerFactory.create("kapua-device_management_operation_registry"), authorizationService, - permissionFactory, deviceEventService, deviceEventFactory, deviceRegistryService, diff --git a/service/device/management/configuration/internal/src/main/java/org/eclipse/kapua/service/device/management/snapshot/internal/DeviceSnapshotManagementServiceImpl.java b/service/device/management/configuration/internal/src/main/java/org/eclipse/kapua/service/device/management/snapshot/internal/DeviceSnapshotManagementServiceImpl.java index 61c84ec95bc..0a4a5e63e1a 100644 --- a/service/device/management/configuration/internal/src/main/java/org/eclipse/kapua/service/device/management/snapshot/internal/DeviceSnapshotManagementServiceImpl.java +++ b/service/device/management/configuration/internal/src/main/java/org/eclipse/kapua/service/device/management/snapshot/internal/DeviceSnapshotManagementServiceImpl.java @@ -12,13 +12,18 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.snapshot.internal; +import java.util.Date; + +import javax.inject.Inject; +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.commons.model.domains.Domains; import org.eclipse.kapua.commons.util.ArgumentValidator; import org.eclipse.kapua.model.domain.Actions; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; +import org.eclipse.kapua.service.authorization.permission.Permission; import org.eclipse.kapua.service.device.management.commons.AbstractDeviceManagementTransactionalServiceImpl; import org.eclipse.kapua.service.device.management.commons.call.DeviceCallBuilder; import org.eclipse.kapua.service.device.management.configuration.internal.DeviceConfigurationAppProperties; @@ -38,10 +43,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.inject.Inject; -import javax.inject.Singleton; -import java.util.Date; - /** * {@link DeviceSnapshotManagementService} implementation. * @@ -56,13 +57,11 @@ public class DeviceSnapshotManagementServiceImpl extends AbstractDeviceManagemen public DeviceSnapshotManagementServiceImpl( TxManager txManager, AuthorizationService authorizationService, - PermissionFactory permissionFactory, DeviceEventService deviceEventService, DeviceEventFactory deviceEventFactory, DeviceRegistryService deviceRegistryService, DeviceSnapshotFactory deviceSnapshotFactory) { super(txManager, authorizationService, - permissionFactory, deviceEventService, deviceEventFactory, deviceRegistryService); @@ -78,7 +77,7 @@ public DeviceSnapshots get(KapuaId scopeId, KapuaId deviceId, Long timeout) ArgumentValidator.notNull(scopeId, "scopeId"); ArgumentValidator.notNull(deviceId, "deviceId"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE_MANAGEMENT, Actions.read, scopeId)); + authorizationService.checkPermission(new Permission(Domains.DEVICE_MANAGEMENT, Actions.read, scopeId)); // Prepare the request SnapshotRequestChannel snapshotRequestChannel = new SnapshotRequestChannel(); snapshotRequestChannel.setAppName(DeviceConfigurationAppProperties.APP_NAME); @@ -124,7 +123,7 @@ public void rollback(KapuaId scopeId, KapuaId deviceId, String snapshotId, Long ArgumentValidator.notNull(deviceId, "deviceId"); ArgumentValidator.notEmptyOrNull(snapshotId, "snapshotId"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE_MANAGEMENT, Actions.execute, scopeId)); + authorizationService.checkPermission(new Permission(Domains.DEVICE_MANAGEMENT, Actions.execute, scopeId)); // Prepare the request SnapshotRequestChannel snapshotRequestChannel = new SnapshotRequestChannel(); snapshotRequestChannel.setAppName(DeviceConfigurationAppProperties.APP_NAME); diff --git a/service/device/management/configuration/job/pom.xml b/service/device/management/configuration/job/pom.xml index 6cb75339f37..2cbfad1f8ae 100644 --- a/service/device/management/configuration/job/pom.xml +++ b/service/device/management/configuration/job/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-device-management-configuration - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-device-management-configuration-job diff --git a/service/device/management/configuration/message-api/pom.xml b/service/device/management/configuration/message-api/pom.xml index 39c116d05dd..68501c2493f 100644 --- a/service/device/management/configuration/message-api/pom.xml +++ b/service/device/management/configuration/message-api/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-device-management-configuration - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-device-management-configuration-message-api diff --git a/service/device/management/configuration/pom.xml b/service/device/management/configuration/pom.xml index 28eb211e6bb..234dc2d94b7 100644 --- a/service/device/management/configuration/pom.xml +++ b/service/device/management/configuration/pom.xml @@ -19,7 +19,7 @@ org.eclipse.kapua kapua-device-management - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT pom diff --git a/service/device/management/inventory/api/pom.xml b/service/device/management/inventory/api/pom.xml index ae6b6cb2711..cc478499fdb 100644 --- a/service/device/management/inventory/api/pom.xml +++ b/service/device/management/inventory/api/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-device-management-inventory - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-device-management-inventory-api diff --git a/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/DeviceInventoryManagementFactory.java b/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/DeviceInventoryManagementFactory.java deleted file mode 100644 index 669bbbc1a23..00000000000 --- a/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/DeviceInventoryManagementFactory.java +++ /dev/null @@ -1,117 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.inventory; - -import org.eclipse.kapua.model.KapuaObjectFactory; -import org.eclipse.kapua.service.device.management.inventory.model.bundle.DeviceInventoryBundle; -import org.eclipse.kapua.service.device.management.inventory.model.bundle.DeviceInventoryBundles; -import org.eclipse.kapua.service.device.management.inventory.model.container.DeviceInventoryContainer; -import org.eclipse.kapua.service.device.management.inventory.model.container.DeviceInventoryContainers; -import org.eclipse.kapua.service.device.management.inventory.model.inventory.DeviceInventory; -import org.eclipse.kapua.service.device.management.inventory.model.inventory.DeviceInventoryItem; -import org.eclipse.kapua.service.device.management.inventory.model.packages.DeviceInventoryPackage; -import org.eclipse.kapua.service.device.management.inventory.model.packages.DeviceInventoryPackages; -import org.eclipse.kapua.service.device.management.inventory.model.system.DeviceInventorySystemPackage; -import org.eclipse.kapua.service.device.management.inventory.model.system.DeviceInventorySystemPackages; - -/** - * {@link DeviceInventoryItem} {@link KapuaObjectFactory} definition. - * - * @see org.eclipse.kapua.model.KapuaObjectFactory - * @since 1.5.0 - */ -public interface DeviceInventoryManagementFactory extends KapuaObjectFactory { - - /** - * Instantiates a new {@link DeviceInventory}. - * - * @return The newly instantiated {@link DeviceInventory} - * @since 1.5.0 - */ - DeviceInventory newDeviceInventory(); - - /** - * Instantiates a new {@link DeviceInventoryItem}. - * - * @return The newly instantiated {@link DeviceInventoryItem} - * @since 1.5.0 - */ - DeviceInventoryItem newDeviceInventoryItem(); - - /** - * Instantiates a new {@link DeviceInventoryBundle}. - * - * @return The newly instantiated {@link DeviceInventoryBundle} - * @since 1.5.0 - */ - DeviceInventoryBundle newDeviceInventoryBundle(); - - /** - * Instantiates a new {@link DeviceInventoryBundles}. - * - * @return The newly instantiated {@link DeviceInventoryBundles} - * @since 1.5.0 - */ - DeviceInventoryBundles newDeviceInventoryBundles(); - - /** - * Instantiates a new {@link DeviceInventoryContainer}. - * - * @return The newly instantiated {@link DeviceInventoryContainer} - * @since 2.0.0 - */ - DeviceInventoryContainer newDeviceInventoryContainer(); - - /** - * Instantiates a new {@link DeviceInventoryContainers}. - * - * @return The newly instantiated {@link DeviceInventoryContainers} - * @since 2.0.0 - */ - DeviceInventoryContainers newDeviceInventoryContainers(); - - - /** - * Instantiates a new {@link DeviceInventorySystemPackage}. - * - * @return The newly instantiated {@link DeviceInventorySystemPackage} - * @since 1.5.0 - */ - DeviceInventorySystemPackage newDeviceInventorySystemPackage(); - - /** - * Instantiates a new {@link DeviceInventorySystemPackages}. - * - * @return The newly instantiated {@link DeviceInventorySystemPackages} - * @since 1.5.0 - */ - DeviceInventorySystemPackages newDeviceInventorySystemPackages(); - - /** - * Instantiates a new {@link DeviceInventoryPackage}. - * - * @return The newly instantiated {@link DeviceInventoryPackage} - * @since 1.5.0 - */ - DeviceInventoryPackage newDeviceInventoryPackage(); - - /** - * Instantiates a new {@link DeviceInventoryPackages}. - * - * @return The newly instantiated {@link DeviceInventoryPackages} - * @since 1.5.0 - */ - DeviceInventoryPackages newDeviceInventoryPackages(); - - -} diff --git a/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/bundle/DeviceInventoryBundle.java b/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/bundle/DeviceInventoryBundle.java index d07855195d3..9ef89b900e8 100644 --- a/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/bundle/DeviceInventoryBundle.java +++ b/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/bundle/DeviceInventoryBundle.java @@ -27,8 +27,14 @@ */ @XmlRootElement(name = "deviceInventoryBundle") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = DeviceInventoryBundlesXmlRegistry.class, factoryMethod = "newDeviceInventoryBundle") -public interface DeviceInventoryBundle { +@XmlType +public class DeviceInventoryBundle { + + private String id; + private String name; + private String version; + private String status; + private Boolean signed; /** * Gets the identifier. @@ -37,15 +43,20 @@ public interface DeviceInventoryBundle { * @since 1.5.0 */ @XmlElement(name = "id") - String getId(); + public String getId() { + return id; + } /** * Sets the identifier. * - * @param id The identifier. + * @param id + * The identifier. * @since 1.5.0 */ - void setId(String id); + public void setId(String id) { + this.id = id; + } /** * Gets the name. @@ -54,15 +65,20 @@ public interface DeviceInventoryBundle { * @since 1.5.0 */ @XmlElement(name = "name") - String getName(); + public String getName() { + return name; + } /** * Sets the name. * - * @param name The name. + * @param name + * The name. * @since 1.5.0 */ - void setName(String name); + public void setName(String name) { + this.name = name; + } /** * Gets the bundle version. @@ -71,15 +87,20 @@ public interface DeviceInventoryBundle { * @since 1.5.0 */ @XmlElement(name = "version") - String getVersion(); + public String getVersion() { + return version; + } /** * Sets the version. * - * @param version The version. + * @param version + * The version. * @since 1.5.0 */ - void setVersion(String version); + public void setVersion(String version) { + this.version = version; + } /** * Gets the status. @@ -88,15 +109,20 @@ public interface DeviceInventoryBundle { * @since 1.5.0 */ @XmlElement(name = "status") - String getStatus(); + public String getStatus() { + return status; + } /** * Sets the status. * - * @param status The status. + * @param status + * The status. * @since 1.5.0 */ - void setStatus(String status); + public void setStatus(String status) { + this.status = status; + } /** * Whether the bundle is signed. @@ -104,13 +130,19 @@ public interface DeviceInventoryBundle { * @return {@code true} if is signed, {@code false} if not or {@code null} if the information is not known. * @since 2.0.0 */ - Boolean getSigned(); + public Boolean getSigned() { + return signed; + } /** * Sets whether the bundle is signed. * - * @param signed {@code true} if is signed, {@code false} if not or {@code null} if the information is not known. + * @param signed + * {@code true} if is signed, {@code false} if not or {@code null} if the information is not known. * @since 2.0.0 */ - void setSigned(Boolean signed); + public void setSigned(Boolean signed) { + this.signed = signed; + } + } diff --git a/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/bundle/DeviceInventoryBundles.java b/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/bundle/DeviceInventoryBundles.java index f62c5983253..c17cb9b8d46 100644 --- a/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/bundle/DeviceInventoryBundles.java +++ b/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/bundle/DeviceInventoryBundles.java @@ -12,7 +12,8 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.inventory.model.bundle; -import org.eclipse.kapua.KapuaSerializable; +import java.util.ArrayList; +import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; @@ -20,7 +21,8 @@ import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; import javax.xml.bind.annotation.XmlType; -import java.util.List; + +import org.eclipse.kapua.KapuaSerializable; /** * {@link DeviceInventoryBundles} definition. @@ -29,8 +31,12 @@ */ @XmlRootElement(name = "deviceInventoryBundles") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = DeviceInventoryBundlesXmlRegistry.class, factoryMethod = "newDeviceInventoryBundles") -public interface DeviceInventoryBundles extends KapuaSerializable { +@XmlType +public class DeviceInventoryBundles implements KapuaSerializable { + + private static final long serialVersionUID = 5229149965375932561L; + + private List inventoryBundles; /** * Gets the {@link List} of {@link DeviceInventoryBundle}s @@ -39,22 +45,35 @@ public interface DeviceInventoryBundles extends KapuaSerializable { * @since 1.5.0 */ @XmlElement(name = "inventoryBundles") - List getInventoryBundles(); + public List getInventoryBundles() { + if (inventoryBundles == null) { + inventoryBundles = new ArrayList<>(); + } + + return inventoryBundles; + } /** * Adds a {@link DeviceInventoryBundle} to the {@link List} * - * @param inventoryBundle The {@link DeviceInventoryBundle} to add. + * @param inventoryBundle + * The {@link DeviceInventoryBundle} to add. * @since 1.5.0 */ @XmlTransient - void addInventoryBundle(DeviceInventoryBundle inventoryBundle); + public void addInventoryBundle(DeviceInventoryBundle inventoryBundle) { + getInventoryBundles().add(inventoryBundle); + } /** * Sets the {@link List} of {@link DeviceInventoryBundle}s * - * @param inventoryBundles The {@link List} of {@link DeviceInventoryBundle}s + * @param inventoryBundles + * The {@link List} of {@link DeviceInventoryBundle}s * @since 1.5.0 */ - void setInventoryBundles(List inventoryBundles); + public void setInventoryBundles(List inventoryBundles) { + this.inventoryBundles = inventoryBundles; + } + } diff --git a/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/bundle/DeviceInventoryBundlesXmlRegistry.java b/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/bundle/DeviceInventoryBundlesXmlRegistry.java deleted file mode 100644 index 5a3ec7ea5cf..00000000000 --- a/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/bundle/DeviceInventoryBundlesXmlRegistry.java +++ /dev/null @@ -1,47 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.inventory.model.bundle; - -import org.eclipse.kapua.locator.KapuaLocator; -import org.eclipse.kapua.service.device.management.inventory.DeviceInventoryManagementFactory; - -/** - * {@link DeviceInventoryBundles} XmlFactory definition. - * - * @since 1.5.0 - */ -public class DeviceInventoryBundlesXmlRegistry { - - private final DeviceInventoryManagementFactory factory = KapuaLocator.getInstance().getFactory(DeviceInventoryManagementFactory.class); - - /** - * Instantiates a new {@link DeviceInventoryBundles}. - * - * @return The newly instantiated {@link DeviceInventoryBundles} - * @since 1.5.0 - */ - public DeviceInventoryBundles newDeviceInventoryBundles() { - return factory.newDeviceInventoryBundles(); - } - - /** - * Instantiates a new {@link DeviceInventoryBundle}. - * - * @return The newly instantiated {@link DeviceInventoryBundle} - * @since 1.5.0 - */ - public DeviceInventoryBundle newDeviceInventoryBundle() { - return factory.newDeviceInventoryBundle(); - } - -} \ No newline at end of file diff --git a/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/container/DeviceInventoryContainer.java b/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/container/DeviceInventoryContainer.java index 0548fd396cb..980442cdefb 100644 --- a/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/container/DeviceInventoryContainer.java +++ b/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/container/DeviceInventoryContainer.java @@ -27,8 +27,14 @@ */ @XmlRootElement(name = "deviceInventoryContainer") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = DeviceInventoryContainersXmlRegistry.class, factoryMethod = "newDeviceInventoryContainer") -public interface DeviceInventoryContainer { +@XmlType +public class DeviceInventoryContainer { + + private String name; + private String version; + private String containerType; + + private DeviceInventoryContainerState state; /** * Gets the name. @@ -37,15 +43,20 @@ public interface DeviceInventoryContainer { * @since 2.0.0 */ @XmlElement(name = "name") - String getName(); + public String getName() { + return name; + } /** * Sets the name. * - * @param name The name. + * @param name + * The name. * @since 2.0.0 */ - void setName(String name); + public void setName(String name) { + this.name = name; + } /** * Gets the container version. @@ -54,15 +65,20 @@ public interface DeviceInventoryContainer { * @since 2.0.0 */ @XmlElement(name = "version") - String getVersion(); + public String getVersion() { + return version; + } /** * Sets the version. * - * @param version The version. + * @param version + * The version. * @since 2.0.0 */ - void setVersion(String version); + public void setVersion(String version) { + this.version = version; + } /** * Gets the type. @@ -71,15 +87,20 @@ public interface DeviceInventoryContainer { * @since 2.0.0 */ @XmlElement(name = "containerType") - String getContainerType(); + public String getContainerType() { + return containerType; + } /** * Sets the container type. * - * @param containerType The container type. + * @param containerType + * The container type. * @since 2.0.0 */ - void setContainerType(String containerType); + public void setContainerType(String containerType) { + this.containerType = containerType; + } /** * Gets the {@link DeviceInventoryContainerState}. @@ -87,14 +108,19 @@ public interface DeviceInventoryContainer { * @return The {@link DeviceInventoryContainerState}. * @since 2.0.0 */ - DeviceInventoryContainerState getState(); + public DeviceInventoryContainerState getState() { + return state; + } /** * Sets the {@link DeviceInventoryContainerState}. * - * @param state The {@link DeviceInventoryContainerState}. + * @param state + * The {@link DeviceInventoryContainerState}. * @since 2.0.0 */ - void setState(DeviceInventoryContainerState state); + public void setState(DeviceInventoryContainerState state) { + this.state = state; + } } diff --git a/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/container/DeviceInventoryContainers.java b/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/container/DeviceInventoryContainers.java index d420d1f7c02..e81590ceb19 100644 --- a/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/container/DeviceInventoryContainers.java +++ b/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/container/DeviceInventoryContainers.java @@ -12,7 +12,8 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.inventory.model.container; -import org.eclipse.kapua.KapuaSerializable; +import java.util.ArrayList; +import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; @@ -20,7 +21,8 @@ import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; import javax.xml.bind.annotation.XmlType; -import java.util.List; + +import org.eclipse.kapua.KapuaSerializable; /** * {@link DeviceInventoryContainers} definition. @@ -29,8 +31,12 @@ */ @XmlRootElement(name = "deviceInventoryContainers") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = DeviceInventoryContainersXmlRegistry.class, factoryMethod = "newDeviceInventoryContainers") -public interface DeviceInventoryContainers extends KapuaSerializable { +@XmlType +public class DeviceInventoryContainers implements KapuaSerializable { + + private static final long serialVersionUID = 5229149965375932561L; + + private List inventoryContainers; /** * Gets the {@link List} of {@link DeviceInventoryContainer}s @@ -39,22 +45,35 @@ public interface DeviceInventoryContainers extends KapuaSerializable { * @since 2.0.0 */ @XmlElement(name = "inventoryContainers") - List getInventoryContainers(); + public List getInventoryContainers() { + if (inventoryContainers == null) { + inventoryContainers = new ArrayList<>(); + } + + return inventoryContainers; + } /** * Adds a {@link DeviceInventoryContainer} to the {@link List} * - * @param inventoryContainer The {@link DeviceInventoryContainer} to add. + * @param inventoryContainer + * The {@link DeviceInventoryContainer} to add. * @since 2.0.0 */ @XmlTransient - void addInventoryContainer(DeviceInventoryContainer inventoryContainer); + public void addInventoryContainer(DeviceInventoryContainer inventoryContainer) { + getInventoryContainers().add(inventoryContainer); + } /** * Sets the {@link List} of {@link DeviceInventoryContainer}s * - * @param inventoryContainers The {@link List} of {@link DeviceInventoryContainer}s + * @param inventoryContainers + * The {@link List} of {@link DeviceInventoryContainer}s * @since 2.0.0 */ - void setInventoryContainers(List inventoryContainers); + public void setInventoryContainers(List inventoryContainers) { + this.inventoryContainers = inventoryContainers; + } + } diff --git a/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/container/DeviceInventoryContainersXmlRegistry.java b/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/container/DeviceInventoryContainersXmlRegistry.java deleted file mode 100644 index a4aa82c82f9..00000000000 --- a/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/container/DeviceInventoryContainersXmlRegistry.java +++ /dev/null @@ -1,47 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.inventory.model.container; - -import org.eclipse.kapua.locator.KapuaLocator; -import org.eclipse.kapua.service.device.management.inventory.DeviceInventoryManagementFactory; - -/** - * {@link DeviceInventoryContainers} XmlFactory definition. - * - * @since 2.0.0 - */ -public class DeviceInventoryContainersXmlRegistry { - - private final DeviceInventoryManagementFactory factory = KapuaLocator.getInstance().getFactory(DeviceInventoryManagementFactory.class); - - /** - * Instantiates a new {@link DeviceInventoryContainers}. - * - * @return The newly instantiated {@link DeviceInventoryContainers} - * @since 2.0.0 - */ - public DeviceInventoryContainers newDeviceInventoryContainers() { - return factory.newDeviceInventoryContainers(); - } - - /** - * Instantiates a new {@link DeviceInventoryContainer}. - * - * @return The newly instantiated {@link DeviceInventoryContainer} - * @since 2.0.0 - */ - public DeviceInventoryContainer newDeviceInventoryContainer() { - return factory.newDeviceInventoryContainer(); - } - -} \ No newline at end of file diff --git a/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/inventory/DeviceInventory.java b/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/inventory/DeviceInventory.java index 837d1e429d1..841d282cbe3 100644 --- a/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/inventory/DeviceInventory.java +++ b/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/inventory/DeviceInventory.java @@ -12,14 +12,16 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.inventory.model.inventory; -import org.eclipse.kapua.KapuaSerializable; +import java.util.ArrayList; +import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; -import java.util.List; + +import org.eclipse.kapua.KapuaSerializable; /** * {@link DeviceInventory} definition. @@ -28,8 +30,12 @@ */ @XmlRootElement(name = "deviceInventory") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = DeviceInventoryXmlRegistry.class, factoryMethod = "newDeviceInventory") -public interface DeviceInventory extends KapuaSerializable { +@XmlType +public class DeviceInventory implements KapuaSerializable { + + private static final long serialVersionUID = 734716753080998855L; + + private List inventoryItems; /** * Gets the {@link List} of {@link DeviceInventoryItem}s @@ -38,21 +44,34 @@ public interface DeviceInventory extends KapuaSerializable { * @since 1.5.0 */ @XmlElement(name = "inventoryItems") - List getInventoryItems(); + public List getInventoryItems() { + if (inventoryItems == null) { + inventoryItems = new ArrayList<>(); + } + + return inventoryItems; + } /** * Adds a {@link DeviceInventoryItem} to the {@link List} * - * @param inventoryItem The {@link DeviceInventoryItem} to add. + * @param inventoryItem + * The {@link DeviceInventoryItem} to add. * @since 1.5.0 */ - void addInventoryItem(DeviceInventoryItem inventoryItem); + public void addInventoryItem(DeviceInventoryItem inventoryItem) { + getInventoryItems().add(inventoryItem); + } /** * Sets the {@link List} of {@link DeviceInventoryItem}s * - * @param inventoryItems The {@link List} of {@link DeviceInventoryItem}s + * @param inventoryItems + * The {@link List} of {@link DeviceInventoryItem}s * @since 1.5.0 */ - void setInventoryItems(List inventoryItems); + public void setInventoryItems(List inventoryItems) { + this.inventoryItems = inventoryItems; + } + } diff --git a/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/inventory/DeviceInventoryItem.java b/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/inventory/DeviceInventoryItem.java index 461a04ce35b..70cda657fd3 100644 --- a/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/inventory/DeviceInventoryItem.java +++ b/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/inventory/DeviceInventoryItem.java @@ -27,8 +27,12 @@ */ @XmlRootElement(name = "deviceInventoryItem") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = DeviceInventoryXmlRegistry.class, factoryMethod = "newDeviceInventoryItem") -public interface DeviceInventoryItem { +@XmlType +public class DeviceInventoryItem { + + private String name; + private String version; + private String itemType; /** * Gets the name. @@ -37,15 +41,20 @@ public interface DeviceInventoryItem { * @since 1.5.0 */ @XmlElement(name = "name") - String getName(); + public String getName() { + return name; + } /** * Sets the name. * - * @param name The name. + * @param name + * The name. * @since 1.5.0 */ - void setName(String name); + public void setName(String name) { + this.name = name; + } /** * Gets the bundle version. @@ -54,15 +63,20 @@ public interface DeviceInventoryItem { * @since 1.5.0 */ @XmlElement(name = "version") - String getVersion(); + public String getVersion() { + return version; + } /** * Sets the version. * - * @param version The version. + * @param version + * The version. * @since 1.5.0 */ - void setVersion(String version); + public void setVersion(String version) { + this.version = version; + } /** * Gets the type. @@ -71,13 +85,19 @@ public interface DeviceInventoryItem { * @since 1.5.0 */ @XmlElement(name = "itemType") - String getItemType(); + public String getItemType() { + return itemType; + } /** * Sets the type. * - * @param itemType The type. + * @param itemType + * The type. * @since 1.5.0 */ - void setItemType(String itemType); + public void setItemType(String itemType) { + this.itemType = itemType; + } + } diff --git a/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/inventory/DeviceInventoryXmlRegistry.java b/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/inventory/DeviceInventoryXmlRegistry.java deleted file mode 100644 index ba258ea9de6..00000000000 --- a/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/inventory/DeviceInventoryXmlRegistry.java +++ /dev/null @@ -1,46 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.inventory.model.inventory; - -import org.eclipse.kapua.locator.KapuaLocator; -import org.eclipse.kapua.service.device.management.inventory.DeviceInventoryManagementFactory; - -/** - * {@link DeviceInventory} XmlFactory definition. - * - * @since 1.5.0 - */ -public class DeviceInventoryXmlRegistry { - - private final DeviceInventoryManagementFactory factory = KapuaLocator.getInstance().getFactory(DeviceInventoryManagementFactory.class); - - /** - * Instantiates a new {@link DeviceInventory}. - * - * @return The newly instantiated {@link DeviceInventory} - * @since 1.5.0 - */ - public DeviceInventory newDeviceInventory() { - return factory.newDeviceInventory(); - } - - /** - * Instantiates a new {@link DeviceInventoryItem}. - * - * @return The newly instantiated {@link DeviceInventoryItem} - * @since 1.5.0 - */ - public DeviceInventoryItem newDeviceInventoryItem() { - return factory.newDeviceInventoryItem(); - } -} diff --git a/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/packages/DeviceInventoryPackage.java b/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/packages/DeviceInventoryPackage.java index 1e787f1e3a3..f74b18dc1fd 100644 --- a/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/packages/DeviceInventoryPackage.java +++ b/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/packages/DeviceInventoryPackage.java @@ -12,14 +12,16 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.inventory.model.packages; -import org.eclipse.kapua.service.device.management.inventory.model.bundle.DeviceInventoryBundle; +import java.util.ArrayList; +import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; -import java.util.List; + +import org.eclipse.kapua.service.device.management.inventory.model.bundle.DeviceInventoryBundle; /** * {@link DeviceInventoryPackage} definition. @@ -30,8 +32,12 @@ */ @XmlRootElement(name = "deviceInventoryDeploymentPackage") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = DeviceInventoryPackagesXmlRegistry.class, factoryMethod = "newDeviceInventoryPackage") -public interface DeviceInventoryPackage { +@XmlType +public class DeviceInventoryPackage { + + private String name; + private String version; + private List packageBundles; /** * Gets the name. @@ -40,15 +46,20 @@ public interface DeviceInventoryPackage { * @since 1.5.0 */ @XmlElement(name = "name") - String getName(); + public String getName() { + return name; + } /** * Sets the name. * - * @param name The name. + * @param name + * The name. * @since 1.5.0 */ - void setName(String name); + public void setName(String name) { + this.name = name; + } /** * Gets the bundle version. @@ -57,15 +68,20 @@ public interface DeviceInventoryPackage { * @since 1.5.0 */ @XmlElement(name = "version") - String getVersion(); + public String getVersion() { + return version; + } /** * Sets the version. * - * @param version The version. + * @param version + * The version. * @since 1.5.0 */ - void setVersion(String version); + public void setVersion(String version) { + this.version = version; + } /** * Gets the {@link List} of {@link DeviceInventoryBundle}s. @@ -73,21 +89,34 @@ public interface DeviceInventoryPackage { * @return The {@link List} of {@link DeviceInventoryBundle}s. * @since 1.5.0 */ - List getPackageBundles(); + public List getPackageBundles() { + if (packageBundles == null) { + packageBundles = new ArrayList<>(); + } + + return packageBundles; + } /** * Adds a {@link DeviceInventoryBundle} to the {@link List}. * - * @param inventoryBundle The {@link DeviceInventoryBundle} to add. + * @param inventoryBundle + * The {@link DeviceInventoryBundle} to add. * @since 1.5.0 */ - void addPackageBundle(DeviceInventoryBundle inventoryBundle); + public void addPackageBundle(DeviceInventoryBundle inventoryBundle) { + getPackageBundles().add(inventoryBundle); + } /** * Sets the {@link List} of {@link DeviceInventoryBundle}s. * - * @param inventoryBundles The {@link List} of {@link DeviceInventoryBundle}s. + * @param inventoryBundles + * The {@link List} of {@link DeviceInventoryBundle}s. * @since 1.5.0 */ - void setPackageBundles(List inventoryBundles); + public void setPackageBundles(List inventoryBundles) { + this.packageBundles = inventoryBundles; + } + } diff --git a/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/packages/DeviceInventoryPackages.java b/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/packages/DeviceInventoryPackages.java index cf35156b9d1..e053c068394 100644 --- a/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/packages/DeviceInventoryPackages.java +++ b/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/packages/DeviceInventoryPackages.java @@ -12,14 +12,16 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.inventory.model.packages; -import org.eclipse.kapua.KapuaSerializable; +import java.util.ArrayList; +import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; -import java.util.List; + +import org.eclipse.kapua.KapuaSerializable; /** * {@link DeviceInventoryPackages} definition. @@ -28,8 +30,12 @@ */ @XmlRootElement(name = "deviceInventoryDeploymentPackages") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = DeviceInventoryPackagesXmlRegistry.class, factoryMethod = "newDeviceInventoryPackages") -public interface DeviceInventoryPackages extends KapuaSerializable { +@XmlType +public class DeviceInventoryPackages implements KapuaSerializable { + + private static final long serialVersionUID = -8272540683907649241L; + + private List packages; /** * Gets the {@link List} of {@link DeviceInventoryPackage}s. @@ -38,21 +44,34 @@ public interface DeviceInventoryPackages extends KapuaSerializable { * @since 1.5.0 */ @XmlElement(name = "deploymentPackages") - List getPackages(); + public List getPackages() { + if (packages == null) { + packages = new ArrayList<>(); + } + + return packages; + } /** * Adds a {@link DeviceInventoryPackage} to the {@link List}. * - * @param aPackage The {@link DeviceInventoryPackage} to add. + * @param aPackage + * The {@link DeviceInventoryPackage} to add. * @since 1.5.0 */ - void addPackage(DeviceInventoryPackage aPackage); + public void addPackage(DeviceInventoryPackage aPackage) { + getPackages().add(aPackage); + } /** * Sets the {@link List} of {@link DeviceInventoryPackage}s. * - * @param inventoryPackages The {@link List} of {@link DeviceInventoryPackage}s. + * @param inventoryPackages + * The {@link List} of {@link DeviceInventoryPackage}s. * @since 1.5.0 */ - void setPackages(List inventoryPackages); + public void setPackages(List inventoryPackages) { + this.packages = inventoryPackages; + } + } diff --git a/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/packages/DeviceInventoryPackagesXmlRegistry.java b/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/packages/DeviceInventoryPackagesXmlRegistry.java deleted file mode 100644 index 8ee0b2e15d3..00000000000 --- a/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/packages/DeviceInventoryPackagesXmlRegistry.java +++ /dev/null @@ -1,46 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.inventory.model.packages; - -import org.eclipse.kapua.locator.KapuaLocator; -import org.eclipse.kapua.service.device.management.inventory.DeviceInventoryManagementFactory; - -/** - * {@link DeviceInventoryPackages} XmlFactory definition. - * - * @since 1.5.0 - */ -public class DeviceInventoryPackagesXmlRegistry { - - private final DeviceInventoryManagementFactory factory = KapuaLocator.getInstance().getFactory(DeviceInventoryManagementFactory.class); - - /** - * Instantiates a new {@link DeviceInventoryPackages}. - * - * @return The newly instantiated {@link DeviceInventoryPackages} - * @since 1.5.0 - */ - public DeviceInventoryPackages newDeviceInventoryPackages() { - return factory.newDeviceInventoryPackages(); - } - - /** - * Instantiates a new {@link DeviceInventoryPackage}. - * - * @return The newly instantiated {@link DeviceInventoryPackage} - * @since 1.5.0 - */ - public DeviceInventoryPackage newDeviceInventoryPackage() { - return factory.newDeviceInventoryPackage(); - } -} diff --git a/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/system/DeviceInventorySystemPackage.java b/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/system/DeviceInventorySystemPackage.java index bf814ddef5c..6ed22b0a83e 100644 --- a/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/system/DeviceInventorySystemPackage.java +++ b/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/system/DeviceInventorySystemPackage.java @@ -27,8 +27,12 @@ */ @XmlRootElement(name = "deviceInventorySystemPackage") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = DeviceInventorySystemPackagesXmlRegistry.class, factoryMethod = "newDeviceInventorySystemPackage") -public interface DeviceInventorySystemPackage { +@XmlType +public class DeviceInventorySystemPackage { + + private String name; + private String version; + private String packageType; /** * Gets the name. @@ -37,15 +41,20 @@ public interface DeviceInventorySystemPackage { * @since 1.5.0 */ @XmlElement(name = "name") - String getName(); + public String getName() { + return name; + } /** * Sets the name. * - * @param name The name. + * @param name + * The name. * @since 1.5.0 */ - void setName(String name); + public void setName(String name) { + this.name = name; + } /** * Gets the bundle version. @@ -54,15 +63,20 @@ public interface DeviceInventorySystemPackage { * @since 1.5.0 */ @XmlElement(name = "version") - String getVersion(); + public String getVersion() { + return version; + } /** * Sets the version. * - * @param version The version. + * @param version + * The version. * @since 1.5.0 */ - void setVersion(String version); + public void setVersion(String version) { + this.version = version; + } /** * Gets the type. @@ -71,13 +85,19 @@ public interface DeviceInventorySystemPackage { * @since 1.5.0 */ @XmlElement(name = "packageType") - String getPackageType(); + public String getPackageType() { + return packageType; + } /** * Sets the type. * - * @param packageType The type. + * @param packageType + * The type. * @since 1.5.0 */ - void setPackageType(String packageType); + public void setPackageType(String packageType) { + this.packageType = packageType; + } + } diff --git a/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/system/DeviceInventorySystemPackages.java b/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/system/DeviceInventorySystemPackages.java index 5418871af73..e1b7325e1b0 100644 --- a/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/system/DeviceInventorySystemPackages.java +++ b/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/system/DeviceInventorySystemPackages.java @@ -12,14 +12,16 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.inventory.model.system; -import org.eclipse.kapua.KapuaSerializable; +import java.util.ArrayList; +import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; -import java.util.List; + +import org.eclipse.kapua.KapuaSerializable; /** * {@link DeviceInventorySystemPackages} definition. @@ -28,8 +30,12 @@ */ @XmlRootElement(name = "deviceInventorySystemPackages") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = DeviceInventorySystemPackagesXmlRegistry.class, factoryMethod = "newDeviceInventorySystemPackages") -public interface DeviceInventorySystemPackages extends KapuaSerializable { +@XmlType +public class DeviceInventorySystemPackages implements KapuaSerializable { + + private static final long serialVersionUID = -3824464082139248997L; + + private List systemPackages; /** * Gets the {@link List} of {@link DeviceInventorySystemPackage}s @@ -38,21 +44,33 @@ public interface DeviceInventorySystemPackages extends KapuaSerializable { * @since 1.5.0 */ @XmlElement(name = "systemPackages") - List getSystemPackages(); + public List getSystemPackages() { + if (systemPackages == null) { + systemPackages = new ArrayList<>(); + } + + return systemPackages; + } /** * Adds a {@link DeviceInventorySystemPackage} to the {@link List} * - * @param inventorySystemPackage The {@link DeviceInventorySystemPackage} to add. + * @param inventorySystemPackage + * The {@link DeviceInventorySystemPackage} to add. * @since 1.5.0 */ - void addSystemPackage(DeviceInventorySystemPackage inventorySystemPackage); + public void addSystemPackage(DeviceInventorySystemPackage inventorySystemPackage) { + getSystemPackages().add(inventorySystemPackage); + } /** * Sets the {@link List} of {@link DeviceInventorySystemPackage}s * - * @param inventorySystemPackages The {@link List} of {@link DeviceInventorySystemPackage}s + * @param inventorySystemPackages + * The {@link List} of {@link DeviceInventorySystemPackage}s * @since 1.5.0 */ - void setSystemPackages(List inventorySystemPackages); + public void setSystemPackages(List inventorySystemPackages) { + this.systemPackages = inventorySystemPackages; + } } diff --git a/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/system/DeviceInventorySystemPackagesXmlRegistry.java b/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/system/DeviceInventorySystemPackagesXmlRegistry.java deleted file mode 100644 index 9a4d0bc78f4..00000000000 --- a/service/device/management/inventory/api/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/system/DeviceInventorySystemPackagesXmlRegistry.java +++ /dev/null @@ -1,46 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.inventory.model.system; - -import org.eclipse.kapua.locator.KapuaLocator; -import org.eclipse.kapua.service.device.management.inventory.DeviceInventoryManagementFactory; - -/** - * {@link DeviceInventorySystemPackages} XmlFactory definition. - * - * @since 1.5.0 - */ -public class DeviceInventorySystemPackagesXmlRegistry { - - private final DeviceInventoryManagementFactory factory = KapuaLocator.getInstance().getFactory(DeviceInventoryManagementFactory.class); - - /** - * Instantiates a new {@link DeviceInventorySystemPackages}. - * - * @return The newly instantiated {@link DeviceInventorySystemPackages} - * @since 1.5.0 - */ - public DeviceInventorySystemPackages newDeviceInventorySystemPackages() { - return factory.newDeviceInventorySystemPackages(); - } - - /** - * Instantiates a new {@link DeviceInventorySystemPackage}. - * - * @return The newly instantiated {@link DeviceInventorySystemPackage} - * @since 1.5.0 - */ - public DeviceInventorySystemPackage newDeviceInventorySystemPackage() { - return factory.newDeviceInventorySystemPackage(); - } -} diff --git a/service/device/management/inventory/internal/pom.xml b/service/device/management/inventory/internal/pom.xml index 8fc1252ee77..29bd23ebc4f 100644 --- a/service/device/management/inventory/internal/pom.xml +++ b/service/device/management/inventory/internal/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-device-management-inventory - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-device-management-inventory-internal diff --git a/service/device/management/inventory/internal/src/main/java/org/eclipse/kapua/service/device/management/inventory/internal/DeviceInventoryManagementFactoryImpl.java b/service/device/management/inventory/internal/src/main/java/org/eclipse/kapua/service/device/management/inventory/internal/DeviceInventoryManagementFactoryImpl.java deleted file mode 100644 index 9bcb4afa974..00000000000 --- a/service/device/management/inventory/internal/src/main/java/org/eclipse/kapua/service/device/management/inventory/internal/DeviceInventoryManagementFactoryImpl.java +++ /dev/null @@ -1,96 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.inventory.internal; - -import org.eclipse.kapua.service.device.management.inventory.DeviceInventoryManagementFactory; -import org.eclipse.kapua.service.device.management.inventory.model.bundle.DeviceInventoryBundle; -import org.eclipse.kapua.service.device.management.inventory.model.bundle.DeviceInventoryBundles; -import org.eclipse.kapua.service.device.management.inventory.model.bundle.internal.DeviceInventoryBundleImpl; -import org.eclipse.kapua.service.device.management.inventory.model.bundle.internal.DeviceInventoryBundlesImpl; -import org.eclipse.kapua.service.device.management.inventory.model.container.DeviceInventoryContainer; -import org.eclipse.kapua.service.device.management.inventory.model.container.DeviceInventoryContainers; -import org.eclipse.kapua.service.device.management.inventory.model.container.internal.DeviceInventoryContainerImpl; -import org.eclipse.kapua.service.device.management.inventory.model.container.internal.DeviceInventoryContainersImpl; -import org.eclipse.kapua.service.device.management.inventory.model.inventory.DeviceInventory; -import org.eclipse.kapua.service.device.management.inventory.model.inventory.DeviceInventoryItem; -import org.eclipse.kapua.service.device.management.inventory.model.inventory.internal.DeviceInventoryImpl; -import org.eclipse.kapua.service.device.management.inventory.model.inventory.internal.DeviceInventoryItemImpl; -import org.eclipse.kapua.service.device.management.inventory.model.packages.DeviceInventoryPackage; -import org.eclipse.kapua.service.device.management.inventory.model.packages.DeviceInventoryPackages; -import org.eclipse.kapua.service.device.management.inventory.model.packages.internal.DeviceInventoryPackageImpl; -import org.eclipse.kapua.service.device.management.inventory.model.packages.internal.DeviceInventoryPackagesImpl; -import org.eclipse.kapua.service.device.management.inventory.model.system.DeviceInventorySystemPackage; -import org.eclipse.kapua.service.device.management.inventory.model.system.DeviceInventorySystemPackages; -import org.eclipse.kapua.service.device.management.inventory.model.system.internal.DeviceInventorySystemPackageImpl; -import org.eclipse.kapua.service.device.management.inventory.model.system.internal.DeviceInventorySystemPackagesImpl; - -import javax.inject.Singleton; - -/** - * {@link DeviceInventoryManagementFactory} implementation. - * - * @since 1.5.0 - */ -@Singleton -public class DeviceInventoryManagementFactoryImpl implements DeviceInventoryManagementFactory { - - @Override - public DeviceInventory newDeviceInventory() { - return new DeviceInventoryImpl(); - } - - @Override - public DeviceInventoryItem newDeviceInventoryItem() { - return new DeviceInventoryItemImpl(); - } - - @Override - public DeviceInventoryBundle newDeviceInventoryBundle() { - return new DeviceInventoryBundleImpl(); - } - - @Override - public DeviceInventoryBundles newDeviceInventoryBundles() { - return new DeviceInventoryBundlesImpl(); - } - - @Override - public DeviceInventoryContainer newDeviceInventoryContainer() { - return new DeviceInventoryContainerImpl(); - } - - @Override - public DeviceInventoryContainers newDeviceInventoryContainers() { - return new DeviceInventoryContainersImpl(); - } - - @Override - public DeviceInventorySystemPackage newDeviceInventorySystemPackage() { - return new DeviceInventorySystemPackageImpl(); - } - - @Override - public DeviceInventorySystemPackages newDeviceInventorySystemPackages() { - return new DeviceInventorySystemPackagesImpl(); - } - - @Override - public DeviceInventoryPackage newDeviceInventoryPackage() { - return new DeviceInventoryPackageImpl(); - } - - @Override - public DeviceInventoryPackages newDeviceInventoryPackages() { - return new DeviceInventoryPackagesImpl(); - } -} diff --git a/service/device/management/inventory/internal/src/main/java/org/eclipse/kapua/service/device/management/inventory/internal/DeviceInventoryManagementServiceImpl.java b/service/device/management/inventory/internal/src/main/java/org/eclipse/kapua/service/device/management/inventory/internal/DeviceInventoryManagementServiceImpl.java index d2458609b13..14d6da4474e 100644 --- a/service/device/management/inventory/internal/src/main/java/org/eclipse/kapua/service/device/management/inventory/internal/DeviceInventoryManagementServiceImpl.java +++ b/service/device/management/inventory/internal/src/main/java/org/eclipse/kapua/service/device/management/inventory/internal/DeviceInventoryManagementServiceImpl.java @@ -12,6 +12,10 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.inventory.internal; +import java.util.Date; + +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.KapuaIllegalArgumentException; import org.eclipse.kapua.commons.model.domains.Domains; @@ -19,11 +23,10 @@ import org.eclipse.kapua.model.domain.Actions; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; +import org.eclipse.kapua.service.authorization.permission.Permission; import org.eclipse.kapua.service.device.management.commons.AbstractDeviceManagementTransactionalServiceImpl; import org.eclipse.kapua.service.device.management.commons.call.DeviceCallBuilder; import org.eclipse.kapua.service.device.management.exception.DeviceManagementRequestContentException; -import org.eclipse.kapua.service.device.management.inventory.DeviceInventoryManagementFactory; import org.eclipse.kapua.service.device.management.inventory.DeviceInventoryManagementService; import org.eclipse.kapua.service.device.management.inventory.internal.message.InventoryBundleExecRequestMessage; import org.eclipse.kapua.service.device.management.inventory.internal.message.InventoryBundlesResponseMessage; @@ -53,9 +56,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.inject.Singleton; -import java.util.Date; - /** * {@link DeviceInventoryManagementService} implementation. * @@ -69,22 +69,17 @@ public class DeviceInventoryManagementServiceImpl extends AbstractDeviceManageme private static final String SCOPE_ID = "scopeId"; private static final String DEVICE_ID = "deviceId"; - private final DeviceInventoryManagementFactory deviceInventoryManagementFactory; - public DeviceInventoryManagementServiceImpl( TxManager txManager, AuthorizationService authorizationService, - PermissionFactory permissionFactory, DeviceEventService deviceEventService, DeviceEventFactory deviceEventFactory, - DeviceRegistryService deviceRegistryService, DeviceInventoryManagementFactory deviceInventoryManagementFactory) { + DeviceRegistryService deviceRegistryService) { super(txManager, authorizationService, - permissionFactory, deviceEventService, deviceEventFactory, deviceRegistryService); - this.deviceInventoryManagementFactory = deviceInventoryManagementFactory; } @Override @@ -94,7 +89,7 @@ public DeviceInventory getInventory(KapuaId scopeId, KapuaId deviceId, Long time ArgumentValidator.notNull(scopeId, SCOPE_ID); ArgumentValidator.notNull(deviceId, DEVICE_ID); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE_MANAGEMENT, Actions.read, scopeId)); + authorizationService.checkPermission(new Permission(Domains.DEVICE_MANAGEMENT, Actions.read, scopeId)); // Prepare the request InventoryRequestChannel inventoryRequestChannel = new InventoryRequestChannel(); inventoryRequestChannel.setAppName(DeviceInventoryAppProperties.APP_NAME); @@ -105,6 +100,7 @@ public DeviceInventory getInventory(KapuaId scopeId, KapuaId deviceId, Long time InventoryRequestPayload inventoryRequestPayload = new InventoryRequestPayload(); InventoryEmptyRequestMessage inventoryRequestMessage = new InventoryEmptyRequestMessage() { + @Override public Class getResponseClass() { return InventoryListResponseMessage.class; @@ -136,7 +132,7 @@ public Class getResponseClass() { // Create event createDeviceEvent(scopeId, deviceId, inventoryRequestMessage, responseMessage); // Check response - return checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getDeviceInventory().orElse(deviceInventoryManagementFactory.newDeviceInventory())); + return checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getDeviceInventory().orElse(new DeviceInventory())); } @Override @@ -146,7 +142,7 @@ public DeviceInventoryBundles getBundles(KapuaId scopeId, KapuaId deviceId, Long ArgumentValidator.notNull(scopeId, SCOPE_ID); ArgumentValidator.notNull(deviceId, DEVICE_ID); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE_MANAGEMENT, Actions.read, scopeId)); + authorizationService.checkPermission(new Permission(Domains.DEVICE_MANAGEMENT, Actions.read, scopeId)); // Prepare the request InventoryRequestChannel inventoryRequestChannel = new InventoryRequestChannel(); inventoryRequestChannel.setAppName(DeviceInventoryAppProperties.APP_NAME); @@ -157,6 +153,7 @@ public DeviceInventoryBundles getBundles(KapuaId scopeId, KapuaId deviceId, Long InventoryRequestPayload inventoryRequestPayload = new InventoryRequestPayload(); InventoryEmptyRequestMessage inventoryRequestMessage = new InventoryEmptyRequestMessage() { + @Override public Class getResponseClass() { return InventoryBundlesResponseMessage.class; @@ -188,11 +185,12 @@ public Class getResponseClass() { // Create event createDeviceEvent(scopeId, deviceId, inventoryRequestMessage, responseMessage); // Check response - return checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getDeviceInventoryBundles().orElse(deviceInventoryManagementFactory.newDeviceInventoryBundles())); + return checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getDeviceInventoryBundles().orElse(new DeviceInventoryBundles())); } @Override - public void execBundle(KapuaId scopeId, KapuaId deviceId, DeviceInventoryBundle deviceInventoryBundle, DeviceInventoryBundleAction deviceInventoryBundleAction, Long timeout) throws KapuaException { + public void execBundle(KapuaId scopeId, KapuaId deviceId, DeviceInventoryBundle deviceInventoryBundle, DeviceInventoryBundleAction deviceInventoryBundleAction, Long timeout) + throws KapuaException { // Argument Validation ArgumentValidator.notNull(scopeId, SCOPE_ID); ArgumentValidator.notNull(deviceId, DEVICE_ID); @@ -204,7 +202,7 @@ public void execBundle(KapuaId scopeId, KapuaId deviceId, DeviceInventoryBundle performAdditionalValidationOnDeviceInventoryBundleId(deviceInventoryBundle.getId()); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE_MANAGEMENT, Actions.write, scopeId)); + authorizationService.checkPermission(new Permission(Domains.DEVICE_MANAGEMENT, Actions.write, scopeId)); // Prepare the request InventoryRequestChannel inventoryRequestChannel = new InventoryRequestChannel(); inventoryRequestChannel.setAppName(DeviceInventoryAppProperties.APP_NAME); @@ -221,6 +219,7 @@ public void execBundle(KapuaId scopeId, KapuaId deviceId, DeviceInventoryBundle } InventoryBundleExecRequestMessage inventoryRequestMessage = new InventoryBundleExecRequestMessage() { + @Override public Class getResponseClass() { return InventoryNoContentResponseMessage.class; @@ -262,7 +261,7 @@ public DeviceInventoryContainers getContainers(KapuaId scopeId, KapuaId deviceId ArgumentValidator.notNull(scopeId, SCOPE_ID); ArgumentValidator.notNull(deviceId, DEVICE_ID); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE_MANAGEMENT, Actions.read, scopeId)); + authorizationService.checkPermission(new Permission(Domains.DEVICE_MANAGEMENT, Actions.read, scopeId)); // Prepare the request InventoryRequestChannel inventoryRequestChannel = new InventoryRequestChannel(); inventoryRequestChannel.setAppName(DeviceInventoryAppProperties.APP_NAME); @@ -273,6 +272,7 @@ public DeviceInventoryContainers getContainers(KapuaId scopeId, KapuaId deviceId InventoryRequestPayload inventoryRequestPayload = new InventoryRequestPayload(); InventoryEmptyRequestMessage inventoryRequestMessage = new InventoryEmptyRequestMessage() { + @Override public Class getResponseClass() { return InventoryContainersResponseMessage.class; @@ -304,11 +304,13 @@ public Class getResponseClass() { // Create event createDeviceEvent(scopeId, deviceId, inventoryRequestMessage, responseMessage); // Check response - return checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getDeviceInventoryContainers().orElse(deviceInventoryManagementFactory.newDeviceInventoryContainers())); + return checkResponseAcceptedOrThrowError(responseMessage, + () -> responseMessage.getPayload().getDeviceInventoryContainers().orElse(new DeviceInventoryContainers())); } @Override - public void execContainer(KapuaId scopeId, KapuaId deviceId, DeviceInventoryContainer deviceInventoryContainer, DeviceInventoryContainerAction deviceInventoryContainerAction, Long timeout) throws KapuaException { + public void execContainer(KapuaId scopeId, KapuaId deviceId, DeviceInventoryContainer deviceInventoryContainer, DeviceInventoryContainerAction deviceInventoryContainerAction, Long timeout) + throws KapuaException { // Argument Validation ArgumentValidator.notNull(scopeId, SCOPE_ID); ArgumentValidator.notNull(deviceId, DEVICE_ID); @@ -317,7 +319,7 @@ public void execContainer(KapuaId scopeId, KapuaId deviceId, DeviceInventoryCont ArgumentValidator.notNull(deviceInventoryContainer.getVersion(), "deviceInventoryContainer.version"); ArgumentValidator.notNull(deviceInventoryContainerAction, "deviceInventoryContainerAction"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE_MANAGEMENT, Actions.write, scopeId)); + authorizationService.checkPermission(new Permission(Domains.DEVICE_MANAGEMENT, Actions.write, scopeId)); // Prepare the request InventoryRequestChannel inventoryRequestChannel = new InventoryRequestChannel(); inventoryRequestChannel.setAppName(DeviceInventoryAppProperties.APP_NAME); @@ -334,6 +336,7 @@ public void execContainer(KapuaId scopeId, KapuaId deviceId, DeviceInventoryCont } InventoryContainerExecRequestMessage inventoryRequestMessage = new InventoryContainerExecRequestMessage() { + @Override public Class getResponseClass() { return InventoryNoContentResponseMessage.class; @@ -358,7 +361,8 @@ public Class getResponseClass() { try { responseMessage = inventoryDeviceCallBuilder.send(); } catch (Exception e) { - LOG.error("Error while executing {} on DeviceInventoryContainer {}:{} for Device {}. Error: {}", deviceInventoryContainerAction, deviceInventoryContainer.getName(), deviceInventoryContainer.getVersion(), deviceId, e.getMessage(), e); + LOG.error("Error while executing {} on DeviceInventoryContainer {}:{} for Device {}. Error: {}", deviceInventoryContainerAction, deviceInventoryContainer.getName(), + deviceInventoryContainer.getVersion(), deviceId, e.getMessage(), e); throw e; } @@ -375,7 +379,7 @@ public DeviceInventorySystemPackages getSystemPackages(KapuaId scopeId, KapuaId ArgumentValidator.notNull(scopeId, SCOPE_ID); ArgumentValidator.notNull(deviceId, DEVICE_ID); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE_MANAGEMENT, Actions.read, scopeId)); + authorizationService.checkPermission(new Permission(Domains.DEVICE_MANAGEMENT, Actions.read, scopeId)); // Prepare the request InventoryRequestChannel inventoryRequestChannel = new InventoryRequestChannel(); inventoryRequestChannel.setAppName(DeviceInventoryAppProperties.APP_NAME); @@ -386,6 +390,7 @@ public DeviceInventorySystemPackages getSystemPackages(KapuaId scopeId, KapuaId InventoryRequestPayload inventoryRequestPayload = new InventoryRequestPayload(); InventoryEmptyRequestMessage inventoryRequestMessage = new InventoryEmptyRequestMessage() { + @Override public Class getResponseClass() { return InventorySystemPackagesResponseMessage.class; @@ -417,7 +422,8 @@ public Class getResponseClass() { // Create event createDeviceEvent(scopeId, deviceId, inventoryRequestMessage, responseMessage); // Check response - return checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getDeviceInventorySystemPackages().orElse(deviceInventoryManagementFactory.newDeviceInventorySystemPackages())); + return checkResponseAcceptedOrThrowError(responseMessage, + () -> responseMessage.getPayload().getDeviceInventorySystemPackages().orElse(new DeviceInventorySystemPackages())); } @Override @@ -427,7 +433,7 @@ public DeviceInventoryPackages getDeploymentPackages(KapuaId scopeId, KapuaId de ArgumentValidator.notNull(scopeId, SCOPE_ID); ArgumentValidator.notNull(deviceId, DEVICE_ID); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE_MANAGEMENT, Actions.read, scopeId)); + authorizationService.checkPermission(new Permission(Domains.DEVICE_MANAGEMENT, Actions.read, scopeId)); // Prepare the request InventoryRequestChannel inventoryRequestChannel = new InventoryRequestChannel(); inventoryRequestChannel.setAppName(DeviceInventoryAppProperties.APP_NAME); @@ -438,6 +444,7 @@ public DeviceInventoryPackages getDeploymentPackages(KapuaId scopeId, KapuaId de InventoryRequestPayload inventoryRequestPayload = new InventoryRequestPayload(); InventoryEmptyRequestMessage inventoryRequestMessage = new InventoryEmptyRequestMessage() { + @Override public Class getResponseClass() { return InventoryPackagesResponseMessage.class; @@ -469,22 +476,23 @@ public Class getResponseClass() { // Create event createDeviceEvent(scopeId, deviceId, inventoryRequestMessage, responseMessage); // Check response - return checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getDeviceInventoryPackages().orElse(deviceInventoryManagementFactory.newDeviceInventoryPackages())); + return checkResponseAcceptedOrThrowError(responseMessage, + () -> responseMessage.getPayload().getDeviceInventoryPackages().orElse(new DeviceInventoryPackages())); } - /** * Performs an additional check on {@link DeviceInventoryBundle#getId()} to verify that it can be converted to a {@link Integer}. *

        - * This check is required because initially the property was created as a {@link String} even if in Kura it is a {@link Integer}. - * See Kura documentation on Device Inventory Bundle here + * This check is required because initially the property was created as a {@link String} even if in Kura it is a {@link Integer}. See Kura documentation on Device Inventory Bundle here *

        - * We cannot change the type of {@link DeviceInventoryBundle#getId()} from {@link String} to {@link Integer} because it would be an API breaking change. - * We can add a validation to improve the error returned in case a non-integer value is provided, since the current error returned is {@link NumberFormatException} (at line - * TranslatorAppInventoryBundleExecKapuaKura:74). + * We cannot change the type of {@link DeviceInventoryBundle#getId()} from {@link String} to {@link Integer} because it would be an API breaking change. We can add a validation to improve the + * error returned in case a non-integer value is provided, since the current error returned is {@link NumberFormatException} (at line TranslatorAppInventoryBundleExecKapuaKura:74). * - * @param deviceInventoryBundleId The {@link DeviceInventoryBundle#getId()} to check - * @throws KapuaIllegalArgumentException If {@link DeviceInventoryBundle#getId()} cannot be converted to a {@link Integer}. + * @param deviceInventoryBundleId + * The {@link DeviceInventoryBundle#getId()} to check + * @throws KapuaIllegalArgumentException + * If {@link DeviceInventoryBundle#getId()} cannot be converted to a {@link Integer}. * @since 2.0.0 */ private void performAdditionalValidationOnDeviceInventoryBundleId(String deviceInventoryBundleId) throws KapuaIllegalArgumentException { diff --git a/service/device/management/inventory/internal/src/main/java/org/eclipse/kapua/service/device/management/inventory/internal/DeviceManagementInventoryModule.java b/service/device/management/inventory/internal/src/main/java/org/eclipse/kapua/service/device/management/inventory/internal/DeviceManagementInventoryModule.java index 21f99c40d43..e4f99d13546 100644 --- a/service/device/management/inventory/internal/src/main/java/org/eclipse/kapua/service/device/management/inventory/internal/DeviceManagementInventoryModule.java +++ b/service/device/management/inventory/internal/src/main/java/org/eclipse/kapua/service/device/management/inventory/internal/DeviceManagementInventoryModule.java @@ -12,42 +12,37 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.inventory.internal; -import com.google.inject.Provides; +import javax.inject.Singleton; + import org.eclipse.kapua.commons.core.AbstractKapuaModule; import org.eclipse.kapua.commons.jpa.KapuaJpaTxManagerFactory; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; -import org.eclipse.kapua.service.device.management.inventory.DeviceInventoryManagementFactory; import org.eclipse.kapua.service.device.management.inventory.DeviceInventoryManagementService; import org.eclipse.kapua.service.device.registry.DeviceRegistryService; import org.eclipse.kapua.service.device.registry.event.DeviceEventFactory; import org.eclipse.kapua.service.device.registry.event.DeviceEventService; -import javax.inject.Singleton; +import com.google.inject.Provides; public class DeviceManagementInventoryModule extends AbstractKapuaModule { + @Override protected void configureModule() { - bind(DeviceInventoryManagementFactory.class).to(DeviceInventoryManagementFactoryImpl.class); } @Provides @Singleton DeviceInventoryManagementService deviceInventoryManagementService( AuthorizationService authorizationService, - PermissionFactory permissionFactory, DeviceEventService deviceEventService, DeviceEventFactory deviceEventFactory, DeviceRegistryService deviceRegistryService, - KapuaJpaTxManagerFactory jpaTxManagerFactory, - DeviceInventoryManagementFactory deviceInventoryManagementFactory) { + KapuaJpaTxManagerFactory jpaTxManagerFactory) { return new DeviceInventoryManagementServiceImpl( jpaTxManagerFactory.create("kapua-device_management_operation_registry"), authorizationService, - permissionFactory, deviceEventService, deviceEventFactory, - deviceRegistryService, - deviceInventoryManagementFactory); + deviceRegistryService); } } diff --git a/service/device/management/inventory/internal/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/bundle/internal/DeviceInventoryBundleImpl.java b/service/device/management/inventory/internal/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/bundle/internal/DeviceInventoryBundleImpl.java deleted file mode 100644 index 03e2fc19eea..00000000000 --- a/service/device/management/inventory/internal/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/bundle/internal/DeviceInventoryBundleImpl.java +++ /dev/null @@ -1,87 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.inventory.model.bundle.internal; - -import org.eclipse.kapua.service.device.management.inventory.model.bundle.DeviceInventoryBundle; - -/** - * {@link DeviceInventoryBundle} implementation. - * - * @since 1.5.0 - */ -public class DeviceInventoryBundleImpl implements DeviceInventoryBundle { - - private String id; - private String name; - private String version; - private String status; - private Boolean signed; - - /** - * Constructor. - * - * @since 1.5.0 - */ - public DeviceInventoryBundleImpl() { - } - - @Override - public String getId() { - return id; - } - - @Override - public void setId(String id) { - this.id = id; - } - - @Override - public String getName() { - return name; - } - - @Override - public void setName(String name) { - this.name = name; - } - - @Override - public String getVersion() { - return version; - } - - @Override - public void setVersion(String version) { - this.version = version; - } - - @Override - public String getStatus() { - return status; - } - - @Override - public void setStatus(String status) { - this.status = status; - } - - @Override - public Boolean getSigned() { - return signed; - } - - @Override - public void setSigned(Boolean signed) { - this.signed = signed; - } -} diff --git a/service/device/management/inventory/internal/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/bundle/internal/DeviceInventoryBundlesImpl.java b/service/device/management/inventory/internal/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/bundle/internal/DeviceInventoryBundlesImpl.java deleted file mode 100644 index 1c0fa0760b5..00000000000 --- a/service/device/management/inventory/internal/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/bundle/internal/DeviceInventoryBundlesImpl.java +++ /dev/null @@ -1,50 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.inventory.model.bundle.internal; - -import org.eclipse.kapua.service.device.management.inventory.model.bundle.DeviceInventoryBundle; -import org.eclipse.kapua.service.device.management.inventory.model.bundle.DeviceInventoryBundles; - -import java.util.ArrayList; -import java.util.List; - -/** - * {@link DeviceInventoryBundles} implementation. - * - * @since 1.5.0 - */ -public class DeviceInventoryBundlesImpl implements DeviceInventoryBundles { - - private static final long serialVersionUID = 5229149965375932561L; - - private List inventoryBundles; - - @Override - public List getInventoryBundles() { - if (inventoryBundles == null) { - inventoryBundles = new ArrayList<>(); - } - - return inventoryBundles; - } - - @Override - public void addInventoryBundle(DeviceInventoryBundle inventoryBundle) { - getInventoryBundles().add(inventoryBundle); - } - - @Override - public void setInventoryBundles(List inventoryBundles) { - this.inventoryBundles = inventoryBundles; - } -} diff --git a/service/device/management/inventory/internal/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/container/internal/DeviceInventoryContainerImpl.java b/service/device/management/inventory/internal/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/container/internal/DeviceInventoryContainerImpl.java deleted file mode 100644 index 4f942fc5150..00000000000 --- a/service/device/management/inventory/internal/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/container/internal/DeviceInventoryContainerImpl.java +++ /dev/null @@ -1,78 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.inventory.model.container.internal; - -import org.eclipse.kapua.service.device.management.inventory.model.container.DeviceInventoryContainer; -import org.eclipse.kapua.service.device.management.inventory.model.container.DeviceInventoryContainerState; - -/** - * {@link DeviceInventoryContainer} implementation. - * - * @since 2.0.0 - */ -public class DeviceInventoryContainerImpl implements DeviceInventoryContainer { - - private String name; - private String version; - private String containerType; - - private DeviceInventoryContainerState state; - - /** - * Constructor. - * - * @since 2.0.0 - */ - public DeviceInventoryContainerImpl() { - } - - @Override - public String getName() { - return name; - } - - @Override - public void setName(String name) { - this.name = name; - } - - @Override - public String getVersion() { - return version; - } - - @Override - public void setVersion(String version) { - this.version = version; - } - - @Override - public String getContainerType() { - return containerType; - } - - @Override - public void setContainerType(String containerType) { - this.containerType = containerType; - } - - - public DeviceInventoryContainerState getState() { - return state; - } - - @Override - public void setState(DeviceInventoryContainerState state) { - this.state = state; - } -} diff --git a/service/device/management/inventory/internal/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/container/internal/DeviceInventoryContainersImpl.java b/service/device/management/inventory/internal/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/container/internal/DeviceInventoryContainersImpl.java deleted file mode 100644 index 2d2039e9161..00000000000 --- a/service/device/management/inventory/internal/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/container/internal/DeviceInventoryContainersImpl.java +++ /dev/null @@ -1,50 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.inventory.model.container.internal; - -import org.eclipse.kapua.service.device.management.inventory.model.container.DeviceInventoryContainer; -import org.eclipse.kapua.service.device.management.inventory.model.container.DeviceInventoryContainers; - -import java.util.ArrayList; -import java.util.List; - -/** - * {@link DeviceInventoryContainers} implementation. - * - * @since 2.0.0 - */ -public class DeviceInventoryContainersImpl implements DeviceInventoryContainers { - - private static final long serialVersionUID = 5229149965375932561L; - - private List inventoryContainers; - - @Override - public List getInventoryContainers() { - if (inventoryContainers == null) { - inventoryContainers = new ArrayList<>(); - } - - return inventoryContainers; - } - - @Override - public void addInventoryContainer(DeviceInventoryContainer inventoryContainer) { - getInventoryContainers().add(inventoryContainer); - } - - @Override - public void setInventoryContainers(List inventoryContainers) { - this.inventoryContainers = inventoryContainers; - } -} diff --git a/service/device/management/inventory/internal/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/inventory/internal/DeviceInventoryImpl.java b/service/device/management/inventory/internal/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/inventory/internal/DeviceInventoryImpl.java deleted file mode 100644 index c5621a1f4b2..00000000000 --- a/service/device/management/inventory/internal/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/inventory/internal/DeviceInventoryImpl.java +++ /dev/null @@ -1,50 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.inventory.model.inventory.internal; - -import org.eclipse.kapua.service.device.management.inventory.model.inventory.DeviceInventory; -import org.eclipse.kapua.service.device.management.inventory.model.inventory.DeviceInventoryItem; - -import java.util.ArrayList; -import java.util.List; - -/** - * {@link DeviceInventory} implementation. - * - * @since 1.5.0 - */ -public class DeviceInventoryImpl implements DeviceInventory { - - private static final long serialVersionUID = 734716753080998855L; - - private List inventoryItems; - - @Override - public List getInventoryItems() { - if (inventoryItems == null) { - inventoryItems = new ArrayList<>(); - } - - return inventoryItems; - } - - @Override - public void addInventoryItem(DeviceInventoryItem inventoryItem) { - getInventoryItems().add(inventoryItem); - } - - @Override - public void setInventoryItems(List inventoryItems) { - this.inventoryItems = inventoryItems; - } -} diff --git a/service/device/management/inventory/internal/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/inventory/internal/DeviceInventoryItemImpl.java b/service/device/management/inventory/internal/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/inventory/internal/DeviceInventoryItemImpl.java deleted file mode 100644 index 2759890e8bd..00000000000 --- a/service/device/management/inventory/internal/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/inventory/internal/DeviceInventoryItemImpl.java +++ /dev/null @@ -1,65 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.inventory.model.inventory.internal; - -import org.eclipse.kapua.service.device.management.inventory.model.inventory.DeviceInventoryItem; - -/** - * {@link DeviceInventoryItem} implementation. - * - * @since 1.5.0 - */ -public class DeviceInventoryItemImpl implements DeviceInventoryItem { - - private String name; - private String version; - private String itemType; - - /** - * Constructor. - * - * @since 1.5.0 - */ - public DeviceInventoryItemImpl() { - } - - @Override - public String getName() { - return name; - } - - @Override - public void setName(String name) { - this.name = name; - } - - @Override - public String getVersion() { - return version; - } - - @Override - public void setVersion(String version) { - this.version = version; - } - - @Override - public String getItemType() { - return itemType; - } - - @Override - public void setItemType(String itemType) { - this.itemType = itemType; - } -} diff --git a/service/device/management/inventory/internal/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/packages/internal/DeviceInventoryPackageImpl.java b/service/device/management/inventory/internal/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/packages/internal/DeviceInventoryPackageImpl.java deleted file mode 100644 index 783a474bf26..00000000000 --- a/service/device/management/inventory/internal/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/packages/internal/DeviceInventoryPackageImpl.java +++ /dev/null @@ -1,79 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.inventory.model.packages.internal; - -import org.eclipse.kapua.service.device.management.inventory.model.bundle.DeviceInventoryBundle; -import org.eclipse.kapua.service.device.management.inventory.model.inventory.DeviceInventoryItem; -import org.eclipse.kapua.service.device.management.inventory.model.packages.DeviceInventoryPackage; - -import java.util.ArrayList; -import java.util.List; - -/** - * {@link DeviceInventoryItem} implementation. - * - * @since 1.5.0 - */ -public class DeviceInventoryPackageImpl implements DeviceInventoryPackage { - - private String name; - private String version; - private List packageBundles; - - /** - * Constructor. - * - * @since 1.5.0 - */ - public DeviceInventoryPackageImpl() { - } - - @Override - public String getName() { - return name; - } - - @Override - public void setName(String name) { - this.name = name; - } - - @Override - public String getVersion() { - return version; - } - - @Override - public void setVersion(String version) { - this.version = version; - } - - @Override - public List getPackageBundles() { - if (packageBundles == null) { - packageBundles = new ArrayList<>(); - } - - return packageBundles; - } - - @Override - public void addPackageBundle(DeviceInventoryBundle inventoryBundle) { - getPackageBundles().add(inventoryBundle); - } - - @Override - public void setPackageBundles(List packageBundles) { - this.packageBundles = packageBundles; - } -} diff --git a/service/device/management/inventory/internal/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/packages/internal/DeviceInventoryPackagesImpl.java b/service/device/management/inventory/internal/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/packages/internal/DeviceInventoryPackagesImpl.java deleted file mode 100644 index c948f7d50c6..00000000000 --- a/service/device/management/inventory/internal/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/packages/internal/DeviceInventoryPackagesImpl.java +++ /dev/null @@ -1,51 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.inventory.model.packages.internal; - -import org.eclipse.kapua.service.device.management.inventory.model.packages.DeviceInventoryPackage; -import org.eclipse.kapua.service.device.management.inventory.model.packages.DeviceInventoryPackages; -import org.eclipse.kapua.service.device.management.inventory.model.system.DeviceInventorySystemPackages; - -import java.util.ArrayList; -import java.util.List; - -/** - * {@link DeviceInventorySystemPackages} implementation. - * - * @since 1.5.0 - */ -public class DeviceInventoryPackagesImpl implements DeviceInventoryPackages { - - private static final long serialVersionUID = -8272540683907649241L; - - private List packages; - - @Override - public List getPackages() { - if (packages == null) { - packages = new ArrayList<>(); - } - - return packages; - } - - @Override - public void addPackage(DeviceInventoryPackage aPackage) { - getPackages().add(aPackage); - } - - @Override - public void setPackages(List packages) { - this.packages = packages; - } -} diff --git a/service/device/management/inventory/internal/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/system/internal/DeviceInventorySystemPackageImpl.java b/service/device/management/inventory/internal/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/system/internal/DeviceInventorySystemPackageImpl.java deleted file mode 100644 index b9b6bf73f36..00000000000 --- a/service/device/management/inventory/internal/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/system/internal/DeviceInventorySystemPackageImpl.java +++ /dev/null @@ -1,65 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.inventory.model.system.internal; - -import org.eclipse.kapua.service.device.management.inventory.model.system.DeviceInventorySystemPackage; - -/** - * {@link DeviceInventorySystemPackage} implementation. - * - * @since 1.5.0 - */ -public class DeviceInventorySystemPackageImpl implements DeviceInventorySystemPackage { - - private String name; - private String version; - private String packageType; - - /** - * Constructor. - * - * @since 1.5.0 - */ - public DeviceInventorySystemPackageImpl() { - } - - @Override - public String getName() { - return name; - } - - @Override - public void setName(String name) { - this.name = name; - } - - @Override - public String getVersion() { - return version; - } - - @Override - public void setVersion(String version) { - this.version = version; - } - - @Override - public String getPackageType() { - return packageType; - } - - @Override - public void setPackageType(String packageType) { - this.packageType = packageType; - } -} diff --git a/service/device/management/inventory/internal/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/system/internal/DeviceInventorySystemPackagesImpl.java b/service/device/management/inventory/internal/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/system/internal/DeviceInventorySystemPackagesImpl.java deleted file mode 100644 index 5c450d199df..00000000000 --- a/service/device/management/inventory/internal/src/main/java/org/eclipse/kapua/service/device/management/inventory/model/system/internal/DeviceInventorySystemPackagesImpl.java +++ /dev/null @@ -1,50 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.inventory.model.system.internal; - -import org.eclipse.kapua.service.device.management.inventory.model.system.DeviceInventorySystemPackage; -import org.eclipse.kapua.service.device.management.inventory.model.system.DeviceInventorySystemPackages; - -import java.util.ArrayList; -import java.util.List; - -/** - * {@link DeviceInventorySystemPackages} implementation. - * - * @since 1.5.0 - */ -public class DeviceInventorySystemPackagesImpl implements DeviceInventorySystemPackages { - - private static final long serialVersionUID = -3824464082139248997L; - - private List systemPackages; - - @Override - public List getSystemPackages() { - if (systemPackages == null) { - systemPackages = new ArrayList<>(); - } - - return systemPackages; - } - - @Override - public void addSystemPackage(DeviceInventorySystemPackage systemPackage) { - getSystemPackages().add(systemPackage); - } - - @Override - public void setSystemPackages(List systemPackages) { - this.systemPackages = systemPackages; - } -} diff --git a/service/device/management/inventory/pom.xml b/service/device/management/inventory/pom.xml index 2a974021de2..af59942217a 100644 --- a/service/device/management/inventory/pom.xml +++ b/service/device/management/inventory/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-device-management - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-device-management-inventory diff --git a/service/device/management/job/api/pom.xml b/service/device/management/job/api/pom.xml index 87b32430a06..fe5198f18a6 100644 --- a/service/device/management/job/api/pom.xml +++ b/service/device/management/job/api/pom.xml @@ -18,7 +18,7 @@ kapua-device-management-job org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-device-management-job-api diff --git a/service/device/management/job/api/src/main/java/org/eclipse/kapua/service/device/management/job/JobDeviceManagementOperationCreator.java b/service/device/management/job/api/src/main/java/org/eclipse/kapua/service/device/management/job/JobDeviceManagementOperationCreator.java index cb29b88c086..09591e77a9c 100644 --- a/service/device/management/job/api/src/main/java/org/eclipse/kapua/service/device/management/job/JobDeviceManagementOperationCreator.java +++ b/service/device/management/job/api/src/main/java/org/eclipse/kapua/service/device/management/job/JobDeviceManagementOperationCreator.java @@ -12,24 +12,39 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.job; -import org.eclipse.kapua.model.KapuaEntityCreator; -import org.eclipse.kapua.model.id.KapuaId; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; +import org.eclipse.kapua.commons.model.id.KapuaEid; +import org.eclipse.kapua.model.KapuaEntityCreator; +import org.eclipse.kapua.model.id.KapuaId; + /** - * {@link JobDeviceManagementOperationCreator} encapsulates all the information needed to create a new {@link JobDeviceManagementOperation} in the system.
        - * The data provided will be used to seed the new {@link JobDeviceManagementOperation}. + * {@link JobDeviceManagementOperationCreator} encapsulates all the information needed to create a new {@link JobDeviceManagementOperation} in the system.
        The data provided will be used to seed + * the new {@link JobDeviceManagementOperation}. * * @since 1.1.0 */ @XmlRootElement(name = "jobDeviceManagementOperationCreator") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = JobDeviceManagementOperationXmlRegistry.class, factoryMethod = "newJobDeviceManagementOperationCreator") -public interface JobDeviceManagementOperationCreator extends KapuaEntityCreator { +@XmlType +public class JobDeviceManagementOperationCreator extends KapuaEntityCreator { + + private KapuaId jobId; + private KapuaId deviceManagementOperationId; + + public JobDeviceManagementOperationCreator() { + } + + public JobDeviceManagementOperationCreator(KapuaId scopeId) { + super(scopeId); + } + + public JobDeviceManagementOperationCreator(KapuaEntityCreator entityCreator) { + super(entityCreator); + } /** * Gets the {@link org.eclipse.kapua.service.job.Job} {@link KapuaId}. @@ -37,15 +52,20 @@ public interface JobDeviceManagementOperationCreator extends KapuaEntityCreator< * @return The {@link org.eclipse.kapua.service.job.Job} {@link KapuaId}. * @since 1.1.0 */ - KapuaId getJobId(); + public KapuaId getJobId() { + return jobId; + } /** * Sets the {@link org.eclipse.kapua.service.job.Job} {@link KapuaId}. * - * @param jobId The {@link org.eclipse.kapua.service.job.Job} {@link KapuaId}. + * @param jobId + * The {@link org.eclipse.kapua.service.job.Job} {@link KapuaId}. * @since 1.1.0 */ - void setJobId(KapuaId jobId); + public void setJobId(KapuaId jobId) { + this.jobId = jobId; + } /** * Gets the {@link org.eclipse.kapua.service.device.management.registry.operation.DeviceManagementOperation} {@link KapuaId}. @@ -53,13 +73,18 @@ public interface JobDeviceManagementOperationCreator extends KapuaEntityCreator< * @return The {@link org.eclipse.kapua.service.device.management.registry.operation.DeviceManagementOperation} {@link KapuaId}. * @since 1.1.0 */ - KapuaId getDeviceManagementOperationId(); + public KapuaId getDeviceManagementOperationId() { + return deviceManagementOperationId; + } /** * Sets the {@link org.eclipse.kapua.service.device.management.registry.operation.DeviceManagementOperation} {@link KapuaId}. * - * @param deviceManagementOperationId The {@link org.eclipse.kapua.service.device.management.registry.operation.DeviceManagementOperation} {@link KapuaId}. + * @param deviceManagementOperationId + * The {@link org.eclipse.kapua.service.device.management.registry.operation.DeviceManagementOperation} {@link KapuaId}. * @since 1.1.0 */ - void setDeviceManagementOperationId(KapuaId deviceManagementOperationId); + public void setDeviceManagementOperationId(KapuaId deviceManagementOperationId) { + this.deviceManagementOperationId = KapuaEid.parseKapuaId(deviceManagementOperationId); + } } diff --git a/service/device/management/job/api/src/main/java/org/eclipse/kapua/service/device/management/job/JobDeviceManagementOperationFactory.java b/service/device/management/job/api/src/main/java/org/eclipse/kapua/service/device/management/job/JobDeviceManagementOperationFactory.java index e44a31feee6..d3489bd6847 100644 --- a/service/device/management/job/api/src/main/java/org/eclipse/kapua/service/device/management/job/JobDeviceManagementOperationFactory.java +++ b/service/device/management/job/api/src/main/java/org/eclipse/kapua/service/device/management/job/JobDeviceManagementOperationFactory.java @@ -19,6 +19,6 @@ * * @since 1.1.0 */ -public interface JobDeviceManagementOperationFactory extends KapuaEntityFactory { +public interface JobDeviceManagementOperationFactory extends KapuaEntityFactory { } diff --git a/service/device/management/job/api/src/main/java/org/eclipse/kapua/service/device/management/job/JobDeviceManagementOperationListResult.java b/service/device/management/job/api/src/main/java/org/eclipse/kapua/service/device/management/job/JobDeviceManagementOperationListResult.java index c7c8afb6642..5a8855a82d8 100644 --- a/service/device/management/job/api/src/main/java/org/eclipse/kapua/service/device/management/job/JobDeviceManagementOperationListResult.java +++ b/service/device/management/job/api/src/main/java/org/eclipse/kapua/service/device/management/job/JobDeviceManagementOperationListResult.java @@ -12,13 +12,13 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.job; -import org.eclipse.kapua.model.query.KapuaListResult; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; +import org.eclipse.kapua.model.query.KapuaListResult; + /** * {@link JobDeviceManagementOperationListResult} definition. * @@ -26,7 +26,7 @@ */ @XmlRootElement(name = "jobDeviceManagementOperationListResult") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = JobDeviceManagementOperationXmlRegistry.class, factoryMethod = "newJobDeviceManagementOperationListResult") -public interface JobDeviceManagementOperationListResult extends KapuaListResult { +@XmlType +public class JobDeviceManagementOperationListResult extends KapuaListResult { } diff --git a/service/device/management/job/api/src/main/java/org/eclipse/kapua/service/device/management/job/JobDeviceManagementOperationQuery.java b/service/device/management/job/api/src/main/java/org/eclipse/kapua/service/device/management/job/JobDeviceManagementOperationQuery.java deleted file mode 100644 index 35d1f7f4557..00000000000 --- a/service/device/management/job/api/src/main/java/org/eclipse/kapua/service/device/management/job/JobDeviceManagementOperationQuery.java +++ /dev/null @@ -1,32 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2019, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.job; - -import org.eclipse.kapua.model.query.KapuaQuery; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlType; - -/** - * {@link JobDeviceManagementOperation} {@link KapuaQuery} definition. - * - * @see KapuaQuery - * @since 1.1.0 - */ -@XmlRootElement(name = "query") -@XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = JobDeviceManagementOperationXmlRegistry.class, factoryMethod = "newQuery") -public interface JobDeviceManagementOperationQuery extends KapuaQuery { -} diff --git a/service/device/management/job/api/src/main/java/org/eclipse/kapua/service/device/management/job/JobDeviceManagementOperationService.java b/service/device/management/job/api/src/main/java/org/eclipse/kapua/service/device/management/job/JobDeviceManagementOperationService.java index bb2617b5aac..9772c463537 100644 --- a/service/device/management/job/api/src/main/java/org/eclipse/kapua/service/device/management/job/JobDeviceManagementOperationService.java +++ b/service/device/management/job/api/src/main/java/org/eclipse/kapua/service/device/management/job/JobDeviceManagementOperationService.java @@ -26,7 +26,8 @@ public interface JobDeviceManagementOperationService extends KapuaEntityService< /** * Returns the {@link JobDeviceManagementOperationListResult} with elements matching the provided query. * - * @param query The {@link JobDeviceManagementOperationQuery} used to filter results. + * @param query + * The {@link KapuaQuery} used to filter results. * @return The {@link JobDeviceManagementOperationListResult} with elements matching the query parameter. * @throws KapuaException * @since 1.1.0 diff --git a/service/device/management/job/api/src/main/java/org/eclipse/kapua/service/device/management/job/JobDeviceManagementOperationXmlRegistry.java b/service/device/management/job/api/src/main/java/org/eclipse/kapua/service/device/management/job/JobDeviceManagementOperationXmlRegistry.java index 604a0f8d1d0..5faf4264281 100644 --- a/service/device/management/job/api/src/main/java/org/eclipse/kapua/service/device/management/job/JobDeviceManagementOperationXmlRegistry.java +++ b/service/device/management/job/api/src/main/java/org/eclipse/kapua/service/device/management/job/JobDeviceManagementOperationXmlRegistry.java @@ -12,10 +12,10 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.job; -import org.eclipse.kapua.locator.KapuaLocator; - import javax.xml.bind.annotation.XmlRegistry; +import org.eclipse.kapua.locator.KapuaLocator; + /** * {@link JobDeviceManagementOperation} xml factory class * @@ -29,16 +29,4 @@ public class JobDeviceManagementOperationXmlRegistry { public JobDeviceManagementOperation newJobDeviceManagementOperation() { return jobDeviceManagementOperationFactory.newEntity(null); } - - public JobDeviceManagementOperationCreator newJobDeviceManagementOperationCreator() { - return jobDeviceManagementOperationFactory.newCreator(null); - } - - public JobDeviceManagementOperationListResult newJobDeviceManagementOperationListResult() { - return jobDeviceManagementOperationFactory.newListResult(); - } - - public JobDeviceManagementOperationQuery newQuery() { - return jobDeviceManagementOperationFactory.newQuery(null); - } } diff --git a/service/device/management/job/internal/pom.xml b/service/device/management/job/internal/pom.xml index d85ba14ed1f..6ee3757752f 100644 --- a/service/device/management/job/internal/pom.xml +++ b/service/device/management/job/internal/pom.xml @@ -18,7 +18,7 @@ kapua-device-management-job org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-device-management-job-internal diff --git a/service/device/management/job/internal/src/main/java/org/eclipse/kapua/service/device/management/job/internal/DeviceManagementJobModule.java b/service/device/management/job/internal/src/main/java/org/eclipse/kapua/service/device/management/job/internal/DeviceManagementJobModule.java index e36951ecf53..cde4cfeefce 100644 --- a/service/device/management/job/internal/src/main/java/org/eclipse/kapua/service/device/management/job/internal/DeviceManagementJobModule.java +++ b/service/device/management/job/internal/src/main/java/org/eclipse/kapua/service/device/management/job/internal/DeviceManagementJobModule.java @@ -12,19 +12,20 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.job.internal; -import com.google.inject.Provides; +import javax.inject.Singleton; + import org.eclipse.kapua.commons.core.AbstractKapuaModule; import org.eclipse.kapua.commons.jpa.KapuaJpaRepositoryConfiguration; import org.eclipse.kapua.commons.jpa.KapuaJpaTxManagerFactory; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; import org.eclipse.kapua.service.device.management.job.JobDeviceManagementOperationFactory; import org.eclipse.kapua.service.device.management.job.JobDeviceManagementOperationRepository; import org.eclipse.kapua.service.device.management.job.JobDeviceManagementOperationService; -import javax.inject.Singleton; +import com.google.inject.Provides; public class DeviceManagementJobModule extends AbstractKapuaModule { + @Override protected void configureModule() { bind(JobDeviceManagementOperationFactory.class).to(JobDeviceManagementOperationFactoryImpl.class); @@ -35,12 +36,10 @@ protected void configureModule() { public JobDeviceManagementOperationService jobDeviceManagementOperationService( JobDeviceManagementOperationFactory entityFactory, AuthorizationService authorizationService, - PermissionFactory permissionFactory, JobDeviceManagementOperationRepository repository, KapuaJpaTxManagerFactory jpaTxManagerFactory) { return new JobDeviceManagementOperationServiceImpl(entityFactory, authorizationService, - permissionFactory, jpaTxManagerFactory.create("kapua-job-device-management-operation"), repository); } diff --git a/service/device/management/job/internal/src/main/java/org/eclipse/kapua/service/device/management/job/internal/JobDeviceManagementOperationCreatorImpl.java b/service/device/management/job/internal/src/main/java/org/eclipse/kapua/service/device/management/job/internal/JobDeviceManagementOperationCreatorImpl.java deleted file mode 100644 index f4b92a1630a..00000000000 --- a/service/device/management/job/internal/src/main/java/org/eclipse/kapua/service/device/management/job/internal/JobDeviceManagementOperationCreatorImpl.java +++ /dev/null @@ -1,54 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2019, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.job.internal; - -import org.eclipse.kapua.commons.model.AbstractKapuaEntityCreator; -import org.eclipse.kapua.commons.model.id.KapuaEid; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.device.management.job.JobDeviceManagementOperation; -import org.eclipse.kapua.service.device.management.job.JobDeviceManagementOperationCreator; - -/** - * {@link JobDeviceManagementOperationCreator} implementation - * - * @since 1.1.0 - */ -public class JobDeviceManagementOperationCreatorImpl extends AbstractKapuaEntityCreator implements JobDeviceManagementOperationCreator { - - private KapuaId jobId; - private KapuaId deviceManagementOperationId; - - public JobDeviceManagementOperationCreatorImpl(KapuaId scopeId) { - super(scopeId); - } - - @Override - public KapuaId getJobId() { - return jobId; - } - - @Override - public void setJobId(KapuaId jobId) { - this.jobId = jobId; - } - - @Override - public KapuaId getDeviceManagementOperationId() { - return deviceManagementOperationId; - } - - @Override - public void setDeviceManagementOperationId(KapuaId deviceManagementOperationId) { - this.deviceManagementOperationId = KapuaEid.parseKapuaId(deviceManagementOperationId); - } -} diff --git a/service/device/management/job/internal/src/main/java/org/eclipse/kapua/service/device/management/job/internal/JobDeviceManagementOperationFactoryImpl.java b/service/device/management/job/internal/src/main/java/org/eclipse/kapua/service/device/management/job/internal/JobDeviceManagementOperationFactoryImpl.java index cbd204575e2..3cfb76daea5 100644 --- a/service/device/management/job/internal/src/main/java/org/eclipse/kapua/service/device/management/job/internal/JobDeviceManagementOperationFactoryImpl.java +++ b/service/device/management/job/internal/src/main/java/org/eclipse/kapua/service/device/management/job/internal/JobDeviceManagementOperationFactoryImpl.java @@ -12,15 +12,12 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.job.internal; +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaEntityCloneException; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.device.management.job.JobDeviceManagementOperation; -import org.eclipse.kapua.service.device.management.job.JobDeviceManagementOperationCreator; import org.eclipse.kapua.service.device.management.job.JobDeviceManagementOperationFactory; -import org.eclipse.kapua.service.device.management.job.JobDeviceManagementOperationListResult; -import org.eclipse.kapua.service.device.management.job.JobDeviceManagementOperationQuery; - -import javax.inject.Singleton; /** * {@link JobDeviceManagementOperationFactory} implementation. @@ -35,21 +32,6 @@ public JobDeviceManagementOperation newEntity(KapuaId scopeId) { return new JobDeviceManagementOperationImpl(scopeId); } - @Override - public JobDeviceManagementOperationCreator newCreator(KapuaId scopeId) { - return new JobDeviceManagementOperationCreatorImpl(scopeId); - } - - @Override - public JobDeviceManagementOperationQuery newQuery(KapuaId scopeId) { - return new JobDeviceManagementOperationQueryImpl(scopeId); - } - - @Override - public JobDeviceManagementOperationListResult newListResult() { - return new JobDeviceManagementOperationListResultImpl(); - } - @Override public JobDeviceManagementOperation clone(JobDeviceManagementOperation jobDeviceManagementOperation) { try { diff --git a/service/device/management/job/internal/src/main/java/org/eclipse/kapua/service/device/management/job/internal/JobDeviceManagementOperationImplJpaRepository.java b/service/device/management/job/internal/src/main/java/org/eclipse/kapua/service/device/management/job/internal/JobDeviceManagementOperationImplJpaRepository.java index dbd24d8cefb..68198b09322 100644 --- a/service/device/management/job/internal/src/main/java/org/eclipse/kapua/service/device/management/job/internal/JobDeviceManagementOperationImplJpaRepository.java +++ b/service/device/management/job/internal/src/main/java/org/eclipse/kapua/service/device/management/job/internal/JobDeviceManagementOperationImplJpaRepository.java @@ -21,7 +21,8 @@ public class JobDeviceManagementOperationImplJpaRepository extends KapuaUpdatableEntityJpaRepository implements JobDeviceManagementOperationRepository { + public JobDeviceManagementOperationImplJpaRepository(KapuaJpaRepositoryConfiguration jpaRepoConfig) { - super(JobDeviceManagementOperationImpl.class, JobDeviceManagementOperation.TYPE, () -> new JobDeviceManagementOperationListResultImpl(), jpaRepoConfig); + super(JobDeviceManagementOperationImpl.class, JobDeviceManagementOperation.TYPE, () -> new JobDeviceManagementOperationListResult(), jpaRepoConfig); } } diff --git a/service/device/management/job/internal/src/main/java/org/eclipse/kapua/service/device/management/job/internal/JobDeviceManagementOperationListResultImpl.java b/service/device/management/job/internal/src/main/java/org/eclipse/kapua/service/device/management/job/internal/JobDeviceManagementOperationListResultImpl.java deleted file mode 100644 index cfd1a91eaf7..00000000000 --- a/service/device/management/job/internal/src/main/java/org/eclipse/kapua/service/device/management/job/internal/JobDeviceManagementOperationListResultImpl.java +++ /dev/null @@ -1,25 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2019, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.job.internal; - -import org.eclipse.kapua.commons.model.query.KapuaListResultImpl; -import org.eclipse.kapua.service.device.management.job.JobDeviceManagementOperation; -import org.eclipse.kapua.service.device.management.job.JobDeviceManagementOperationListResult; - -/** - * {@link JobDeviceManagementOperationListResult} implementation. - * - * @since 1.1.0 - */ -public class JobDeviceManagementOperationListResultImpl extends KapuaListResultImpl implements JobDeviceManagementOperationListResult { -} diff --git a/service/device/management/job/internal/src/main/java/org/eclipse/kapua/service/device/management/job/internal/JobDeviceManagementOperationQueryImpl.java b/service/device/management/job/internal/src/main/java/org/eclipse/kapua/service/device/management/job/internal/JobDeviceManagementOperationQueryImpl.java deleted file mode 100644 index 2f0b27f35d8..00000000000 --- a/service/device/management/job/internal/src/main/java/org/eclipse/kapua/service/device/management/job/internal/JobDeviceManagementOperationQueryImpl.java +++ /dev/null @@ -1,35 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2019, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.job.internal; - -import org.eclipse.kapua.commons.model.query.AbstractKapuaQuery; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.device.management.job.JobDeviceManagementOperationQuery; - -/** - * {@link JobDeviceManagementOperationQuery} definition. - * - * @since 1.1.0 - */ -public class JobDeviceManagementOperationQueryImpl extends AbstractKapuaQuery implements JobDeviceManagementOperationQuery { - - /** - * Constructor. - * - * @param scopeId The {@link #getScopeId()}. - * @since 1.1.0 - */ - public JobDeviceManagementOperationQueryImpl(KapuaId scopeId) { - super(scopeId); - } -} diff --git a/service/device/management/job/internal/src/main/java/org/eclipse/kapua/service/device/management/job/internal/JobDeviceManagementOperationServiceImpl.java b/service/device/management/job/internal/src/main/java/org/eclipse/kapua/service/device/management/job/internal/JobDeviceManagementOperationServiceImpl.java index 9a63d5a979a..9dcd11af9f6 100644 --- a/service/device/management/job/internal/src/main/java/org/eclipse/kapua/service/device/management/job/internal/JobDeviceManagementOperationServiceImpl.java +++ b/service/device/management/job/internal/src/main/java/org/eclipse/kapua/service/device/management/job/internal/JobDeviceManagementOperationServiceImpl.java @@ -12,34 +12,34 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.job.internal; +import java.util.AbstractMap; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import javax.inject.Inject; +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaEntityUniquenessException; import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.commons.model.domains.Domains; -import org.eclipse.kapua.commons.model.query.predicate.AndPredicateImpl; -import org.eclipse.kapua.commons.model.query.predicate.AttributePredicateImpl; import org.eclipse.kapua.commons.util.ArgumentValidator; import org.eclipse.kapua.model.domain.Actions; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.model.query.KapuaQuery; +import org.eclipse.kapua.model.query.predicate.AndPredicate; +import org.eclipse.kapua.model.query.predicate.AttributePredicate; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; +import org.eclipse.kapua.service.authorization.permission.Permission; import org.eclipse.kapua.service.device.management.job.JobDeviceManagementOperation; import org.eclipse.kapua.service.device.management.job.JobDeviceManagementOperationAttributes; import org.eclipse.kapua.service.device.management.job.JobDeviceManagementOperationCreator; import org.eclipse.kapua.service.device.management.job.JobDeviceManagementOperationFactory; import org.eclipse.kapua.service.device.management.job.JobDeviceManagementOperationListResult; -import org.eclipse.kapua.service.device.management.job.JobDeviceManagementOperationQuery; import org.eclipse.kapua.service.device.management.job.JobDeviceManagementOperationRepository; import org.eclipse.kapua.service.device.management.job.JobDeviceManagementOperationService; import org.eclipse.kapua.storage.TxManager; -import javax.inject.Inject; -import javax.inject.Singleton; -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - /** * {@link JobDeviceManagementOperationService} implementation * @@ -51,7 +51,6 @@ public class JobDeviceManagementOperationServiceImpl private final JobDeviceManagementOperationFactory entityFactory; private final AuthorizationService authorizationService; - private final PermissionFactory permissionFactory; private final TxManager txManager; private final JobDeviceManagementOperationRepository repository; @@ -59,12 +58,10 @@ public class JobDeviceManagementOperationServiceImpl public JobDeviceManagementOperationServiceImpl( JobDeviceManagementOperationFactory entityFactory, AuthorizationService authorizationService, - PermissionFactory permissionFactory, TxManager txManager, JobDeviceManagementOperationRepository repository) { this.entityFactory = entityFactory; this.authorizationService = authorizationService; - this.permissionFactory = permissionFactory; this.txManager = txManager; this.repository = repository; } @@ -77,13 +74,13 @@ public JobDeviceManagementOperation create(JobDeviceManagementOperationCreator j ArgumentValidator.notNull(jobDeviceManagementOperationCreator.getJobId(), "jobDeviceManagementOperationCreator.jobId"); ArgumentValidator.notNull(jobDeviceManagementOperationCreator.getDeviceManagementOperationId(), "jobDeviceManagementOperationCreator.deviceManagementOperationId"); // Check access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.write, null)); + authorizationService.checkPermission(new Permission(Domains.JOB, Actions.write, null)); // Check duplicate - JobDeviceManagementOperationQuery query = new JobDeviceManagementOperationQueryImpl(jobDeviceManagementOperationCreator.getScopeId()); + KapuaQuery query = new KapuaQuery(jobDeviceManagementOperationCreator.getScopeId()); query.setPredicate( - new AndPredicateImpl( - new AttributePredicateImpl<>(JobDeviceManagementOperationAttributes.JOB_ID, jobDeviceManagementOperationCreator.getJobId()), - new AttributePredicateImpl<>(JobDeviceManagementOperationAttributes.DEVICE_MANAGEMENT_OPERATION_ID, jobDeviceManagementOperationCreator.getDeviceManagementOperationId()) + new AndPredicate( + new AttributePredicate<>(JobDeviceManagementOperationAttributes.JOB_ID, jobDeviceManagementOperationCreator.getJobId()), + new AttributePredicate<>(JobDeviceManagementOperationAttributes.DEVICE_MANAGEMENT_OPERATION_ID, jobDeviceManagementOperationCreator.getDeviceManagementOperationId()) ) ); @@ -92,7 +89,8 @@ public JobDeviceManagementOperation create(JobDeviceManagementOperationCreator j List> uniqueAttributes = new ArrayList<>(); uniqueAttributes.add(new AbstractMap.SimpleEntry<>(JobDeviceManagementOperationAttributes.JOB_ID, jobDeviceManagementOperationCreator.getJobId())); - uniqueAttributes.add(new AbstractMap.SimpleEntry<>(JobDeviceManagementOperationAttributes.DEVICE_MANAGEMENT_OPERATION_ID, jobDeviceManagementOperationCreator.getDeviceManagementOperationId())); + uniqueAttributes.add( + new AbstractMap.SimpleEntry<>(JobDeviceManagementOperationAttributes.DEVICE_MANAGEMENT_OPERATION_ID, jobDeviceManagementOperationCreator.getDeviceManagementOperationId())); throw new KapuaEntityUniquenessException(JobDeviceManagementOperation.TYPE, uniqueAttributes); } @@ -112,7 +110,7 @@ public JobDeviceManagementOperation find(KapuaId scopeId, KapuaId jobDeviceManag ArgumentValidator.notNull(scopeId, "scopeId"); ArgumentValidator.notNull(jobDeviceManagementOperationId, "jobDeviceManagementOperationId"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.write, scopeId)); + authorizationService.checkPermission(new Permission(Domains.JOB, Actions.write, scopeId)); // Do find return txManager.execute(tx -> repository.find(tx, scopeId, jobDeviceManagementOperationId)) .orElse(null); @@ -123,7 +121,7 @@ public JobDeviceManagementOperationListResult query(KapuaQuery query) throws Kap // Argument Validation ArgumentValidator.notNull(query, "query"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.read, query.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.JOB, Actions.read, query.getScopeId())); // Do query return txManager.execute(tx -> repository.query(tx, query)); } @@ -133,7 +131,7 @@ public long count(KapuaQuery query) throws KapuaException { // Argument Validation ArgumentValidator.notNull(query, "query"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.read, query.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.JOB, Actions.read, query.getScopeId())); // Do query return txManager.execute(tx -> repository.count(tx, query)); } @@ -145,7 +143,7 @@ public void delete(KapuaId scopeId, KapuaId jobDeviceManagementOperationId) thro ArgumentValidator.notNull(jobDeviceManagementOperationId, "jobDeviceManagementOperationId"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.delete, scopeId)); + authorizationService.checkPermission(new Permission(Domains.JOB, Actions.delete, scopeId)); // Do delete txManager.execute(tx -> repository.delete(tx, scopeId, jobDeviceManagementOperationId)); diff --git a/service/device/management/job/internal/src/main/java/org/eclipse/kapua/service/device/management/job/manager/internal/JobDeviceManagementOperationManagerServiceImpl.java b/service/device/management/job/internal/src/main/java/org/eclipse/kapua/service/device/management/job/manager/internal/JobDeviceManagementOperationManagerServiceImpl.java index aad30fefc6c..8312bc1ab39 100644 --- a/service/device/management/job/internal/src/main/java/org/eclipse/kapua/service/device/management/job/manager/internal/JobDeviceManagementOperationManagerServiceImpl.java +++ b/service/device/management/job/internal/src/main/java/org/eclipse/kapua/service/device/management/job/manager/internal/JobDeviceManagementOperationManagerServiceImpl.java @@ -12,17 +12,20 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.job.manager.internal; +import java.util.Date; + +import javax.inject.Inject; +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaEntityNotFoundException; import org.eclipse.kapua.KapuaException; -import org.eclipse.kapua.job.engine.JobEngineFactory; import org.eclipse.kapua.job.engine.JobEngineService; import org.eclipse.kapua.job.engine.JobStartOptions; import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.service.device.management.job.JobDeviceManagementOperation; import org.eclipse.kapua.service.device.management.job.JobDeviceManagementOperationAttributes; -import org.eclipse.kapua.service.device.management.job.JobDeviceManagementOperationFactory; import org.eclipse.kapua.service.device.management.job.JobDeviceManagementOperationListResult; -import org.eclipse.kapua.service.device.management.job.JobDeviceManagementOperationQuery; import org.eclipse.kapua.service.device.management.job.JobDeviceManagementOperationService; import org.eclipse.kapua.service.device.management.job.manager.JobDeviceManagementOperationManagerService; import org.eclipse.kapua.service.device.management.message.notification.NotifyStatus; @@ -32,18 +35,12 @@ import org.eclipse.kapua.service.device.management.registry.operation.notification.ManagementOperationNotification; import org.eclipse.kapua.service.job.targets.JobTarget; import org.eclipse.kapua.service.job.targets.JobTargetAttributes; -import org.eclipse.kapua.service.job.targets.JobTargetFactory; import org.eclipse.kapua.service.job.targets.JobTargetListResult; -import org.eclipse.kapua.service.job.targets.JobTargetQuery; import org.eclipse.kapua.service.job.targets.JobTargetService; import org.eclipse.kapua.service.job.targets.JobTargetStatus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.inject.Inject; -import javax.inject.Singleton; -import java.util.Date; - /** * {@link JobDeviceManagementOperationManagerService} implementation. * @@ -56,28 +53,19 @@ public class JobDeviceManagementOperationManagerServiceImpl implements JobDevice private final DeviceManagementOperationRegistryService deviceManagementOperationRegistryService; private final JobDeviceManagementOperationService jobDeviceManagementOperationService; - private final JobDeviceManagementOperationFactory jobDeviceManagementOperationFactory; private final JobEngineService jobEngineService; - private final JobEngineFactory jobEngineFactory; private final JobTargetService jobTargetService; - private final JobTargetFactory jobTargetFactory; @Inject public JobDeviceManagementOperationManagerServiceImpl( DeviceManagementOperationRegistryService deviceManagementOperationRegistryService, JobDeviceManagementOperationService jobDeviceManagementOperationService, - JobDeviceManagementOperationFactory jobDeviceManagementOperationFactory, JobEngineService jobEngineService, - JobEngineFactory jobEngineFactory, - JobTargetService jobTargetService, - JobTargetFactory jobTargetFactory) { + JobTargetService jobTargetService) { this.deviceManagementOperationRegistryService = deviceManagementOperationRegistryService; this.jobDeviceManagementOperationService = jobDeviceManagementOperationService; - this.jobDeviceManagementOperationFactory = jobDeviceManagementOperationFactory; this.jobEngineService = jobEngineService; - this.jobEngineFactory = jobEngineFactory; this.jobTargetService = jobTargetService; - this.jobTargetFactory = jobTargetFactory; } @Override @@ -100,7 +88,7 @@ public void processJobTargetOnNotification(KapuaId scopeId, KapuaId operationId, return; } - JobTargetQuery jobTargetQuery = jobTargetFactory.newQuery(scopeId); + KapuaQuery jobTargetQuery = new KapuaQuery(scopeId); jobTargetQuery.setPredicate( jobTargetQuery.andPredicate( jobTargetQuery.attributePredicate(JobTargetAttributes.JOB_ID, jobDeviceManagementOperation.getJobId()), @@ -118,20 +106,21 @@ public void processJobTargetOnNotification(KapuaId scopeId, KapuaId operationId, jobTarget = jobTargets.getFirstItem(); if (jobTarget == null) { - LOG.warn("JobTarget with targetId {} for Job {} not found! This is something strange that happened and needs some checking! Reference JobDeviceManagementOperation: {}", deviceManagementOperation.getDeviceId(), jobDeviceManagementOperation.getJobId(), jobDeviceManagementOperation.getId()); + LOG.warn("JobTarget with targetId {} for Job {} not found! This is something strange that happened and needs some checking! Reference JobDeviceManagementOperation: {}", + deviceManagementOperation.getDeviceId(), jobDeviceManagementOperation.getJobId(), jobDeviceManagementOperation.getId()); return; } switch (status) { - case COMPLETED: - jobTarget.setStatus(JobTargetStatus.NOTIFIED_COMPLETION); - break; - case FAILED: - jobTarget.setStatus(JobTargetStatus.PROCESS_FAILED); - break; - case STALE: - default: - break; + case COMPLETED: + jobTarget.setStatus(JobTargetStatus.NOTIFIED_COMPLETION); + break; + case FAILED: + jobTarget.setStatus(JobTargetStatus.PROCESS_FAILED); + break; + case STALE: + default: + break; } jobTargetService.update(jobTarget); @@ -157,7 +146,7 @@ public void processJobTargetOnNotification(KapuaId scopeId, KapuaId operationId, return; } // Start the job - JobStartOptions jobStartOptions = jobEngineFactory.newJobStartOptions(); + JobStartOptions jobStartOptions = new JobStartOptions(); jobStartOptions.addTargetIdToSublist(jobTarget.getId()); jobStartOptions.setFromStepIndex(jobTarget.getStepIndex()); jobStartOptions.setEnqueue(true); @@ -166,14 +155,17 @@ public void processJobTargetOnNotification(KapuaId scopeId, KapuaId operationId, } /** - * This fixes the double {@link NotifyStatus#COMPLETED} {@link ManagementOperationNotification} set from Kura - * when performing a Device package download with the 'install' flag is set to {@code true}. + * This fixes the double {@link NotifyStatus#COMPLETED} {@link ManagementOperationNotification} set from Kura when performing a Device package download with the 'install' flag is set to + * {@code true}. *

        * If this is not the last {@link ManagementOperationNotification} the processing must stop. * - * @param deviceManagementOperation The current {@link DeviceManagementOperation} which the {@link ManagementOperationNotification} refers to. - * @param status The {@link ManagementOperationNotification} {@link NotifyStatus}. - * @param resource The {@link ManagementOperationNotification} resource. + * @param deviceManagementOperation + * The current {@link DeviceManagementOperation} which the {@link ManagementOperationNotification} refers to. + * @param status + * The {@link ManagementOperationNotification} {@link NotifyStatus}. + * @param resource + * The {@link ManagementOperationNotification} resource. * @return {@code true} if this is the last {@link ManagementOperationNotification} for the {@link DeviceManagementOperation}, {@code false} otherwise. * @since 1.1.0 */ @@ -199,18 +191,22 @@ private boolean checkLastNotification(DeviceManagementOperation deviceManagement /** * Gets the {@link JobDeviceManagementOperation} associated with the given {@link DeviceManagementOperation#getOperationId()}. * - * @param scopeId The scope {@link KapuaId} of the {@link JobDeviceManagementOperation}. - * @param operationId The {@link DeviceManagementOperation#getOperationId()} to match. + * @param scopeId + * The scope {@link KapuaId} of the {@link JobDeviceManagementOperation}. + * @param operationId + * The {@link DeviceManagementOperation#getOperationId()} to match. * @return The matched {@link JobDeviceManagementOperation} - * @throws KapuaEntityNotFoundException if there is no {@link JobDeviceManagementOperation} with the given {@code operationId}. - * @throws KapuaException If something goes bad. + * @throws KapuaEntityNotFoundException + * if there is no {@link JobDeviceManagementOperation} with the given {@code operationId}. + * @throws KapuaException + * If something goes bad. * @since 1.1.0 */ private JobDeviceManagementOperation getJobDeviceManagementOperation(KapuaId scopeId, KapuaId operationId) throws KapuaException { DeviceManagementOperation deviceManagementOperation = getDeviceManagementOperation(scopeId, operationId); - JobDeviceManagementOperationQuery query = jobDeviceManagementOperationFactory.newQuery(scopeId); + KapuaQuery query = new KapuaQuery(scopeId); query.setPredicate(query.attributePredicate(JobDeviceManagementOperationAttributes.DEVICE_MANAGEMENT_OPERATION_ID, deviceManagementOperation.getId())); JobDeviceManagementOperationListResult operations = jobDeviceManagementOperationService.query(query); @@ -223,15 +219,18 @@ private JobDeviceManagementOperation getJobDeviceManagementOperation(KapuaId sco return jobDeviceManagementOperation; } - /** * Gets the {@link DeviceManagementOperation} that matches the given {@code operationId}. * - * @param scopeId The scope {@link KapuaId} of the {@link DeviceManagementOperation}. - * @param operationId The {@link DeviceManagementOperation#getOperationId()} to match. + * @param scopeId + * The scope {@link KapuaId} of the {@link DeviceManagementOperation}. + * @param operationId + * The {@link DeviceManagementOperation#getOperationId()} to match. * @return The matched {@link DeviceManagementOperation}. - * @throws KapuaEntityNotFoundException if there is no {@link DeviceManagementOperation} with the given {@code operationId}. - * @throws KapuaException If something goes bad. + * @throws KapuaEntityNotFoundException + * if there is no {@link DeviceManagementOperation} with the given {@code operationId}. + * @throws KapuaException + * If something goes bad. * @since 1.1.0 */ private DeviceManagementOperation getDeviceManagementOperation(KapuaId scopeId, KapuaId operationId) throws KapuaException { diff --git a/service/device/management/job/internal/src/main/java/org/eclipse/kapua/service/device/management/job/scheduler/internal/JobDeviceManagementTriggerManagerServiceImpl.java b/service/device/management/job/internal/src/main/java/org/eclipse/kapua/service/device/management/job/scheduler/internal/JobDeviceManagementTriggerManagerServiceImpl.java index f2b1d51cdec..697507f1967 100644 --- a/service/device/management/job/internal/src/main/java/org/eclipse/kapua/service/device/management/job/scheduler/internal/JobDeviceManagementTriggerManagerServiceImpl.java +++ b/service/device/management/job/internal/src/main/java/org/eclipse/kapua/service/device/management/job/scheduler/internal/JobDeviceManagementTriggerManagerServiceImpl.java @@ -12,41 +12,36 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.job.scheduler.internal; +import java.util.Date; + +import javax.inject.Inject; +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaEntityNotFoundException; import org.eclipse.kapua.commons.security.KapuaSecurityUtils; -import org.eclipse.kapua.job.engine.JobEngineFactory; import org.eclipse.kapua.job.engine.JobEngineService; import org.eclipse.kapua.job.engine.JobStartOptions; import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.model.query.predicate.AttributePredicate; import org.eclipse.kapua.service.device.management.job.scheduler.manager.JobDeviceManagementTriggerManagerService; import org.eclipse.kapua.service.device.management.job.scheduler.manager.exception.ProcessOnConnectException; import org.eclipse.kapua.service.job.step.JobStepAttributes; -import org.eclipse.kapua.service.job.step.JobStepFactory; -import org.eclipse.kapua.service.job.step.JobStepQuery; import org.eclipse.kapua.service.job.step.JobStepService; import org.eclipse.kapua.service.job.targets.JobTarget; import org.eclipse.kapua.service.job.targets.JobTargetAttributes; -import org.eclipse.kapua.service.job.targets.JobTargetFactory; import org.eclipse.kapua.service.job.targets.JobTargetListResult; -import org.eclipse.kapua.service.job.targets.JobTargetQuery; import org.eclipse.kapua.service.job.targets.JobTargetService; import org.eclipse.kapua.service.job.targets.JobTargetStatus; import org.eclipse.kapua.service.scheduler.trigger.Trigger; import org.eclipse.kapua.service.scheduler.trigger.TriggerAttributes; -import org.eclipse.kapua.service.scheduler.trigger.TriggerFactory; import org.eclipse.kapua.service.scheduler.trigger.TriggerListResult; -import org.eclipse.kapua.service.scheduler.trigger.TriggerQuery; import org.eclipse.kapua.service.scheduler.trigger.TriggerService; import org.eclipse.kapua.service.scheduler.trigger.definition.TriggerDefinition; import org.eclipse.kapua.service.scheduler.trigger.definition.TriggerDefinitionService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.inject.Inject; -import javax.inject.Singleton; -import java.util.Date; - /** * {@link JobDeviceManagementTriggerManagerService} implementation. * @@ -58,45 +53,32 @@ public class JobDeviceManagementTriggerManagerServiceImpl implements JobDeviceMa private static final Logger LOG = LoggerFactory.getLogger(JobDeviceManagementTriggerManagerServiceImpl.class); private final JobEngineService jobEngineService; - private final JobEngineFactory jobEngineFactory; private final JobStepService jobStepService; - private final JobStepFactory jobStepFactory; private final JobTargetService jobTargetService; - private final JobTargetFactory jobTargetFactory; private final TriggerDefinitionService triggerDefinitionService; private final TriggerService triggerService; - private final TriggerFactory triggerFactory; @Inject public JobDeviceManagementTriggerManagerServiceImpl( JobEngineService jobEngineService, - JobEngineFactory jobEngineFactory, JobStepService jobStepService, - JobStepFactory jobStepFactory, JobTargetService jobTargetService, - JobTargetFactory jobTargetFactory, TriggerDefinitionService triggerDefinitionService, - TriggerService triggerService, - TriggerFactory triggerFactory) { + TriggerService triggerService) { this.jobEngineService = jobEngineService; - this.jobEngineFactory = jobEngineFactory; this.jobStepService = jobStepService; - this.jobStepFactory = jobStepFactory; this.jobTargetService = jobTargetService; - this.jobTargetFactory = jobTargetFactory; this.triggerDefinitionService = triggerDefinitionService; this.triggerService = triggerService; - this.triggerFactory = triggerFactory; } - @Override public void processOnConnect(KapuaId scopeId, KapuaId deviceId) throws ProcessOnConnectException { Date now = new Date(); try { - JobTargetQuery jobTargetQuery = jobTargetFactory.newQuery(scopeId); + KapuaQuery jobTargetQuery = new KapuaQuery(scopeId); jobTargetQuery.setPredicate( jobTargetQuery.attributePredicate(JobTargetAttributes.JOB_TARGET_ID, deviceId) @@ -105,7 +87,7 @@ public void processOnConnect(KapuaId scopeId, KapuaId deviceId) throws ProcessOn JobTargetListResult jobTargetListResult = KapuaSecurityUtils.doPrivileged(() -> jobTargetService.query(jobTargetQuery)); for (JobTarget jt : jobTargetListResult.getItems()) { - JobStepQuery jobStepQuery = jobStepFactory.newQuery(jt.getScopeId()); + KapuaQuery jobStepQuery = new KapuaQuery(jt.getScopeId()); jobStepQuery.setPredicate( jobStepQuery.attributePredicate(JobStepAttributes.JOB_ID, jt.getJobId()) @@ -118,7 +100,7 @@ public void processOnConnect(KapuaId scopeId, KapuaId deviceId) throws ProcessOn continue; } - TriggerQuery triggerQuery = triggerFactory.newQuery(scopeId); + KapuaQuery triggerQuery = new KapuaQuery(scopeId); triggerQuery.setPredicate( triggerQuery.andPredicate( @@ -136,7 +118,7 @@ public void processOnConnect(KapuaId scopeId, KapuaId deviceId) throws ProcessOn TriggerListResult jobTriggers = KapuaSecurityUtils.doPrivileged(() -> triggerService.query(triggerQuery)); for (Trigger t : jobTriggers.getItems()) { - JobStartOptions jobStartOptions = jobEngineFactory.newJobStartOptions(); + JobStartOptions jobStartOptions = new JobStartOptions(); jobStartOptions.addTargetIdToSublist(jt.getId()); jobStartOptions.setFromStepIndex(jt.getStepIndex()); diff --git a/service/device/management/job/pom.xml b/service/device/management/job/pom.xml index fba5b4495ca..806928977da 100644 --- a/service/device/management/job/pom.xml +++ b/service/device/management/job/pom.xml @@ -18,7 +18,7 @@ kapua-device-management org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT pom diff --git a/service/device/management/keystore/api/pom.xml b/service/device/management/keystore/api/pom.xml index f54deb6c97a..25c76c62802 100644 --- a/service/device/management/keystore/api/pom.xml +++ b/service/device/management/keystore/api/pom.xml @@ -17,7 +17,7 @@ org.eclipse.kapua kapua-device-management-keystore - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-device-management-keystore-api diff --git a/service/device/management/keystore/api/src/main/java/org/eclipse/kapua/service/device/management/keystore/DeviceKeystoreManagementFactory.java b/service/device/management/keystore/api/src/main/java/org/eclipse/kapua/service/device/management/keystore/DeviceKeystoreManagementFactory.java deleted file mode 100644 index 4c70729d0ef..00000000000 --- a/service/device/management/keystore/api/src/main/java/org/eclipse/kapua/service/device/management/keystore/DeviceKeystoreManagementFactory.java +++ /dev/null @@ -1,114 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.keystore; - -import org.eclipse.kapua.model.KapuaObjectFactory; -import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystore; -import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystoreCSR; -import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystoreCSRInfo; -import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystoreCertificate; -import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystoreItem; -import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystoreItemQuery; -import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystoreItems; -import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystoreKeypair; -import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystoreSubjectAN; -import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystores; - -/** - * {@link DeviceKeystore} {@link KapuaObjectFactory} definition. - * - * @see org.eclipse.kapua.model.KapuaObjectFactory - * @since 1.5.0 - */ -public interface DeviceKeystoreManagementFactory extends KapuaObjectFactory { - - /** - * Instantiates a new {@link DeviceKeystores}. - * - * @return The newly instantiated {@link DeviceKeystores}. - * @since 1.5.0 - */ - DeviceKeystores newDeviceKeystores(); - - /** - * Instantiates a new {@link DeviceKeystore}. - * - * @return The newly instantiated {@link DeviceKeystore}. - * @since 1.5.0 - */ - DeviceKeystore newDeviceKeystore(); - - /** - * Instantiates a new {@link DeviceKeystoreItems}. - * - * @return The newly instantiated {@link DeviceKeystoreItems}. - * @since 1.5.0 - */ - DeviceKeystoreItems newDeviceKeystoreItems(); - - /** - * Instantiates a new {@link DeviceKeystoreItem}. - * - * @return The newly instantiated {@link DeviceKeystoreItem}. - * @since 1.5.0 - */ - DeviceKeystoreItem newDeviceKeystoreItem(); - - /** - * Instantiates a new {@link DeviceKeystoreSubjectAN}. - * - * @return The newly instantiated {@link DeviceKeystoreSubjectAN}. - * @since 1.5.0 - */ - DeviceKeystoreSubjectAN newDeviceKeystoreSubjectAN(); - - /** - * Instantiates a new {@link DeviceKeystoreItemQuery}. - * - * @return The newly instantiated {@link DeviceKeystoreItemQuery}. - * @since 1.5.0 - */ - DeviceKeystoreItemQuery newDeviceKeystoreItemQuery(); - - /** - * Instantiates a new {@link DeviceKeystoreCertificate}. - * - * @return The newly instantiated {@link DeviceKeystoreCertificate}. - * @since 1.5.0 - */ - DeviceKeystoreCertificate newDeviceKeystoreCertificate(); - - /** - * Instantiates a new {@link DeviceKeystoreKeypair}. - * - * @return The newly instantiated {@link DeviceKeystoreKeypair}. - * @since 1.5.0 - */ - DeviceKeystoreKeypair newDeviceKeystoreKeypair(); - - /** - * Instantiates a new {@link DeviceKeystoreCSRInfo}. - * - * @return The newly instantiated {@link DeviceKeystoreCSRInfo}. - * @since 1.5.0 - */ - DeviceKeystoreCSRInfo newDeviceKeystoreCSRInfo(); - - /** - * Instantiates a new {@link DeviceKeystoreCSR}. - * - * @return The newly instantiated {@link DeviceKeystoreCSR}. - * @since 1.5.0 - */ - DeviceKeystoreCSR newDeviceKeystoreCSR(); -} diff --git a/service/device/management/keystore/api/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/DeviceKeystore.java b/service/device/management/keystore/api/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/DeviceKeystore.java index f6a93baf326..78df5890ede 100644 --- a/service/device/management/keystore/api/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/DeviceKeystore.java +++ b/service/device/management/keystore/api/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/DeviceKeystore.java @@ -27,8 +27,12 @@ */ @XmlRootElement(name = "deviceKeystore") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = DeviceKeystoreXmlRegistry.class, factoryMethod = "newDeviceKeystore") -public interface DeviceKeystore { +@XmlType +public class DeviceKeystore { + + private String id; + private String keystoreType; + private Integer size; /** * Gets the identifier. @@ -37,15 +41,20 @@ public interface DeviceKeystore { * @since 1.5.0 */ @XmlElement(name = "id") - String getId(); + public String getId() { + return id; + } /** * Sets the identifier. * - * @param id The identifier. + * @param id + * The identifier. * @since 1.5.0 */ - void setId(String id); + public void setId(String id) { + this.id = id; + } /** * Gets the keystore type. @@ -54,15 +63,20 @@ public interface DeviceKeystore { * @since 1.5.0 */ @XmlElement(name = "keystoreType") - String getKeystoreType(); + public String getKeystoreType() { + return keystoreType; + } /** * Sets the keystore type. * - * @param keystoreType The keystore type. + * @param keystoreType + * The keystore type. * @since 1.5.0 */ - void setKeystoreType(String keystoreType); + public void setKeystoreType(String keystoreType) { + this.keystoreType = keystoreType; + } /** * Gets the size. @@ -71,13 +85,18 @@ public interface DeviceKeystore { * @since 1.5.0 */ @XmlElement(name = "size") - Integer getSize(); + public Integer getSize() { + return size; + } /** * Sets the size. * - * @param size The size. + * @param size + * The size. * @since 1.5.0 */ - void setSize(Integer size); + public void setSize(Integer size) { + this.size = size; + } } diff --git a/service/device/management/keystore/api/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/DeviceKeystoreCSR.java b/service/device/management/keystore/api/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/DeviceKeystoreCSR.java index 400a3b91970..f09f8ff43c7 100644 --- a/service/device/management/keystore/api/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/DeviceKeystoreCSR.java +++ b/service/device/management/keystore/api/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/DeviceKeystoreCSR.java @@ -12,15 +12,15 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.keystore.model; -import org.eclipse.kapua.KapuaSerializable; -import org.eclipse.kapua.service.device.registry.Device; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; +import org.eclipse.kapua.KapuaSerializable; +import org.eclipse.kapua.service.device.registry.Device; + /** * {@link DeviceKeystoreCSR} definition. *

        @@ -30,8 +30,10 @@ */ @XmlRootElement(name = "deviceKeystoreCSR") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = DeviceKeystoreXmlRegistry.class, factoryMethod = "newDeviceKeystoreCSR") -public interface DeviceKeystoreCSR extends KapuaSerializable { +@XmlType +public class DeviceKeystoreCSR implements KapuaSerializable { + + private String signingRequest; /** * Gets the certificate signing request from the {@link Device#getId()}. @@ -40,13 +42,19 @@ public interface DeviceKeystoreCSR extends KapuaSerializable { * @since 1.5.0 */ @XmlElement(name = "signingRequest") - String getSigningRequest(); + public String getSigningRequest() { + return signingRequest; + } /** * Sets the certificate signing request from the {@link Device#getId()}. * - * @param signingRequest The signing request from the {@link Device#getId()}. + * @param signingRequest + * The signing request from the {@link Device#getId()}. * @since 1.5.0 */ - void setSigningRequest(String signingRequest); + public void setSigningRequest(String signingRequest) { + this.signingRequest = signingRequest; + } + } diff --git a/service/device/management/keystore/api/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/DeviceKeystoreCSRInfo.java b/service/device/management/keystore/api/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/DeviceKeystoreCSRInfo.java index a4cfead1b15..42e734d0fb1 100644 --- a/service/device/management/keystore/api/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/DeviceKeystoreCSRInfo.java +++ b/service/device/management/keystore/api/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/DeviceKeystoreCSRInfo.java @@ -12,15 +12,15 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.keystore.model; -import org.eclipse.kapua.KapuaSerializable; -import org.eclipse.kapua.service.device.registry.Device; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; +import org.eclipse.kapua.KapuaSerializable; +import org.eclipse.kapua.service.device.registry.Device; + /** * {@link DeviceKeystoreCSRInfo} definition. *

        @@ -30,8 +30,13 @@ */ @XmlRootElement(name = "deviceKeystoreCSRInfo") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = DeviceKeystoreXmlRegistry.class, factoryMethod = "newDeviceKeystoreCSRInfo") -public interface DeviceKeystoreCSRInfo extends KapuaSerializable { +@XmlType +public class DeviceKeystoreCSRInfo implements KapuaSerializable { + + private String keystoreId; + private String alias; + private String signatureAlgorithm; + private String attributes; /** * Gets the {@link DeviceKeystoreItem#getKeystoreId()} target to be used for signing. @@ -40,15 +45,20 @@ public interface DeviceKeystoreCSRInfo extends KapuaSerializable { * @since 1.5.0 */ @XmlElement(name = "keystoreId") - String getKeystoreId(); + public String getKeystoreId() { + return keystoreId; + } /** * Sets the {@link DeviceKeystoreItem#getKeystoreId()} target to be used for signing. * - * @param keystoreId The {@link DeviceKeystoreItem#getKeystoreId()} target to be used for signing. + * @param keystoreId + * The {@link DeviceKeystoreItem#getKeystoreId()} target to be used for signing. * @since 1.5.0 */ - void setKeystoreId(String keystoreId); + public void setKeystoreId(String keystoreId) { + this.keystoreId = keystoreId; + } /** * Gets the {@link DeviceKeystoreItem#getAlias()} target to be used for signing. @@ -57,15 +67,20 @@ public interface DeviceKeystoreCSRInfo extends KapuaSerializable { * @since 1.5.0 */ @XmlElement(name = "alias") - String getAlias(); + public String getAlias() { + return alias; + } /** * Sets the {@link DeviceKeystoreItem#getAlias()} target to be used for signing. * - * @param alias The {@link DeviceKeystoreItem#getAlias()} target to be used for signing. + * @param alias + * The {@link DeviceKeystoreItem#getAlias()} target to be used for signing. * @since 1.5.0 */ - void setAlias(String alias); + public void setAlias(String alias) { + this.alias = alias; + } /** * Gets the signature algorithm. @@ -74,15 +89,20 @@ public interface DeviceKeystoreCSRInfo extends KapuaSerializable { * @since 1.5.0 */ @XmlElement(name = "signatureAlgorithm") - String getSignatureAlgorithm(); + public String getSignatureAlgorithm() { + return signatureAlgorithm; + } /** * Sets the signature algorithm. * - * @param signatureAlgorithm The signature algorithm. + * @param signatureAlgorithm + * The signature algorithm. * @since 1.5.0 */ - void setSignatureAlgorithm(String signatureAlgorithm); + public void setSignatureAlgorithm(String signatureAlgorithm) { + this.signatureAlgorithm = signatureAlgorithm; + } /** * Gets the attributes to sign. @@ -91,13 +111,19 @@ public interface DeviceKeystoreCSRInfo extends KapuaSerializable { * @since 1.5.0 */ @XmlElement(name = "attributes") - String getAttributes(); + public String getAttributes() { + return attributes; + } /** * Sets the attributes to sign. * - * @param attributes The attributes to sign. + * @param attributes + * The attributes to sign. * @since 1.5.0 */ - void setAttributes(String attributes); + public void setAttributes(String attributes) { + this.attributes = attributes; + } + } diff --git a/service/device/management/keystore/api/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/DeviceKeystoreCertificate.java b/service/device/management/keystore/api/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/DeviceKeystoreCertificate.java index 54c1c587f66..553ed30ed6d 100644 --- a/service/device/management/keystore/api/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/DeviceKeystoreCertificate.java +++ b/service/device/management/keystore/api/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/DeviceKeystoreCertificate.java @@ -12,15 +12,15 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.keystore.model; -import org.eclipse.kapua.KapuaSerializable; -import org.eclipse.kapua.service.device.registry.Device; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; +import org.eclipse.kapua.KapuaSerializable; +import org.eclipse.kapua.service.device.registry.Device; + /** * {@link DeviceKeystoreCertificate} definition. *

        @@ -30,8 +30,12 @@ */ @XmlRootElement(name = "deviceKeystoreCertificate") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = DeviceKeystoreXmlRegistry.class, factoryMethod = "newDeviceKeystoreCertificate") -public interface DeviceKeystoreCertificate extends KapuaSerializable { +@XmlType +public class DeviceKeystoreCertificate implements KapuaSerializable { + + private String keystoreId; + private String alias; + private String certificate; /** * Gets the keystore id. @@ -40,15 +44,20 @@ public interface DeviceKeystoreCertificate extends KapuaSerializable { * @since 1.5.0 */ @XmlElement(name = "keystoreId") - String getKeystoreId(); + public String getKeystoreId() { + return keystoreId; + } /** * Sets the keystore id. * - * @param keystoreId The keystore id. + * @param keystoreId + * The keystore id. * @since 1.5.0 */ - void setKeystoreId(String keystoreId); + public void setKeystoreId(String keystoreId) { + this.keystoreId = keystoreId; + } /** * Gets the alias. @@ -57,15 +66,20 @@ public interface DeviceKeystoreCertificate extends KapuaSerializable { * @since 1.5.0 */ @XmlElement(name = "alias") - String getAlias(); + public String getAlias() { + return alias; + } /** * Sets the alias. * - * @param alias The alias. + * @param alias + * The alias. * @since 1.5.0 */ - void setAlias(String alias); + public void setAlias(String alias) { + this.alias = alias; + } /** * Gets the certificate. @@ -74,13 +88,19 @@ public interface DeviceKeystoreCertificate extends KapuaSerializable { * @since 1.5.0 */ @XmlElement(name = "certificate") - String getCertificate(); + public String getCertificate() { + return certificate; + } /** * Sets the certificate. * - * @param certificate The certificate. + * @param certificate + * The certificate. * @since 1.5.0 */ - void setCertificate(String certificate); + public void setCertificate(String certificate) { + this.certificate = certificate; + } + } diff --git a/service/device/management/keystore/api/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/DeviceKeystoreItem.java b/service/device/management/keystore/api/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/DeviceKeystoreItem.java index 697048ef1df..e97052ece42 100644 --- a/service/device/management/keystore/api/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/DeviceKeystoreItem.java +++ b/service/device/management/keystore/api/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/DeviceKeystoreItem.java @@ -12,8 +12,9 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.keystore.model; -import org.eclipse.kapua.model.xml.DateXmlAdapter; -import org.eclipse.kapua.service.device.registry.Device; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; @@ -21,8 +22,9 @@ import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; -import java.util.Date; -import java.util.List; + +import org.eclipse.kapua.model.xml.DateXmlAdapter; +import org.eclipse.kapua.service.device.registry.Device; /** * {@link DeviceKeystoreItem} definition. @@ -33,8 +35,21 @@ */ @XmlRootElement(name = "deviceKeystoreItem") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = DeviceKeystoreXmlRegistry.class, factoryMethod = "newDeviceKeystoreItem") -public interface DeviceKeystoreItem { +@XmlType +public class DeviceKeystoreItem { + + private String keystoreId; + private String itemType; + private Integer size; + private String algorithm; + private String alias; + private String subjectDN; + private List subjectAN; + private String issuer; + private Date notBefore; + private Date notAfter; + private String certificate; + private List certificateChain; /** * Gets the keystore id. @@ -43,15 +58,20 @@ public interface DeviceKeystoreItem { * @since 1.5.0 */ @XmlElement(name = "keystoreId") - String getKeystoreId(); + public String getKeystoreId() { + return keystoreId; + } /** * Sets the keystore id. * - * @param keystoreId The keystore id. + * @param keystoreId + * The keystore id. * @since 1.5.0 */ - void setKeystoreId(String keystoreId); + public void setKeystoreId(String keystoreId) { + this.keystoreId = keystoreId; + } /** * Gets the alias. @@ -60,15 +80,20 @@ public interface DeviceKeystoreItem { * @since 1.5.0 */ @XmlElement(name = "alias") - String getAlias(); + public String getAlias() { + return alias; + } /** * Sets the alias. * - * @param alias The alias. + * @param alias + * The alias. * @since 1.5.0 */ - void setAlias(String alias); + public void setAlias(String alias) { + this.alias = alias; + } /** * Gets the item type. @@ -84,15 +109,20 @@ public interface DeviceKeystoreItem { * @since 1.5.0 */ @XmlElement(name = "itemType") - String getItemType(); + public String getItemType() { + return itemType; + } /** * Sets the item type. * - * @param itemType The item type. + * @param itemType + * The item type. * @since 1.5.0 */ - void setItemType(String itemType); + public void setItemType(String itemType) { + this.itemType = itemType; + } /** * Gets the size in bytes. @@ -101,15 +131,20 @@ public interface DeviceKeystoreItem { * @since 1.5.0 */ @XmlElement(name = "size") - Integer getSize(); + public Integer getSize() { + return size; + } /** * Sets the size in bytes. * - * @param size The size in bytes. + * @param size + * The size in bytes. * @since 1.5.0 */ - void setSize(Integer size); + public void setSize(Integer size) { + this.size = size; + } /** * Gets the algorithm. @@ -118,15 +153,20 @@ public interface DeviceKeystoreItem { * @since 1.5.0 */ @XmlElement(name = "algorithm") - String getAlgorithm(); + public String getAlgorithm() { + return algorithm; + } /** * Sets the algorithm. * - * @param algorithm The algorithm. + * @param algorithm + * The algorithm. * @since 1.5.0 */ - void setAlgorithm(String algorithm); + public void setAlgorithm(String algorithm) { + this.algorithm = algorithm; + } /** * Gets the subject distinguished name. @@ -135,15 +175,20 @@ public interface DeviceKeystoreItem { * @since 1.5.0 */ @XmlElement(name = "subjectDN") - String getSubjectDN(); + public String getSubjectDN() { + return subjectDN; + } /** * Sets the subject distinguished name. * - * @param subjectDN The subject distinguished name. + * @param subjectDN + * The subject distinguished name. * @since 1.5.0 */ - void setSubjectDN(String subjectDN); + public void setSubjectDN(String subjectDN) { + this.subjectDN = subjectDN; + } /** * Gets the {@link List} of {@link DeviceKeystoreSubjectAN}s. @@ -152,23 +197,35 @@ public interface DeviceKeystoreItem { * @since 1.5.0 */ @XmlElement(name = "subjectANs") - List getSubjectAN(); + public List getSubjectAN() { + if (subjectAN == null) { + subjectAN = new ArrayList<>(); + } + + return subjectAN; + } /** * Adds a {@link DeviceKeystoreSubjectAN} to {@link #getSubjectAN()}. * - * @param subjectAN The {@link DeviceKeystoreSubjectAN} to add. + * @param subjectAN + * The {@link DeviceKeystoreSubjectAN} to add. * @since 1.5.0 */ - void addSubjectAN(DeviceKeystoreSubjectAN subjectAN); + public void addSubjectAN(DeviceKeystoreSubjectAN subjectAN) { + getSubjectAN().add(subjectAN); + } /** * Sets the {@link List} of {@link DeviceKeystoreSubjectAN}s. * - * @param subjectAN The {@link List} of {@link DeviceKeystoreSubjectAN}s. + * @param subjectAN + * The {@link List} of {@link DeviceKeystoreSubjectAN}s. * @since 1.5.0 */ - void setSubjectAN(List subjectAN); + public void setSubjectAN(List subjectAN) { + this.subjectAN = subjectAN; + } /** * Gets the issuer. @@ -177,15 +234,20 @@ public interface DeviceKeystoreItem { * @since 1.5.0 */ @XmlElement(name = "issuer") - String getIssuer(); + public String getIssuer() { + return issuer; + } /** * Sets the issuer. * - * @param issuer The issuer. + * @param issuer + * The issuer. * @since 1.5.0 */ - void setIssuer(String issuer); + public void setIssuer(String issuer) { + this.issuer = issuer; + } /** * Gets the not before {@link Date}. @@ -195,15 +257,20 @@ public interface DeviceKeystoreItem { */ @XmlElement(name = "notBefore") @XmlJavaTypeAdapter(DateXmlAdapter.class) - Date getNotBefore(); + public Date getNotBefore() { + return notBefore; + } /** * Sets the not before {@link Date}. * - * @param notBefore The not before {@link Date}. + * @param notBefore + * The not before {@link Date}. * @since 1.5.0 */ - void setNotBefore(Date notBefore); + public void setNotBefore(Date notBefore) { + this.notBefore = notBefore; + } /** * Gets the not after {@link Date}. @@ -213,15 +280,20 @@ public interface DeviceKeystoreItem { */ @XmlElement(name = "notAfter") @XmlJavaTypeAdapter(DateXmlAdapter.class) - Date getNotAfter(); + public Date getNotAfter() { + return notAfter; + } /** * Sets the not after {@link Date}. * - * @param notAfter The not after {@link Date}. + * @param notAfter + * The not after {@link Date}. * @since 1.5.0 */ - void setNotAfter(Date notAfter); + public void setNotAfter(Date notAfter) { + this.notAfter = notAfter; + } /** * Gets the certificate. @@ -230,15 +302,20 @@ public interface DeviceKeystoreItem { * @since 1.5.0 */ @XmlElement(name = "certificate") - String getCertificate(); + public String getCertificate() { + return certificate; + } /** * Sets the certificate. * - * @param certificate The certificate. + * @param certificate + * The certificate. * @since 1.5.0 */ - void setCertificate(String certificate); + public void setCertificate(String certificate) { + this.certificate = certificate; + } /** * Gets the certificate chain. @@ -247,22 +324,34 @@ public interface DeviceKeystoreItem { * @since 1.5.0 */ @XmlElement(name = "certificateChain") - List getCertificateChain(); + public List getCertificateChain() { + if (certificateChain == null) { + certificateChain = new ArrayList<>(); + } + + return certificateChain; + } /** * Adds a certificate to the {@link #getCertificateChain()}. * - * @param certificate The certificate to add. + * @param certificate + * The certificate to add. * @since 1.5.0 */ - void addCertificateChain(String certificate); + public void addCertificateChain(String certificate) { + getCertificateChain().add(certificate); + } /** * Sets the certificate chain. * - * @param certificateChain The certificate chain. + * @param certificateChain + * The certificate chain. * @since 1.5.0 */ - void setCertificateChain(List certificateChain); + public void setCertificateChain(List certificateChain) { + this.certificateChain = certificateChain; + } } diff --git a/service/device/management/keystore/api/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/DeviceKeystoreItemQuery.java b/service/device/management/keystore/api/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/DeviceKeystoreItemQuery.java index 318a63131ca..8ffcd4c7bf7 100644 --- a/service/device/management/keystore/api/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/DeviceKeystoreItemQuery.java +++ b/service/device/management/keystore/api/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/DeviceKeystoreItemQuery.java @@ -12,8 +12,6 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.keystore.model; -import org.eclipse.kapua.KapuaSerializable; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; @@ -21,18 +19,24 @@ import javax.xml.bind.annotation.XmlTransient; import javax.xml.bind.annotation.XmlType; +import org.eclipse.kapua.KapuaSerializable; + +import com.google.common.base.Strings; + /** * {@link DeviceKeystoreItemQuery} definition. *

        - * Is used to filter result from the keystore. - * Only one of the filter can be used at a time. + * Is used to filter result from the keystore. Only one of the filter can be used at a time. * * @since 1.5.0 */ @XmlRootElement(name = "deviceKeystoreItemQuery") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = DeviceKeystoreXmlRegistry.class, factoryMethod = "newDeviceKeystoreItemQuery") -public interface DeviceKeystoreItemQuery extends KapuaSerializable { +@XmlType +public class DeviceKeystoreItemQuery implements KapuaSerializable { + + private String keystoreId; + private String alias; /** * Gets the keystore id. @@ -41,15 +45,20 @@ public interface DeviceKeystoreItemQuery extends KapuaSerializable { * @since 1.5.0 */ @XmlElement(name = "keystoreId") - String getKeystoreId(); + public String getKeystoreId() { + return keystoreId; + } /** * Sets the keystore id. * - * @param keystoreId The keystore id. + * @param keystoreId + * The keystore id. * @since 1.5.0 */ - void setKeystoreId(String keystoreId); + public void setKeystoreId(String keystoreId) { + this.keystoreId = keystoreId; + } /** * Gets the alias. @@ -58,15 +67,20 @@ public interface DeviceKeystoreItemQuery extends KapuaSerializable { * @since 1.5.0 */ @XmlElement(name = "alias") - String getAlias(); + public String getAlias() { + return alias; + } /** * Sets the alias. * - * @param alias The alias. + * @param alias + * The alias. * @since 1.5.0 */ - void setAlias(String alias); + public void setAlias(String alias) { + this.alias = alias; + } /** * Gets whether or not there is a filter specified. @@ -75,5 +89,8 @@ public interface DeviceKeystoreItemQuery extends KapuaSerializable { * @since 1.5.0 */ @XmlTransient - boolean hasFilters(); + public boolean hasFilters() { + return !Strings.isNullOrEmpty(getKeystoreId()) || + !Strings.isNullOrEmpty(getAlias()); + } } diff --git a/service/device/management/keystore/api/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/DeviceKeystoreItems.java b/service/device/management/keystore/api/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/DeviceKeystoreItems.java index dd5860aeddd..d5f1d044a3d 100644 --- a/service/device/management/keystore/api/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/DeviceKeystoreItems.java +++ b/service/device/management/keystore/api/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/DeviceKeystoreItems.java @@ -12,14 +12,16 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.keystore.model; -import org.eclipse.kapua.KapuaSerializable; +import java.util.ArrayList; +import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; -import java.util.List; + +import org.eclipse.kapua.KapuaSerializable; /** * {@link DeviceKeystoreItems} definition. @@ -28,8 +30,12 @@ */ @XmlRootElement(name = "deviceKeystoreItems") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = DeviceKeystoreXmlRegistry.class, factoryMethod = "newDeviceKeystoreItems") -public interface DeviceKeystoreItems extends KapuaSerializable { +@XmlType +public class DeviceKeystoreItems implements KapuaSerializable { + + private static final long serialVersionUID = 1318691706440015345L; + + private List keystoreItems; /** * Gets the {@link List} of {@link DeviceKeystoreItem}s @@ -38,21 +44,34 @@ public interface DeviceKeystoreItems extends KapuaSerializable { * @since 1.5.0 */ @XmlElement(name = "keystoreItems") - List getKeystoreItems(); + public List getKeystoreItems() { + if (keystoreItems == null) { + keystoreItems = new ArrayList<>(); + } + + return keystoreItems; + } /** * Adds a {@link DeviceKeystoreItem} to the {@link List} * - * @param keystoreItem The {@link DeviceKeystoreItem} to add. + * @param keystoreItem + * The {@link DeviceKeystoreItem} to add. * @since 1.5.0 */ - void addKeystoreItem(DeviceKeystoreItem keystoreItem); + public void addKeystoreItem(DeviceKeystoreItem keystoreItem) { + getKeystoreItems().add(keystoreItem); + } /** * Sets the {@link List} of {@link DeviceKeystoreItem}s * - * @param keystoreItems The {@link List} of {@link DeviceKeystoreItem}s + * @param keystoreItems + * The {@link List} of {@link DeviceKeystoreItem}s * @since 1.5.0 */ - void setKeystoreItems(List keystoreItems); + public void setKeystoreItems(List keystoreItems) { + this.keystoreItems = keystoreItems; + } + } diff --git a/service/device/management/keystore/api/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/DeviceKeystoreKeypair.java b/service/device/management/keystore/api/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/DeviceKeystoreKeypair.java index d2ef4f1033e..7a5914a208c 100644 --- a/service/device/management/keystore/api/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/DeviceKeystoreKeypair.java +++ b/service/device/management/keystore/api/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/DeviceKeystoreKeypair.java @@ -12,15 +12,14 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.keystore.model; -import org.eclipse.kapua.KapuaSerializable; -import org.eclipse.kapua.service.device.registry.Device; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; +import org.eclipse.kapua.KapuaSerializable; +import org.eclipse.kapua.service.device.registry.Device; /** * {@link DeviceKeystoreKeypair} definition. @@ -31,8 +30,15 @@ */ @XmlRootElement(name = "deviceKeystoreKeypair") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = DeviceKeystoreXmlRegistry.class, factoryMethod = "newDeviceKeystoreKeypair") -public interface DeviceKeystoreKeypair extends KapuaSerializable { +@XmlType +public class DeviceKeystoreKeypair implements KapuaSerializable { + + private String keystoreId; + private String alias; + private String algorithm; + private String signatureAlgorithm; + private Integer size; + private String attributes; /** * Gets the keystore id. @@ -41,15 +47,20 @@ public interface DeviceKeystoreKeypair extends KapuaSerializable { * @since 1.5.0 */ @XmlElement(name = "keystoreId") - String getKeystoreId(); + public String getKeystoreId() { + return keystoreId; + } /** * Sets the keystore id. * - * @param keystoreId The keystore id. + * @param keystoreId + * The keystore id. * @since 1.5.0 */ - void setKeystoreId(String keystoreId); + public void setKeystoreId(String keystoreId) { + this.keystoreId = keystoreId; + } /** * Gets the alias. @@ -58,15 +69,20 @@ public interface DeviceKeystoreKeypair extends KapuaSerializable { * @since 1.5.0 */ @XmlElement(name = "alias") - String getAlias(); + public String getAlias() { + return alias; + } /** * Sets the alias. * - * @param alias The alias. + * @param alias + * The alias. * @since 1.5.0 */ - void setAlias(String alias); + public void setAlias(String alias) { + this.alias = alias; + } /** * Gets the algorithm. @@ -75,15 +91,20 @@ public interface DeviceKeystoreKeypair extends KapuaSerializable { * @since 1.5.0 */ @XmlElement(name = "algorithm") - String getAlgorithm(); + public String getAlgorithm() { + return algorithm; + } /** * Sets the algorithm. * - * @param algorithm The algorithm. + * @param algorithm + * The algorithm. * @since 1.5.0 */ - void setAlgorithm(String algorithm); + public void setAlgorithm(String algorithm) { + this.algorithm = algorithm; + } /** * Gets the size in bytes. @@ -92,15 +113,20 @@ public interface DeviceKeystoreKeypair extends KapuaSerializable { * @since 1.5.0 */ @XmlElement(name = "size") - Integer getSize(); + public Integer getSize() { + return size; + } /** * Sets the size in bytes. * - * @param size The size in bytes. + * @param size + * The size in bytes. * @since 1.5.0 */ - void setSize(Integer size); + public void setSize(Integer size) { + this.size = size; + } /** * Gets the signature algorithm. @@ -109,15 +135,20 @@ public interface DeviceKeystoreKeypair extends KapuaSerializable { * @since 1.5.0 */ @XmlElement(name = "signatureAlgorithm") - String getSignatureAlgorithm(); + public String getSignatureAlgorithm() { + return signatureAlgorithm; + } /** * Sets the signature algorithm. * - * @param signatureAlgorithm The signature algorithm. + * @param signatureAlgorithm + * The signature algorithm. * @since 1.5.0 */ - void setSignatureAlgorithm(String signatureAlgorithm); + public void setSignatureAlgorithm(String signatureAlgorithm) { + this.signatureAlgorithm = signatureAlgorithm; + } /** * Gets the attributes. @@ -126,13 +157,19 @@ public interface DeviceKeystoreKeypair extends KapuaSerializable { * @since 1.5.0 */ @XmlElement(name = "attributes") - String getAttributes(); + public String getAttributes() { + return attributes; + } /** * Sets the attributes. * - * @param attributes The attributes. + * @param attributes + * The attributes. * @since 1.5.0 */ - void setAttributes(String attributes); + public void setAttributes(String attributes) { + this.attributes = attributes; + } + } diff --git a/service/device/management/keystore/api/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/DeviceKeystoreSubjectAN.java b/service/device/management/keystore/api/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/DeviceKeystoreSubjectAN.java index f3bc8bc3979..cf80cbbe483 100644 --- a/service/device/management/keystore/api/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/DeviceKeystoreSubjectAN.java +++ b/service/device/management/keystore/api/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/DeviceKeystoreSubjectAN.java @@ -25,8 +25,24 @@ */ @XmlRootElement(name = "subjectAN") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = DeviceKeystoreXmlRegistry.class, factoryMethod = "newDeviceKeystoreSubjectAN") -public interface DeviceKeystoreSubjectAN { +@XmlType +public class DeviceKeystoreSubjectAN { + + private String anType; + private String value; + + public DeviceKeystoreSubjectAN() { + } + + /** + * Constructor. + * + * @since 1.5.0 + */ + public DeviceKeystoreSubjectAN(String anType, String anValue) { + setANType(anType); + setValue(anValue); + } /** * The type of the subject alternative name. @@ -35,15 +51,20 @@ public interface DeviceKeystoreSubjectAN { * @since 1.5.0 */ @XmlElement(name = "anType") - String getANType(); + public String getANType() { + return anType; + } /** * Sets the type of the subject alternative name. * - * @param anType The type of the subject alternative name. + * @param anType + * The type of the subject alternative name. * @since 1.5.0 */ - void setANType(String anType); + public void setANType(String anType) { + this.anType = anType; + } /** * Gets the alternative name value. @@ -52,13 +73,19 @@ public interface DeviceKeystoreSubjectAN { * @since 1.5.0 */ @XmlElement(name = "value") - String getValue(); + public String getValue() { + return value; + } /** * Sets the alternative name value. * - * @param value The alternative name value. + * @param value + * The alternative name value. * @since 1.5.0 */ - void setValue(String value); + public void setValue(String value) { + this.value = value; + } + } diff --git a/service/device/management/keystore/api/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/DeviceKeystoreXmlRegistry.java b/service/device/management/keystore/api/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/DeviceKeystoreXmlRegistry.java deleted file mode 100644 index 8451cd7d7ac..00000000000 --- a/service/device/management/keystore/api/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/DeviceKeystoreXmlRegistry.java +++ /dev/null @@ -1,126 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.keystore.model; - -import org.eclipse.kapua.locator.KapuaLocator; -import org.eclipse.kapua.service.device.management.keystore.DeviceKeystoreManagementFactory; - -/** - * {@link DeviceKeystore} XmlFactory definition. - * - * @since 1.5.0 - */ -public class DeviceKeystoreXmlRegistry { - - private final DeviceKeystoreManagementFactory factory = KapuaLocator.getInstance().getFactory(DeviceKeystoreManagementFactory.class); - - /** - * Instantiates a new {@link DeviceKeystores}. - * - * @return The newly instantiated {@link DeviceKeystores} - * @since 1.5.0 - */ - DeviceKeystores newDeviceKeystores() { - return factory.newDeviceKeystores(); - } - - /** - * Instantiates a new {@link DeviceKeystore}. - * - * @return The newly instantiated {@link DeviceKeystore} - * @since 1.5.0 - */ - DeviceKeystore newDeviceKeystore() { - return factory.newDeviceKeystore(); - } - - /** - * Instantiates a new {@link DeviceKeystoreItems}. - * - * @return The newly instantiated {@link DeviceKeystoreItems} - * @since 1.5.0 - */ - DeviceKeystoreItems newDeviceKeystoreItems() { - return factory.newDeviceKeystoreItems(); - } - - /** - * Instantiates a new {@link DeviceKeystoreItem}. - * - * @return The newly instantiated {@link DeviceKeystoreItem} - * @since 1.5.0 - */ - DeviceKeystoreItem newDeviceKeystoreItem() { - return factory.newDeviceKeystoreItem(); - } - - /** - * Instantiates a new {@link DeviceKeystoreSubjectAN}. - * - * @return The newly instantiated {@link DeviceKeystoreSubjectAN} - * @since 1.5.0 - */ - DeviceKeystoreSubjectAN newDeviceKeystoreSubjectAN() { - return factory.newDeviceKeystoreSubjectAN(); - } - - /** - * Instantiates a new {@link DeviceKeystoreItemQuery}. - * - * @return The newly instantiated {@link DeviceKeystoreItemQuery} - * @since 1.5.0 - */ - DeviceKeystoreItemQuery newDeviceKeystoreItemQuery() { - return factory.newDeviceKeystoreItemQuery(); - } - - /** - * Instantiates a new {@link DeviceKeystoreCertificate}. - * - * @return The newly instantiated {@link DeviceKeystoreCertificate} - * @since 1.5.0 - */ - DeviceKeystoreCertificate newDeviceKeystoreCertificate() { - return factory.newDeviceKeystoreCertificate(); - } - - /** - * Instantiates a new {@link DeviceKeystoreKeypair}. - * - * @return The newly instantiated {@link DeviceKeystoreKeypair} - * @since 1.5.0 - */ - DeviceKeystoreKeypair newDeviceKeystoreKeypair() { - return factory.newDeviceKeystoreKeypair(); - } - - /** - * Instantiates a new {@link DeviceKeystoreCSRInfo}. - * - * @return The newly instantiated {@link DeviceKeystoreCSRInfo} - * @since 1.5.0 - */ - DeviceKeystoreCSRInfo newDeviceKeystoreCSRInfo() { - return factory.newDeviceKeystoreCSRInfo(); - } - - /** - * Instantiates a new {@link DeviceKeystoreCSR}. - * - * @return The newly instantiated {@link DeviceKeystoreCSR} - * @since 1.5.0 - */ - DeviceKeystoreCSR newDeviceKeystoreCSR() { - return factory.newDeviceKeystoreCSR(); - } -} diff --git a/service/device/management/keystore/api/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/DeviceKeystores.java b/service/device/management/keystore/api/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/DeviceKeystores.java index c1315cb3f48..2944c63cc16 100644 --- a/service/device/management/keystore/api/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/DeviceKeystores.java +++ b/service/device/management/keystore/api/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/DeviceKeystores.java @@ -12,14 +12,16 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.keystore.model; -import org.eclipse.kapua.KapuaSerializable; +import java.util.ArrayList; +import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; -import java.util.List; + +import org.eclipse.kapua.KapuaSerializable; /** * {@link DeviceKeystores} definition. @@ -28,8 +30,12 @@ */ @XmlAccessorType(XmlAccessType.PROPERTY) @XmlRootElement(name = "deviceKeystores") -@XmlType(factoryClass = DeviceKeystoreXmlRegistry.class, factoryMethod = "newDeviceKeystores") -public interface DeviceKeystores extends KapuaSerializable { +@XmlType +public class DeviceKeystores implements KapuaSerializable { + + private static final long serialVersionUID = 1318691706440015345L; + + private List keystores; /** * Gets the {@link List} of {@link DeviceKeystore}s @@ -38,21 +44,34 @@ public interface DeviceKeystores extends KapuaSerializable { * @since 1.5.0 */ @XmlElement(name = "keystores") - List getKeystores(); + public List getKeystores() { + if (keystores == null) { + keystores = new ArrayList<>(); + } + + return keystores; + } /** * Adds a {@link DeviceKeystore} to the {@link List} * - * @param keystore The {@link DeviceKeystore} to add. + * @param keystore + * The {@link DeviceKeystore} to add. * @since 1.5.0 */ - void addKeystore(DeviceKeystore keystore); + public void addKeystore(DeviceKeystore keystore) { + getKeystores().add(keystore); + } /** * Sets the {@link List} of {@link DeviceKeystore}s * - * @param keystores The {@link List} of {@link DeviceKeystore}s + * @param keystores + * The {@link List} of {@link DeviceKeystore}s * @since 1.5.0 */ - void setKeystores(List keystores); + public void setKeystores(List keystores) { + this.keystores = keystores; + } + } diff --git a/service/device/management/keystore/internal/pom.xml b/service/device/management/keystore/internal/pom.xml index 77b17da9db3..ccb4cc50dbc 100644 --- a/service/device/management/keystore/internal/pom.xml +++ b/service/device/management/keystore/internal/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-device-management-keystore - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-device-management-keystore-internal diff --git a/service/device/management/keystore/internal/src/main/java/org/eclipse/kapua/service/device/management/keystore/internal/DeviceKeystoreManagementFactoryImpl.java b/service/device/management/keystore/internal/src/main/java/org/eclipse/kapua/service/device/management/keystore/internal/DeviceKeystoreManagementFactoryImpl.java deleted file mode 100644 index 4ed1844435b..00000000000 --- a/service/device/management/keystore/internal/src/main/java/org/eclipse/kapua/service/device/management/keystore/internal/DeviceKeystoreManagementFactoryImpl.java +++ /dev/null @@ -1,96 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.keystore.internal; - -import org.eclipse.kapua.service.device.management.keystore.DeviceKeystoreManagementFactory; -import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystore; -import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystoreCSR; -import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystoreCSRInfo; -import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystoreCertificate; -import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystoreItem; -import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystoreItemQuery; -import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystoreItems; -import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystoreKeypair; -import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystoreSubjectAN; -import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystores; -import org.eclipse.kapua.service.device.management.keystore.model.internal.DeviceKeystoreCSRImpl; -import org.eclipse.kapua.service.device.management.keystore.model.internal.DeviceKeystoreCSRInfoImpl; -import org.eclipse.kapua.service.device.management.keystore.model.internal.DeviceKeystoreCertificateImpl; -import org.eclipse.kapua.service.device.management.keystore.model.internal.DeviceKeystoreImpl; -import org.eclipse.kapua.service.device.management.keystore.model.internal.DeviceKeystoreItemImpl; -import org.eclipse.kapua.service.device.management.keystore.model.internal.DeviceKeystoreItemQueryImpl; -import org.eclipse.kapua.service.device.management.keystore.model.internal.DeviceKeystoreItemsImpl; -import org.eclipse.kapua.service.device.management.keystore.model.internal.DeviceKeystoreKeypairImpl; -import org.eclipse.kapua.service.device.management.keystore.model.internal.DeviceKeystoreSubjectANImpl; -import org.eclipse.kapua.service.device.management.keystore.model.internal.DeviceKeystoresImpl; - -import javax.inject.Singleton; - -/** - * {@link DeviceKeystoreManagementFactory} implementation. - * - * @since 1.5.0 - */ -@Singleton -public class DeviceKeystoreManagementFactoryImpl implements DeviceKeystoreManagementFactory { - - @Override - public DeviceKeystores newDeviceKeystores() { - return new DeviceKeystoresImpl(); - } - - @Override - public DeviceKeystore newDeviceKeystore() { - return new DeviceKeystoreImpl(); - } - - @Override - public DeviceKeystoreItems newDeviceKeystoreItems() { - return new DeviceKeystoreItemsImpl(); - } - - @Override - public DeviceKeystoreItem newDeviceKeystoreItem() { - return new DeviceKeystoreItemImpl(); - } - - @Override - public DeviceKeystoreSubjectAN newDeviceKeystoreSubjectAN() { - return new DeviceKeystoreSubjectANImpl(); - } - - @Override - public DeviceKeystoreItemQuery newDeviceKeystoreItemQuery() { - return new DeviceKeystoreItemQueryImpl(); - } - - @Override - public DeviceKeystoreCertificate newDeviceKeystoreCertificate() { - return new DeviceKeystoreCertificateImpl(); - } - - @Override - public DeviceKeystoreKeypair newDeviceKeystoreKeypair() { - return new DeviceKeystoreKeypairImpl(); - } - - @Override - public DeviceKeystoreCSRInfo newDeviceKeystoreCSRInfo() { - return new DeviceKeystoreCSRInfoImpl(); - } - - @Override - public DeviceKeystoreCSR newDeviceKeystoreCSR() { - return new DeviceKeystoreCSRImpl(); - } -} diff --git a/service/device/management/keystore/internal/src/main/java/org/eclipse/kapua/service/device/management/keystore/internal/DeviceKeystoreManagementServiceImpl.java b/service/device/management/keystore/internal/src/main/java/org/eclipse/kapua/service/device/management/keystore/internal/DeviceKeystoreManagementServiceImpl.java index 63e33accaec..54f9f161e40 100644 --- a/service/device/management/keystore/internal/src/main/java/org/eclipse/kapua/service/device/management/keystore/internal/DeviceKeystoreManagementServiceImpl.java +++ b/service/device/management/keystore/internal/src/main/java/org/eclipse/kapua/service/device/management/keystore/internal/DeviceKeystoreManagementServiceImpl.java @@ -12,7 +12,10 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.keystore.internal; -import com.google.common.base.Strings; +import java.util.Date; + +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaEntityNotFoundException; import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.KapuaIllegalArgumentException; @@ -21,14 +24,13 @@ import org.eclipse.kapua.model.domain.Actions; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; +import org.eclipse.kapua.service.authorization.permission.Permission; import org.eclipse.kapua.service.certificate.info.CertificateInfo; import org.eclipse.kapua.service.certificate.info.CertificateInfoFactory; import org.eclipse.kapua.service.certificate.info.CertificateInfoService; import org.eclipse.kapua.service.device.management.commons.AbstractDeviceManagementTransactionalServiceImpl; import org.eclipse.kapua.service.device.management.commons.call.DeviceCallBuilder; import org.eclipse.kapua.service.device.management.exception.DeviceManagementRequestContentException; -import org.eclipse.kapua.service.device.management.keystore.DeviceKeystoreManagementFactory; import org.eclipse.kapua.service.device.management.keystore.DeviceKeystoreManagementService; import org.eclipse.kapua.service.device.management.keystore.internal.message.request.KeystoreCertificateRequestMessage; import org.eclipse.kapua.service.device.management.keystore.internal.message.request.KeystoreCsrRequestMessage; @@ -50,8 +52,6 @@ import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystoreItems; import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystoreKeypair; import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystores; -import org.eclipse.kapua.service.device.management.keystore.model.internal.DeviceKeystoreCertificateImpl; -import org.eclipse.kapua.service.device.management.keystore.model.internal.DeviceKeystoreItemQueryImpl; import org.eclipse.kapua.service.device.management.message.KapuaMethod; import org.eclipse.kapua.service.device.registry.DeviceRegistryService; import org.eclipse.kapua.service.device.registry.event.DeviceEventFactory; @@ -60,8 +60,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.inject.Singleton; -import java.util.Date; +import com.google.common.base.Strings; /** * {@link DeviceKeystoreManagementService} implementation. @@ -78,26 +77,22 @@ public class DeviceKeystoreManagementServiceImpl extends AbstractDeviceManagemen protected final CertificateInfoService certificateInfoService; protected final CertificateInfoFactory certificateInfoFactory; - private final DeviceKeystoreManagementFactory deviceKeystoreManagementFactory; public DeviceKeystoreManagementServiceImpl( TxManager txManager, AuthorizationService authorizationService, - PermissionFactory permissionFactory, DeviceEventService deviceEventService, DeviceEventFactory deviceEventFactory, DeviceRegistryService deviceRegistryService, CertificateInfoService certificateInfoService, - CertificateInfoFactory certificateInfoFactory, DeviceKeystoreManagementFactory deviceKeystoreManagementFactory) { + CertificateInfoFactory certificateInfoFactory) { super(txManager, authorizationService, - permissionFactory, deviceEventService, deviceEventFactory, deviceRegistryService); this.certificateInfoService = certificateInfoService; this.certificateInfoFactory = certificateInfoFactory; - this.deviceKeystoreManagementFactory = deviceKeystoreManagementFactory; } @Override @@ -107,7 +102,7 @@ public DeviceKeystores getKeystores(KapuaId scopeId, KapuaId deviceId, Long time ArgumentValidator.notNull(scopeId, SCOPE_ID); ArgumentValidator.notNull(deviceId, DEVICE_ID); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE_MANAGEMENT, Actions.read, scopeId)); + authorizationService.checkPermission(new Permission(Domains.DEVICE_MANAGEMENT, Actions.read, scopeId)); // Prepare the request KeystoreRequestChannel keystoreRequestChannel = new KeystoreRequestChannel(); keystoreRequestChannel.setAppName(DeviceKeystoreAppProperties.APP_NAME); @@ -117,6 +112,7 @@ public DeviceKeystores getKeystores(KapuaId scopeId, KapuaId deviceId, Long time KeystoreRequestPayload keystoreRequestPayload = new KeystoreRequestPayload(); KeystoreQueryRequestMessage keystoreRequestMessage = new KeystoreQueryRequestMessage() { + @Override public Class getResponseClass() { return KeystoresResponseMessage.class; @@ -147,12 +143,12 @@ public Class getResponseClass() { // Create event createDeviceEvent(scopeId, deviceId, keystoreRequestMessage, responseMessage); // Check response - return checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getKeystores().orElse(deviceKeystoreManagementFactory.newDeviceKeystores())); + return checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getKeystores().orElse(new DeviceKeystores())); } @Override public DeviceKeystoreItems getKeystoreItems(KapuaId scopeId, KapuaId deviceId, Long timeout) throws KapuaException { - return getKeystoreItems(scopeId, deviceId, new DeviceKeystoreItemQueryImpl(), timeout); + return getKeystoreItems(scopeId, deviceId, new DeviceKeystoreItemQuery(), timeout); } @Override @@ -170,7 +166,7 @@ public DeviceKeystoreItems getKeystoreItems(KapuaId scopeId, KapuaId deviceId, D throw new KapuaIllegalArgumentException("itemQuery.alias", itemQuery.getAlias()); } // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE_MANAGEMENT, Actions.read, scopeId)); + authorizationService.checkPermission(new Permission(Domains.DEVICE_MANAGEMENT, Actions.read, scopeId)); // Prepare the request KeystoreRequestChannel keystoreRequestChannel = new KeystoreRequestChannel(); keystoreRequestChannel.setAppName(DeviceKeystoreAppProperties.APP_NAME); @@ -186,6 +182,7 @@ public DeviceKeystoreItems getKeystoreItems(KapuaId scopeId, KapuaId deviceId, D } KeystoreQueryRequestMessage keystoreRequestMessage = new KeystoreQueryRequestMessage() { + @Override public Class getResponseClass() { return KeystoreItemsResponseMessage.class; @@ -216,7 +213,7 @@ public Class getResponseClass() { // Create event createDeviceEvent(scopeId, deviceId, keystoreRequestMessage, responseMessage); // Check response - return checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getKeystoreItems().orElse(deviceKeystoreManagementFactory.newDeviceKeystoreItems())); + return checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getKeystoreItems().orElse(new DeviceKeystoreItems())); } @Override @@ -227,7 +224,7 @@ public DeviceKeystoreItem getKeystoreItem(KapuaId scopeId, KapuaId deviceId, Str ArgumentValidator.notEmptyOrNull(keystoreId, "keystoreId"); ArgumentValidator.notEmptyOrNull(alias, "alias"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE_MANAGEMENT, Actions.read, scopeId)); + authorizationService.checkPermission(new Permission(Domains.DEVICE_MANAGEMENT, Actions.read, scopeId)); // Prepare the request KeystoreRequestChannel keystoreRequestChannel = new KeystoreRequestChannel(); keystoreRequestChannel.setAppName(DeviceKeystoreAppProperties.APP_NAME); @@ -236,7 +233,7 @@ public DeviceKeystoreItem getKeystoreItem(KapuaId scopeId, KapuaId deviceId, Str keystoreRequestChannel.setResource("item"); // Build query - DeviceKeystoreItemQuery itemQuery = new DeviceKeystoreItemQueryImpl(); + DeviceKeystoreItemQuery itemQuery = new DeviceKeystoreItemQuery(); itemQuery.setKeystoreId(keystoreId); itemQuery.setAlias(alias); @@ -248,6 +245,7 @@ public DeviceKeystoreItem getKeystoreItem(KapuaId scopeId, KapuaId deviceId, Str } KeystoreQueryRequestMessage keystoreRequestMessage = new KeystoreQueryRequestMessage() { + @Override public Class getResponseClass() { return KeystoreItemResponseMessage.class; @@ -278,7 +276,7 @@ public Class getResponseClass() { // Create event createDeviceEvent(scopeId, deviceId, keystoreRequestMessage, responseMessage); // Check response - return checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getKeystoreItem().orElse(deviceKeystoreManagementFactory.newDeviceKeystoreItem())); + return checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getKeystoreItem().orElse(new DeviceKeystoreItem())); } @Override @@ -293,7 +291,8 @@ public void createKeystoreCertificate(KapuaId scopeId, KapuaId deviceId, String try { certificateInfo = certificateInfoService.find(scopeId, certificateId); } catch (UnsupportedOperationException e) { - LOG.warn("Unable to get the certificate {} since the implementation does not support CertificateInfoService.find(scopeId, certificateId)... Returning KapuaEntityNotFoundException!", certificateId); + LOG.warn("Unable to get the certificate {} since the implementation does not support CertificateInfoService.find(scopeId, certificateId)... Returning KapuaEntityNotFoundException!", + certificateId); throw new KapuaEntityNotFoundException(CertificateInfo.TYPE, certificateId); } @@ -301,7 +300,7 @@ public void createKeystoreCertificate(KapuaId scopeId, KapuaId deviceId, String throw new KapuaEntityNotFoundException(CertificateInfo.TYPE, certificateId); } // Build DeviceKeystoreCertificate create - DeviceKeystoreCertificate deviceKeystoreCertificate = new DeviceKeystoreCertificateImpl(); + DeviceKeystoreCertificate deviceKeystoreCertificate = new DeviceKeystoreCertificate(); deviceKeystoreCertificate.setKeystoreId(keystoreId); deviceKeystoreCertificate.setAlias(alias); deviceKeystoreCertificate.setCertificate(certificateInfo.getCertificate()); @@ -316,7 +315,7 @@ public void createKeystoreCertificate(KapuaId scopeId, KapuaId deviceId, DeviceK ArgumentValidator.notNull(deviceId, DEVICE_ID); ArgumentValidator.notNull(keystoreCertificate, "keystoreCertificate"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE_MANAGEMENT, Actions.write, scopeId)); + authorizationService.checkPermission(new Permission(Domains.DEVICE_MANAGEMENT, Actions.write, scopeId)); // Prepare the request KeystoreRequestChannel keystoreRequestChannel = new KeystoreRequestChannel(); keystoreRequestChannel.setAppName(DeviceKeystoreAppProperties.APP_NAME); @@ -332,6 +331,7 @@ public void createKeystoreCertificate(KapuaId scopeId, KapuaId deviceId, DeviceK } KeystoreCertificateRequestMessage keystoreRequestMessage = new KeystoreCertificateRequestMessage() { + @Override public Class getResponseClass() { return KeystoreNoContentResponseMessage.class; @@ -373,7 +373,7 @@ public void createKeystoreKeypair(KapuaId scopeId, KapuaId deviceId, DeviceKeyst ArgumentValidator.notNull(deviceId, DEVICE_ID); ArgumentValidator.notNull(keystoreKeypair, "keystoreKeypair"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE_MANAGEMENT, Actions.write, scopeId)); + authorizationService.checkPermission(new Permission(Domains.DEVICE_MANAGEMENT, Actions.write, scopeId)); // Prepare the request KeystoreRequestChannel keystoreRequestChannel = new KeystoreRequestChannel(); keystoreRequestChannel.setAppName(DeviceKeystoreAppProperties.APP_NAME); @@ -389,6 +389,7 @@ public void createKeystoreKeypair(KapuaId scopeId, KapuaId deviceId, DeviceKeyst } KeystoreKeypairRequestMessage keystoreRequestMessage = new KeystoreKeypairRequestMessage() { + @Override public Class getResponseClass() { return KeystoreNoContentResponseMessage.class; @@ -430,7 +431,7 @@ public DeviceKeystoreCSR createKeystoreCSR(KapuaId scopeId, KapuaId deviceId, De ArgumentValidator.notNull(deviceId, DEVICE_ID); ArgumentValidator.notNull(keystoreCSRInfo, "keystoreCSRInfo"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE_MANAGEMENT, Actions.read, scopeId)); + authorizationService.checkPermission(new Permission(Domains.DEVICE_MANAGEMENT, Actions.read, scopeId)); // Prepare the request KeystoreRequestChannel keystoreRequestChannel = new KeystoreRequestChannel(); keystoreRequestChannel.setAppName(DeviceKeystoreAppProperties.APP_NAME); @@ -446,6 +447,7 @@ public DeviceKeystoreCSR createKeystoreCSR(KapuaId scopeId, KapuaId deviceId, De } KeystoreCsrRequestMessage keystoreRequestMessage = new KeystoreCsrRequestMessage() { + @Override public Class getResponseClass() { return KeystoreCsrResponseMessage.class; @@ -477,7 +479,7 @@ public Class getResponseClass() { // Create event createDeviceEvent(scopeId, deviceId, keystoreRequestMessage, responseMessage); // Check response - return checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getCSR().orElse(deviceKeystoreManagementFactory.newDeviceKeystoreCSR())); + return checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getCSR().orElse(new DeviceKeystoreCSR())); } @Override @@ -488,7 +490,7 @@ public void deleteKeystoreItem(KapuaId scopeId, KapuaId deviceId, String keystor ArgumentValidator.notEmptyOrNull(keystoreId, "keystoreId"); ArgumentValidator.notEmptyOrNull(alias, "alias"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE_MANAGEMENT, Actions.delete, scopeId)); + authorizationService.checkPermission(new Permission(Domains.DEVICE_MANAGEMENT, Actions.delete, scopeId)); // Prepare the request KeystoreRequestChannel keystoreRequestChannel = new KeystoreRequestChannel(); keystoreRequestChannel.setAppName(DeviceKeystoreAppProperties.APP_NAME); @@ -497,7 +499,7 @@ public void deleteKeystoreItem(KapuaId scopeId, KapuaId deviceId, String keystor keystoreRequestChannel.setResource("items"); // Build query - DeviceKeystoreItemQuery itemQuery = new DeviceKeystoreItemQueryImpl(); + DeviceKeystoreItemQuery itemQuery = new DeviceKeystoreItemQuery(); itemQuery.setKeystoreId(keystoreId); itemQuery.setAlias(alias); @@ -509,6 +511,7 @@ public void deleteKeystoreItem(KapuaId scopeId, KapuaId deviceId, String keystor } KeystoreQueryRequestMessage keystoreRequestMessage = new KeystoreQueryRequestMessage() { + @Override public Class getResponseClass() { return KeystoreNoContentResponseMessage.class; diff --git a/service/device/management/keystore/internal/src/main/java/org/eclipse/kapua/service/device/management/keystore/internal/DeviceManagementKeystoreModule.java b/service/device/management/keystore/internal/src/main/java/org/eclipse/kapua/service/device/management/keystore/internal/DeviceManagementKeystoreModule.java index a863682f9e7..0ec58805760 100644 --- a/service/device/management/keystore/internal/src/main/java/org/eclipse/kapua/service/device/management/keystore/internal/DeviceManagementKeystoreModule.java +++ b/service/device/management/keystore/internal/src/main/java/org/eclipse/kapua/service/device/management/keystore/internal/DeviceManagementKeystoreModule.java @@ -12,49 +12,44 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.keystore.internal; -import com.google.inject.Provides; +import javax.inject.Singleton; + import org.eclipse.kapua.commons.core.AbstractKapuaModule; import org.eclipse.kapua.commons.jpa.KapuaJpaTxManagerFactory; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; import org.eclipse.kapua.service.certificate.info.CertificateInfoFactory; import org.eclipse.kapua.service.certificate.info.CertificateInfoService; -import org.eclipse.kapua.service.device.management.keystore.DeviceKeystoreManagementFactory; import org.eclipse.kapua.service.device.management.keystore.DeviceKeystoreManagementService; import org.eclipse.kapua.service.device.registry.DeviceRegistryService; import org.eclipse.kapua.service.device.registry.event.DeviceEventFactory; import org.eclipse.kapua.service.device.registry.event.DeviceEventService; -import javax.inject.Singleton; +import com.google.inject.Provides; public class DeviceManagementKeystoreModule extends AbstractKapuaModule { + @Override protected void configureModule() { - bind(DeviceKeystoreManagementFactory.class).to(DeviceKeystoreManagementFactoryImpl.class); } @Provides @Singleton DeviceKeystoreManagementService deviceKeystoreManagementService( AuthorizationService authorizationService, - PermissionFactory permissionFactory, DeviceEventService deviceEventService, DeviceEventFactory deviceEventFactory, DeviceRegistryService deviceRegistryService, CertificateInfoService certificateInfoService, CertificateInfoFactory certificateInfoFactory, - KapuaJpaTxManagerFactory jpaTxManagerFactory, - DeviceKeystoreManagementFactory deviceKeystoreManagementFactory + KapuaJpaTxManagerFactory jpaTxManagerFactory ) { return new DeviceKeystoreManagementServiceImpl( jpaTxManagerFactory.create("kapua-device_management_operation_registry"), authorizationService, - permissionFactory, deviceEventService, deviceEventFactory, deviceRegistryService, certificateInfoService, - certificateInfoFactory, - deviceKeystoreManagementFactory); + certificateInfoFactory); } } diff --git a/service/device/management/keystore/internal/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/internal/DeviceKeystoreCSRImpl.java b/service/device/management/keystore/internal/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/internal/DeviceKeystoreCSRImpl.java deleted file mode 100644 index 69af06333e8..00000000000 --- a/service/device/management/keystore/internal/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/internal/DeviceKeystoreCSRImpl.java +++ /dev/null @@ -1,43 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.keystore.model.internal; - -import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystoreCSR; - -/** - * {@link DeviceKeystoreCSR} implementation. - * - * @since 1.5.0 - */ -public class DeviceKeystoreCSRImpl implements DeviceKeystoreCSR { - - private String signingRequest; - - /** - * Constructor. - * - * @since 1.5.0 - */ - public DeviceKeystoreCSRImpl() { - } - - @Override - public String getSigningRequest() { - return signingRequest; - } - - @Override - public void setSigningRequest(String signingRequest) { - this.signingRequest = signingRequest; - } -} \ No newline at end of file diff --git a/service/device/management/keystore/internal/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/internal/DeviceKeystoreCSRInfoImpl.java b/service/device/management/keystore/internal/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/internal/DeviceKeystoreCSRInfoImpl.java deleted file mode 100644 index 4854d51d727..00000000000 --- a/service/device/management/keystore/internal/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/internal/DeviceKeystoreCSRInfoImpl.java +++ /dev/null @@ -1,76 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.keystore.model.internal; - -import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystoreCSRInfo; - -/** - * {@link DeviceKeystoreCSRInfo} implementation. - * - * @since 1.5.0 - */ -public class DeviceKeystoreCSRInfoImpl implements DeviceKeystoreCSRInfo { - - private String keystoreId; - private String alias; - private String signatureAlgorithm; - private String attributes; - - /** - * Constructor. - * - * @since 1.5.0 - */ - public DeviceKeystoreCSRInfoImpl() { - } - - @Override - public String getKeystoreId() { - return keystoreId; - } - - @Override - public void setKeystoreId(String keystoreId) { - this.keystoreId = keystoreId; - } - - @Override - public String getAlias() { - return alias; - } - - @Override - public void setAlias(String alias) { - this.alias = alias; - } - - @Override - public String getSignatureAlgorithm() { - return signatureAlgorithm; - } - - @Override - public void setSignatureAlgorithm(String signatureAlgorithm) { - this.signatureAlgorithm = signatureAlgorithm; - } - - @Override - public String getAttributes() { - return attributes; - } - - @Override - public void setAttributes(String attributes) { - this.attributes = attributes; - } -} diff --git a/service/device/management/keystore/internal/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/internal/DeviceKeystoreCertificateImpl.java b/service/device/management/keystore/internal/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/internal/DeviceKeystoreCertificateImpl.java deleted file mode 100644 index cbda861ffcb..00000000000 --- a/service/device/management/keystore/internal/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/internal/DeviceKeystoreCertificateImpl.java +++ /dev/null @@ -1,65 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.keystore.model.internal; - -import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystoreCertificate; - -/** - * {@link DeviceKeystoreCertificate} implementation. - * - * @since 1.5.0 - */ -public class DeviceKeystoreCertificateImpl implements DeviceKeystoreCertificate { - - private String keystoreId; - private String alias; - private String certificate; - - /** - * Constructor. - * - * @since 1.5.0 - */ - public DeviceKeystoreCertificateImpl() { - } - - @Override - public String getKeystoreId() { - return keystoreId; - } - - @Override - public void setKeystoreId(String keystoreId) { - this.keystoreId = keystoreId; - } - - @Override - public String getAlias() { - return alias; - } - - @Override - public void setAlias(String alias) { - this.alias = alias; - } - - @Override - public String getCertificate() { - return certificate; - } - - @Override - public void setCertificate(String certificate) { - this.certificate = certificate; - } -} \ No newline at end of file diff --git a/service/device/management/keystore/internal/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/internal/DeviceKeystoreImpl.java b/service/device/management/keystore/internal/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/internal/DeviceKeystoreImpl.java deleted file mode 100644 index 1eb528a82cf..00000000000 --- a/service/device/management/keystore/internal/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/internal/DeviceKeystoreImpl.java +++ /dev/null @@ -1,65 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.keystore.model.internal; - -import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystore; - -/** - * {@link DeviceKeystore} implementation. - * - * @since 1.5.0 - */ -public class DeviceKeystoreImpl implements DeviceKeystore { - - private String id; - private String keystoreType; - private Integer size; - - /** - * Constructor. - * - * @since 1.5.0 - */ - public DeviceKeystoreImpl() { - } - - @Override - public String getId() { - return id; - } - - @Override - public void setId(String id) { - this.id = id; - } - - @Override - public String getKeystoreType() { - return keystoreType; - } - - @Override - public void setKeystoreType(String keystoreType) { - this.keystoreType = keystoreType; - } - - @Override - public Integer getSize() { - return size; - } - - @Override - public void setSize(Integer size) { - this.size = size; - } -} diff --git a/service/device/management/keystore/internal/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/internal/DeviceKeystoreItemImpl.java b/service/device/management/keystore/internal/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/internal/DeviceKeystoreItemImpl.java deleted file mode 100644 index 7aea72060da..00000000000 --- a/service/device/management/keystore/internal/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/internal/DeviceKeystoreItemImpl.java +++ /dev/null @@ -1,187 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.keystore.model.internal; - -import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystoreItem; -import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystoreSubjectAN; - -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -/** - * {@link DeviceKeystoreItem} implementation. - * - * @since 1.5.0 - */ -public class DeviceKeystoreItemImpl implements DeviceKeystoreItem { - - private String keystoreId; - private String itemType; - private Integer size; - private String algorithm; - private String alias; - private String subjectDN; - private List subjectAN; - private String issuer; - private Date notBefore; - private Date notAfter; - private String certificate; - private List certificateChain; - - /** - * Constructor. - * - * @since 1.5.0 - */ - public DeviceKeystoreItemImpl() { - } - - @Override - public String getKeystoreId() { - return keystoreId; - } - - @Override - public void setKeystoreId(String keystoreId) { - this.keystoreId = keystoreId; - } - - @Override - public String getItemType() { - return itemType; - } - - @Override - public void setItemType(String itemType) { - this.itemType = itemType; - } - - @Override - public Integer getSize() { - return size; - } - - @Override - public void setSize(Integer size) { - this.size = size; - } - - @Override - public String getAlgorithm() { - return algorithm; - } - - @Override - public void setAlgorithm(String algorithm) { - this.algorithm = algorithm; - } - - @Override - public String getAlias() { - return alias; - } - - @Override - public void setAlias(String alias) { - this.alias = alias; - } - - @Override - public String getSubjectDN() { - return subjectDN; - } - - @Override - public void setSubjectDN(String subjectDN) { - this.subjectDN = subjectDN; - } - - @Override - public List getSubjectAN() { - if (subjectAN == null) { - subjectAN = new ArrayList<>(); - } - - return subjectAN; - } - - @Override - public void addSubjectAN(DeviceKeystoreSubjectAN subjectAN) { - getSubjectAN().add(subjectAN); - } - - @Override - public void setSubjectAN(List subjectAN) { - this.subjectAN = subjectAN; - } - - @Override - public String getIssuer() { - return issuer; - } - - @Override - public void setIssuer(String issuer) { - this.issuer = issuer; - } - - @Override - public Date getNotBefore() { - return notBefore; - } - - @Override - public void setNotBefore(Date notBefore) { - this.notBefore = notBefore; - } - - @Override - public Date getNotAfter() { - return notAfter; - } - - @Override - public void setNotAfter(Date notAfter) { - this.notAfter = notAfter; - } - - @Override - public String getCertificate() { - return certificate; - } - - @Override - public void setCertificate(String certificate) { - this.certificate = certificate; - } - - @Override - public List getCertificateChain() { - if (certificateChain == null) { - certificateChain = new ArrayList<>(); - } - - return certificateChain; - } - - @Override - public void addCertificateChain(String certificate) { - getCertificateChain().add(certificate); - } - - @Override - public void setCertificateChain(List certificateChain) { - this.certificateChain = certificateChain; - } -} diff --git a/service/device/management/keystore/internal/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/internal/DeviceKeystoreItemQueryImpl.java b/service/device/management/keystore/internal/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/internal/DeviceKeystoreItemQueryImpl.java deleted file mode 100644 index 4437550c735..00000000000 --- a/service/device/management/keystore/internal/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/internal/DeviceKeystoreItemQueryImpl.java +++ /dev/null @@ -1,61 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.keystore.model.internal; - -import com.google.common.base.Strings; -import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystoreItemQuery; - -/** - * {@link DeviceKeystoreItemQuery} implementation. - * - * @since 1.5.0 - */ -public class DeviceKeystoreItemQueryImpl implements DeviceKeystoreItemQuery { - - private String keystoreId; - private String alias; - - /** - * Constructor. - * - * @since 1.5.0 - */ - public DeviceKeystoreItemQueryImpl() { - } - - @Override - public String getKeystoreId() { - return keystoreId; - } - - @Override - public void setKeystoreId(String keystoreId) { - this.keystoreId = keystoreId; - } - - @Override - public String getAlias() { - return alias; - } - - @Override - public void setAlias(String alias) { - this.alias = alias; - } - - @Override - public boolean hasFilters() { - return !Strings.isNullOrEmpty(getKeystoreId()) || - !Strings.isNullOrEmpty(getAlias()); - } -} diff --git a/service/device/management/keystore/internal/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/internal/DeviceKeystoreItemsImpl.java b/service/device/management/keystore/internal/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/internal/DeviceKeystoreItemsImpl.java deleted file mode 100644 index 535015e62ae..00000000000 --- a/service/device/management/keystore/internal/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/internal/DeviceKeystoreItemsImpl.java +++ /dev/null @@ -1,58 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.keystore.model.internal; - -import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystoreItem; -import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystoreItems; - -import java.util.ArrayList; -import java.util.List; - -/** - * {@link DeviceKeystoreItems} implementation. - * - * @since 1.5.0 - */ -public class DeviceKeystoreItemsImpl implements DeviceKeystoreItems { - - private static final long serialVersionUID = 1318691706440015345L; - - private List keystoreItems; - - /** - * Constructor. - * - * @since 1.5.0 - */ - public DeviceKeystoreItemsImpl() { - } - - @Override - public List getKeystoreItems() { - if (keystoreItems == null) { - keystoreItems = new ArrayList<>(); - } - - return keystoreItems; - } - - @Override - public void addKeystoreItem(DeviceKeystoreItem keystoreItem) { - getKeystoreItems().add(keystoreItem); - } - - @Override - public void setKeystoreItems(List keystoreItems) { - this.keystoreItems = keystoreItems; - } -} diff --git a/service/device/management/keystore/internal/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/internal/DeviceKeystoreKeypairImpl.java b/service/device/management/keystore/internal/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/internal/DeviceKeystoreKeypairImpl.java deleted file mode 100644 index 0ec2bbd00ed..00000000000 --- a/service/device/management/keystore/internal/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/internal/DeviceKeystoreKeypairImpl.java +++ /dev/null @@ -1,98 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.keystore.model.internal; - -import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystoreKeypair; - -/** - * {@link DeviceKeystoreKeypair} implementation. - * - * @since 1.5.0 - */ -public class DeviceKeystoreKeypairImpl implements DeviceKeystoreKeypair { - - private String keystoreId; - private String alias; - private String algorithm; - private String signatureAlgorithm; - private Integer size; - private String attributes; - - /** - * Constructor. - * - * @since 1.5.0 - */ - public DeviceKeystoreKeypairImpl() { - } - - @Override - public String getKeystoreId() { - return keystoreId; - } - - @Override - public void setKeystoreId(String keystoreId) { - this.keystoreId = keystoreId; - } - - @Override - public String getAlias() { - return alias; - } - - @Override - public void setAlias(String alias) { - this.alias = alias; - } - - @Override - public String getAlgorithm() { - return algorithm; - } - - @Override - public void setAlgorithm(String algorithm) { - this.algorithm = algorithm; - } - - @Override - public String getSignatureAlgorithm() { - return signatureAlgorithm; - } - - @Override - public void setSignatureAlgorithm(String signatureAlgorithm) { - this.signatureAlgorithm = signatureAlgorithm; - } - - @Override - public Integer getSize() { - return size; - } - - @Override - public void setSize(Integer size) { - this.size = size; - } - - @Override - public String getAttributes() { - return attributes; - } - - @Override - public void setAttributes(String attributes) { - this.attributes = attributes; - } -} diff --git a/service/device/management/keystore/internal/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/internal/DeviceKeystoreSubjectANImpl.java b/service/device/management/keystore/internal/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/internal/DeviceKeystoreSubjectANImpl.java deleted file mode 100644 index be8f70d6739..00000000000 --- a/service/device/management/keystore/internal/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/internal/DeviceKeystoreSubjectANImpl.java +++ /dev/null @@ -1,59 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.keystore.model.internal; - -import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystoreSubjectAN; - -/** - * {@link DeviceKeystoreSubjectAN} implementation. - * - * @since 1.5.0 - */ -public class DeviceKeystoreSubjectANImpl implements DeviceKeystoreSubjectAN { - - private String anType; - private String value; - - public DeviceKeystoreSubjectANImpl() { - } - - /** - * Constructor. - * - * @since 1.5.0 - */ - public DeviceKeystoreSubjectANImpl(String anType, String anValue) { - setANType(anType); - setValue(anValue); - } - - @Override - public String getANType() { - return anType; - } - - @Override - public void setANType(String anType) { - this.anType = anType; - } - - @Override - public String getValue() { - return value; - } - - @Override - public void setValue(String value) { - this.value = value; - } -} diff --git a/service/device/management/keystore/internal/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/internal/DeviceKeystoresImpl.java b/service/device/management/keystore/internal/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/internal/DeviceKeystoresImpl.java deleted file mode 100644 index bd56c2fc92e..00000000000 --- a/service/device/management/keystore/internal/src/main/java/org/eclipse/kapua/service/device/management/keystore/model/internal/DeviceKeystoresImpl.java +++ /dev/null @@ -1,58 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.keystore.model.internal; - -import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystore; -import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystores; - -import java.util.ArrayList; -import java.util.List; - -/** - * {@link DeviceKeystores} implementation. - * - * @since 1.5.0 - */ -public class DeviceKeystoresImpl implements DeviceKeystores { - - private static final long serialVersionUID = 1318691706440015345L; - - private List keystores; - - /** - * Constructor. - * - * @since 1.5.0 - */ - public DeviceKeystoresImpl() { - } - - @Override - public List getKeystores() { - if (keystores == null) { - keystores = new ArrayList<>(); - } - - return keystores; - } - - @Override - public void addKeystore(DeviceKeystore keystore) { - getKeystores().add(keystore); - } - - @Override - public void setKeystores(List keystores) { - this.keystores = keystores; - } -} diff --git a/service/device/management/keystore/job/pom.xml b/service/device/management/keystore/job/pom.xml index f74f99da050..9ebabe6218f 100644 --- a/service/device/management/keystore/job/pom.xml +++ b/service/device/management/keystore/job/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-device-management-keystore - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-device-management-keystore-job diff --git a/service/device/management/keystore/job/src/main/java/org/eclipse/kapua/service/device/management/keystore/job/DeviceKeystoreCertificateCreateTargetProcessor.java b/service/device/management/keystore/job/src/main/java/org/eclipse/kapua/service/device/management/keystore/job/DeviceKeystoreCertificateCreateTargetProcessor.java index 6f3ad6c3335..46bdcfcb0ee 100644 --- a/service/device/management/keystore/job/src/main/java/org/eclipse/kapua/service/device/management/keystore/job/DeviceKeystoreCertificateCreateTargetProcessor.java +++ b/service/device/management/keystore/job/src/main/java/org/eclipse/kapua/service/device/management/keystore/job/DeviceKeystoreCertificateCreateTargetProcessor.java @@ -12,22 +12,21 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.keystore.job; +import javax.batch.runtime.context.JobContext; +import javax.batch.runtime.context.StepContext; +import javax.inject.Inject; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.commons.security.KapuaSecurityUtils; import org.eclipse.kapua.job.engine.commons.operation.AbstractDeviceTargetProcessor; import org.eclipse.kapua.job.engine.commons.wrappers.JobTargetWrapper; import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.device.management.keystore.DeviceKeystoreManagementFactory; import org.eclipse.kapua.service.device.management.keystore.DeviceKeystoreManagementService; import org.eclipse.kapua.service.device.management.keystore.job.definition.DeviceKeystoreCertificateCreatePropertyKeys; import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystoreCertificate; import org.eclipse.kapua.service.job.operation.TargetProcessor; import org.eclipse.kapua.service.job.targets.JobTarget; -import javax.batch.runtime.context.JobContext; -import javax.batch.runtime.context.StepContext; -import javax.inject.Inject; - /** * {@link TargetProcessor} for {@link DeviceKeystoreManagementService#createKeystoreCertificate(KapuaId, KapuaId, DeviceKeystoreCertificate, Long)}. * @@ -38,8 +37,6 @@ public class DeviceKeystoreCertificateCreateTargetProcessor extends AbstractDevi @Inject DeviceKeystoreManagementService deviceKeystoreManagementService; @Inject - DeviceKeystoreManagementFactory deviceKeystoreManagementFactory; - @Inject JobContext jobContext; @Inject StepContext stepContext; @@ -57,7 +54,7 @@ public void processTarget(JobTarget jobTarget) throws KapuaException { String certificate = stepContextWrapper.getStepProperty(DeviceKeystoreCertificateCreatePropertyKeys.CERTIFICATE, String.class); Long timeout = stepContextWrapper.getStepProperty(DeviceKeystoreCertificateCreatePropertyKeys.TIMEOUT, Long.class); - DeviceKeystoreCertificate deviceKeystoreCertificate = deviceKeystoreManagementFactory.newDeviceKeystoreCertificate(); + DeviceKeystoreCertificate deviceKeystoreCertificate = new DeviceKeystoreCertificate(); deviceKeystoreCertificate.setKeystoreId(keystoreId); deviceKeystoreCertificate.setAlias(alias); diff --git a/service/device/management/keystore/job/src/main/java/org/eclipse/kapua/service/device/management/keystore/job/DeviceKeystoreKeypairCreateTargetProcessor.java b/service/device/management/keystore/job/src/main/java/org/eclipse/kapua/service/device/management/keystore/job/DeviceKeystoreKeypairCreateTargetProcessor.java index ff8b4403c11..7c53bed4e13 100644 --- a/service/device/management/keystore/job/src/main/java/org/eclipse/kapua/service/device/management/keystore/job/DeviceKeystoreKeypairCreateTargetProcessor.java +++ b/service/device/management/keystore/job/src/main/java/org/eclipse/kapua/service/device/management/keystore/job/DeviceKeystoreKeypairCreateTargetProcessor.java @@ -12,12 +12,15 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.keystore.job; +import javax.batch.runtime.context.JobContext; +import javax.batch.runtime.context.StepContext; +import javax.inject.Inject; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.commons.security.KapuaSecurityUtils; import org.eclipse.kapua.job.engine.commons.operation.AbstractDeviceTargetProcessor; import org.eclipse.kapua.job.engine.commons.wrappers.JobTargetWrapper; import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.device.management.keystore.DeviceKeystoreManagementFactory; import org.eclipse.kapua.service.device.management.keystore.DeviceKeystoreManagementService; import org.eclipse.kapua.service.device.management.keystore.job.definition.DeviceKeystoreKeypairCreatePropertyKeys; import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystoreCertificate; @@ -25,10 +28,6 @@ import org.eclipse.kapua.service.job.operation.TargetProcessor; import org.eclipse.kapua.service.job.targets.JobTarget; -import javax.batch.runtime.context.JobContext; -import javax.batch.runtime.context.StepContext; -import javax.inject.Inject; - /** * {@link TargetProcessor} for {@link DeviceKeystoreManagementService#createKeystoreCertificate(KapuaId, KapuaId, DeviceKeystoreCertificate, Long)}. * @@ -39,8 +38,6 @@ public class DeviceKeystoreKeypairCreateTargetProcessor extends AbstractDeviceTa @Inject DeviceKeystoreManagementService deviceKeystoreManagementService; @Inject - DeviceKeystoreManagementFactory deviceKeystoreManagementFactory; - @Inject JobContext jobContext; @Inject StepContext stepContext; @@ -61,7 +58,7 @@ public void processTarget(JobTarget jobTarget) throws KapuaException { String attributes = stepContextWrapper.getStepProperty(DeviceKeystoreKeypairCreatePropertyKeys.ATTRIBUTES, String.class); Long timeout = stepContextWrapper.getStepProperty(DeviceKeystoreKeypairCreatePropertyKeys.TIMEOUT, Long.class); - DeviceKeystoreKeypair deviceKeystoreKeypair = deviceKeystoreManagementFactory.newDeviceKeystoreKeypair(); + DeviceKeystoreKeypair deviceKeystoreKeypair = new DeviceKeystoreKeypair(); deviceKeystoreKeypair.setKeystoreId(keystoreId); deviceKeystoreKeypair.setAlias(alias); diff --git a/service/device/management/keystore/pom.xml b/service/device/management/keystore/pom.xml index b89c44ad26d..53c6a41a022 100644 --- a/service/device/management/keystore/pom.xml +++ b/service/device/management/keystore/pom.xml @@ -19,7 +19,7 @@ kapua-device-management org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-device-management-keystore diff --git a/service/device/management/packages/api/pom.xml b/service/device/management/packages/api/pom.xml index dac3b355f01..4584f6561e5 100644 --- a/service/device/management/packages/api/pom.xml +++ b/service/device/management/packages/api/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-device-management-packages - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-device-management-packages-api diff --git a/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/DevicePackageFactory.java b/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/DevicePackageFactory.java deleted file mode 100644 index 1c41afcc3aa..00000000000 --- a/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/DevicePackageFactory.java +++ /dev/null @@ -1,152 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.packages; - -import org.eclipse.kapua.model.KapuaObjectFactory; -import org.eclipse.kapua.service.device.management.packages.model.DevicePackage; -import org.eclipse.kapua.service.device.management.packages.model.DevicePackageBundleInfo; -import org.eclipse.kapua.service.device.management.packages.model.DevicePackageBundleInfos; -import org.eclipse.kapua.service.device.management.packages.model.DevicePackages; -import org.eclipse.kapua.service.device.management.packages.model.download.AdvancedPackageDownloadOptions; -import org.eclipse.kapua.service.device.management.packages.model.download.DevicePackageDownloadOperation; -import org.eclipse.kapua.service.device.management.packages.model.download.DevicePackageDownloadOptions; -import org.eclipse.kapua.service.device.management.packages.model.download.DevicePackageDownloadRequest; -import org.eclipse.kapua.service.device.management.packages.model.install.DevicePackageInstallOperation; -import org.eclipse.kapua.service.device.management.packages.model.install.DevicePackageInstallOptions; -import org.eclipse.kapua.service.device.management.packages.model.install.DevicePackageInstallRequest; -import org.eclipse.kapua.service.device.management.packages.model.uninstall.DevicePackageUninstallOperation; -import org.eclipse.kapua.service.device.management.packages.model.uninstall.DevicePackageUninstallOptions; -import org.eclipse.kapua.service.device.management.packages.model.uninstall.DevicePackageUninstallRequest; - -/** - * {@link DevicePackageFactory} definition. - * - * @since 1.0.0 - */ -public interface DevicePackageFactory extends KapuaObjectFactory { - - /** - * Creates a new {@link DevicePackages} - * - * @return the newly created {@link DevicePackages} - * @since 1.0.0 - */ - DevicePackages newDeviceDeploymentPackages(); - - /** - * Creates a new {@link DevicePackage} - * - * @return The newly created {@link DevicePackage} - * @since 1.0.0 - */ - DevicePackage newDeviceDeploymentPackage(); - - /** - * Creates a new {@link DevicePackageBundleInfo} - * - * @return the newly created {@link DevicePackageBundleInfo} - * @since 1.0.0 - */ - DevicePackageBundleInfo newDevicePackageBundleInfo(); - - /** - * Creates a new {@link DevicePackageBundleInfos} - * - * @return the newly created {@link DevicePackageBundleInfos} - * @since 1.0.0 - */ - DevicePackageBundleInfos newDevicePackageBundleInfos(); - // Download operation - - /** - * Creates a new {@link DevicePackageDownloadRequest} - * - * @return The newly created {@link DevicePackageDownloadRequest} - * @since 1.0.0 - */ - DevicePackageDownloadRequest newPackageDownloadRequest(); - - /** - * Creates a new {@link DevicePackageDownloadOptions} - * - * @return the newly created {@link DevicePackageDownloadOptions} - * @since 1.1.0 - */ - DevicePackageDownloadOptions newPackageDownloadOptions(); - - /** - * Creates a new {@link AdvancedPackageDownloadOptions} - * - * @return the newly created {@link AdvancedPackageDownloadOptions} - * @since 1.1.0 - */ - AdvancedPackageDownloadOptions newAdvancedPackageDownloadOptions(); - - /** - * Creates a new {@link DevicePackageDownloadOperation} - * - * @return the newly created {@link DevicePackageDownloadOperation} - * @since 1.0.0 - */ - DevicePackageDownloadOperation newPackageDownloadOperation(); - // Install operation - - /** - * Creates a new {@link DevicePackageInstallRequest} - * - * @return the newly created {@link DevicePackageInstallRequest} - * @since 1.0.0 - */ - DevicePackageInstallRequest newPackageInstallRequest(); - - /** - * Creates a new {@link DevicePackageInstallOptions} - * - * @return the newly created {@link DevicePackageInstallOptions} - * @since 1.1.0 - */ - DevicePackageInstallOptions newPackageInstallOptions(); - - /** - * Instantiates a new {@link DevicePackageInstallOperation}. - * - * @return The newly instantiated {@link DevicePackageInstallOperation}. - * @since 1.5.0 - */ - DevicePackageInstallOperation newPackageInstallOperation(); - // Uninstall operation - - /** - * Creates a new {@link DevicePackageUninstallRequest} - * - * @return the newly created {@link DevicePackageUninstallRequest} - * @since 1.0.0 - */ - DevicePackageUninstallRequest newPackageUninstallRequest(); - - /** - * Creates a new {@link DevicePackageUninstallOptions} - * - * @return the newly created {@link DevicePackageUninstallOptions} - * @since 1.1.0 - */ - DevicePackageUninstallOptions newPackageUninstallOptions(); - - /** - * Instantiates a new {@link DevicePackageUninstallOperation}. - * - * @return The newly instantiated {@link DevicePackageUninstallOperation}. - * @since 1.5.0 - */ - DevicePackageUninstallOperation newPackageUninstallOperation(); -} diff --git a/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/DevicePackage.java b/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/DevicePackage.java index 037ded2f00b..efe15fe3401 100644 --- a/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/DevicePackage.java +++ b/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/DevicePackage.java @@ -12,12 +12,13 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.packages.model; +import java.util.Date; + import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; -import java.util.Date; /** * {@link DevicePackage} definition. @@ -26,8 +27,13 @@ */ @XmlRootElement(name = "devicePackage") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = DevicePackageXmlRegistry.class, factoryMethod = "newDevicePackage") -public interface DevicePackage { +@XmlType +public class DevicePackage { + + private String name; + private String version; + private DevicePackageBundleInfos bundleInfos; + private Date installDate; /** * Gets the name. @@ -36,15 +42,20 @@ public interface DevicePackage { * @since 1.0.0 */ @XmlElement(name = "name") - String getName(); + public String getName() { + return name; + } /** * Sets the name. * - * @param name The name. + * @param name + * The name. * @since 1.0.0 */ - void setName(String name); + public void setName(String name) { + this.name = name; + } /** * Gets the version. @@ -53,15 +64,20 @@ public interface DevicePackage { * @since 1.0.0 */ @XmlElement(name = "version") - String getVersion(); + public String getVersion() { + return version; + } /** * Sets the version. * - * @param version The version. + * @param version + * The version. * @since 1.0.0 */ - void setVersion(String version); + public void setVersion(String version) { + this.version = version; + } /** * Gets the {@link DevicePackageBundleInfos}. @@ -70,15 +86,24 @@ public interface DevicePackage { * @since 1.0.0 */ @XmlElement(name = "bundleInfos") - DevicePackageBundleInfos getBundleInfos(); + public DevicePackageBundleInfos getBundleInfos() { + if (bundleInfos == null) { + bundleInfos = new DevicePackageBundleInfos(); + } + + return bundleInfos; + } /** * Sets the {@link DevicePackageBundleInfos}. * - * @param bundleInfos The {@link DevicePackageBundleInfos}. + * @param bundleInfos + * The {@link DevicePackageBundleInfos}. * @since 1.0.0 */ - void setBundleInfos(DevicePackageBundleInfos bundleInfos); + public void setBundleInfos(DevicePackageBundleInfos bundleInfos) { + this.bundleInfos = bundleInfos; + } /** * Gets the installation date. @@ -87,13 +112,18 @@ public interface DevicePackage { * @since 1.0.0 */ @XmlElement(name = "installDate") - Date getInstallDate(); + public Date getInstallDate() { + return installDate; + } /** * Sets the installation date. * - * @param installDate The installation date. + * @param installDate + * The installation date. * @since 1.0.0 */ - void setInstallDate(Date installDate); + public void setInstallDate(Date installDate) { + this.installDate = installDate; + } } diff --git a/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/DevicePackageBundleInfo.java b/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/DevicePackageBundleInfo.java index 639a90d89d1..6ed39a2c99a 100644 --- a/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/DevicePackageBundleInfo.java +++ b/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/DevicePackageBundleInfo.java @@ -25,8 +25,11 @@ */ @XmlRootElement(name = "bundleInfo") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = DevicePackageXmlRegistry.class, factoryMethod = "newDevicePackageBundleInfo") -public interface DevicePackageBundleInfo { +@XmlType +public class DevicePackageBundleInfo { + + public String name; + public String version; /** * Gets the name. @@ -35,15 +38,20 @@ public interface DevicePackageBundleInfo { * @since 1.0.0 */ @XmlElement(name = "name") - String getName(); + public String getName() { + return name; + } /** * Sets the name. * - * @param name The name. + * @param name + * The name. * @since 1.0.0 */ - void setName(String name); + public void setName(String name) { + this.name = name; + } /** * Gets the version. @@ -52,13 +60,19 @@ public interface DevicePackageBundleInfo { * @since 1.0.0 */ @XmlElement(name = "version") - String getVersion(); + public String getVersion() { + return version; + } /** * Sets the version. * - * @param version The version. + * @param version + * The version. * @since 1.0.0 */ - void setVersion(String version); + public void setVersion(String version) { + this.version = version; + } + } diff --git a/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/DevicePackageBundleInfos.java b/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/DevicePackageBundleInfos.java index eda213f8315..37736c709be 100644 --- a/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/DevicePackageBundleInfos.java +++ b/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/DevicePackageBundleInfos.java @@ -13,12 +13,14 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.packages.model; +import java.util.ArrayList; +import java.util.List; + import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; -import java.util.List; /** * {@link DevicePackageBundleInfos} implementation. @@ -27,8 +29,10 @@ */ @XmlRootElement(name = "bundleInfos") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = DevicePackageXmlRegistry.class, factoryMethod = "newDevicePackageBundleInfos") -public interface DevicePackageBundleInfos { +@XmlType +public class DevicePackageBundleInfos { + + List bundleInfos; /** * Gets the {@link DevicePackageBundleInfo} {@link List}. @@ -37,5 +41,10 @@ public interface DevicePackageBundleInfos { * @since 1.0.0 */ @XmlElement(name = "bundleInfo") - List getBundlesInfos(); + public List getBundlesInfos() { + if (bundleInfos == null) { + bundleInfos = new ArrayList<>(); + } + return bundleInfos; + } } diff --git a/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/DevicePackageOptions.java b/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/DevicePackageOptions.java index f6372608273..e7213a50533 100644 --- a/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/DevicePackageOptions.java +++ b/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/DevicePackageOptions.java @@ -19,7 +19,9 @@ * * @since 1.1.0 */ -public interface DevicePackageOptions { +public abstract class DevicePackageOptions { + + private Long timeout; /** * The {@link DeviceManagementOperation} timeout. @@ -27,13 +29,18 @@ public interface DevicePackageOptions { * @return The {@link DeviceManagementOperation} timeout. * @since 1.1.0 */ - Long getTimeout(); + public Long getTimeout() { + return timeout; + } /** * Sets the {@link DeviceManagementOperation} timeout. * - * @param timeout The {@link DeviceManagementOperation} timeout. + * @param timeout + * The {@link DeviceManagementOperation} timeout. * @since 1.1.0 */ - void setTimeout(Long timeout); + public void setTimeout(Long timeout) { + this.timeout = timeout; + } } diff --git a/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/DevicePackageXmlRegistry.java b/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/DevicePackageXmlRegistry.java deleted file mode 100644 index 11b81d2b41a..00000000000 --- a/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/DevicePackageXmlRegistry.java +++ /dev/null @@ -1,134 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.packages.model; - -import org.eclipse.kapua.locator.KapuaLocator; -import org.eclipse.kapua.service.device.management.packages.DevicePackageFactory; -import org.eclipse.kapua.service.device.management.packages.model.download.AdvancedPackageDownloadOptions; -import org.eclipse.kapua.service.device.management.packages.model.download.DevicePackageDownloadOperation; -import org.eclipse.kapua.service.device.management.packages.model.download.DevicePackageDownloadRequest; -import org.eclipse.kapua.service.device.management.packages.model.install.DevicePackageInstallOperation; -import org.eclipse.kapua.service.device.management.packages.model.uninstall.DevicePackageUninstallOperation; -import org.eclipse.kapua.service.device.management.packages.model.uninstall.DevicePackageUninstallRequest; - -import javax.xml.bind.annotation.XmlRegistry; - -/** - * {@link DevicePackageXmlRegistry} class. - * - * @since 1.0.0 - */ -@XmlRegistry -public class DevicePackageXmlRegistry { - - private final DevicePackageFactory devicePackageFactory = KapuaLocator.getInstance().getFactory(DevicePackageFactory.class); - - /** - * Creates a new device package instance - * - * @return - * @since 1.0.0 - */ - public DevicePackage newDevicePackage() { - return devicePackageFactory.newDeviceDeploymentPackage(); - } - - /** - * Creates a new device packages instance - * - * @return - * @since 1.0.0 - */ - public DevicePackages newDevicePackages() { - return devicePackageFactory.newDeviceDeploymentPackages(); - } - - /** - * Creates a new device package bundle information instance - * - * @return - * @since 1.0.0 - */ - public DevicePackageBundleInfo newDevicePackageBundleInfo() { - return devicePackageFactory.newDevicePackageBundleInfo(); - } - - /** - * Creates a new device package bundle informations instance - * - * @return - * @since 1.0.0 - */ - public DevicePackageBundleInfos newDevicePackageBundleInfos() { - return devicePackageFactory.newDevicePackageBundleInfos(); - } - - /** - * Creates a new device package download request instance - * - * @return - */ - public DevicePackageDownloadRequest newDevicePackageDownloadRequest() { - return devicePackageFactory.newPackageDownloadRequest(); - } - - /** - * Creates a new device package download request instance - * - * @return - * @since 1.1.0 - */ - public AdvancedPackageDownloadOptions newAdvancedPackageDownloadOptions() { - return devicePackageFactory.newAdvancedPackageDownloadOptions(); - } - - /** - * Instantiates a new {@link DevicePackageDownloadOperation}. - * - * @return The newly instantiated {@link DevicePackageDownloadOperation}. - * @since 1.5.0 - */ - public DevicePackageDownloadOperation newDevicePackageDownloadOperation() { - return devicePackageFactory.newPackageDownloadOperation(); - } - - /** - * Instantiates a new {@link DevicePackageInstallOperation}. - * - * @return The newly instantiated {@link DevicePackageInstallOperation}. - * @since 1.5.0 - */ - public DevicePackageInstallOperation newDevicePackageInstallOperation() { - return devicePackageFactory.newPackageInstallOperation(); - } - - /** - * Creates a new device package uninstall request instance - * - * @return - * @since 1.0.0 - */ - public DevicePackageUninstallRequest newDevicePackageUninstallRequest() { - return devicePackageFactory.newPackageUninstallRequest(); - } - - /** - * Instantiates a new {@link DevicePackageUninstallOperation}. - * - * @return The newly instantiated {@link DevicePackageUninstallOperation}. - * @since 1.5.0 - */ - public DevicePackageUninstallOperation newDevicePackageUninstallOperation() { - return devicePackageFactory.newPackageUninstallOperation(); - } -} diff --git a/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/DevicePackages.java b/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/DevicePackages.java index 276ef765984..c703e9fdc32 100644 --- a/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/DevicePackages.java +++ b/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/DevicePackages.java @@ -13,14 +13,16 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.packages.model; -import org.eclipse.kapua.KapuaSerializable; +import java.util.ArrayList; +import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; -import java.util.List; + +import org.eclipse.kapua.KapuaSerializable; /** * {@link DevicePackages} definition. @@ -29,8 +31,12 @@ */ @XmlRootElement(name = "devicePackages") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = DevicePackageXmlRegistry.class, factoryMethod = "newDevicePackages") -public interface DevicePackages extends KapuaSerializable { +@XmlType +public class DevicePackages implements KapuaSerializable { + + private static final long serialVersionUID = 2450088980495469562L; + + public List deploymentPackages; /** * Gets the {@link DevicePackage} {@link List} @@ -39,5 +45,11 @@ public interface DevicePackages extends KapuaSerializable { * @since 1.0.0 */ @XmlElement(name = "devicePackage") - List getPackages(); + public List getPackages() { + if (deploymentPackages == null) { + deploymentPackages = new ArrayList<>(); + } + + return deploymentPackages; + } } diff --git a/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/download/AdvancedPackageDownloadOptions.java b/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/download/AdvancedPackageDownloadOptions.java index 989445165a6..9c38087ae86 100644 --- a/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/download/AdvancedPackageDownloadOptions.java +++ b/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/download/AdvancedPackageDownloadOptions.java @@ -12,8 +12,6 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.packages.model.download; -import org.eclipse.kapua.service.device.management.packages.model.DevicePackageXmlRegistry; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; @@ -25,8 +23,41 @@ * @since 1.1.0 */ @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = DevicePackageXmlRegistry.class, factoryMethod = "newAdvancedPackageDownloadOptions") -public interface AdvancedPackageDownloadOptions { +@XmlType +public class AdvancedPackageDownloadOptions { + + private Boolean restart; + private Integer blockSize; + private Integer blockDelay; + private Integer blockTimeout; + private Integer notifyBlockSize; + private String installVerifierURI; + + /** + * Constructor. + * + * @since 1.1.0 + */ + public AdvancedPackageDownloadOptions() { + } + + /** + * Clone Constructor. + * + * @param advancedPackageDownloadOptions + * The {@link AdvancedPackageDownloadOptions} to clone. + * @since 1.1.0 + */ + public AdvancedPackageDownloadOptions(AdvancedPackageDownloadOptions advancedPackageDownloadOptions) { + super(); + + setRestart(advancedPackageDownloadOptions.getRestart()); + setBlockSize(advancedPackageDownloadOptions.getBlockSize()); + setBlockDelay(advancedPackageDownloadOptions.getBlockDelay()); + setBlockTimeout(advancedPackageDownloadOptions.getBlockTimeout()); + setNotifyBlockSize(advancedPackageDownloadOptions.getNotifyBlockSize()); + setInstallVerifierURI(advancedPackageDownloadOptions.getInstallVerifierURI()); + } /** * Gets whether or not to restart the download from the beginning. @@ -34,15 +65,20 @@ public interface AdvancedPackageDownloadOptions { * @return {@code true} if the download must be restarted from the beginning, {@code false} otherwise. * @since 1.2.0 */ - Boolean getRestart(); + public Boolean getRestart() { + return restart; + } /** * Sets whether or not to restart the download from the beginning. * - * @param restart {@code true} if the download must be restarted from the beginning, {@code false} otherwise. + * @param restart + * {@code true} if the download must be restarted from the beginning, {@code false} otherwise. * @since 1.2.0 */ - void setRestart(Boolean restart); + public void setRestart(Boolean restart) { + this.restart = restart; + } /** * Gets the size in {@code Byte}s of the blocks to transfer from the URI. @@ -51,15 +87,20 @@ public interface AdvancedPackageDownloadOptions { * @since 1.1.0 */ @XmlElement(name = "blockSize") - Integer getBlockSize(); + public Integer getBlockSize() { + return blockSize; + } /** * Sets the size in {@code Byte}s of the blocks to transfer from the URI. * - * @param blockSize The size in {@code Byte}s of the blocks to transfer from the URI. + * @param blockSize + * The size in {@code Byte}s of the blocks to transfer from the URI. * @since 1.1.0 */ - void setBlockSize(Integer blockSize); + public void setBlockSize(Integer blockSize) { + this.blockSize = blockSize; + } /** * Gets the delay between each block transfer from the URI. @@ -68,15 +109,20 @@ public interface AdvancedPackageDownloadOptions { * @since 1.1.0 */ @XmlElement(name = "blockDelay") - Integer getBlockDelay(); + public Integer getBlockDelay() { + return blockDelay; + } /** * Sets the delay between each block transfer from the URI. * - * @param blockDelay The delay between each block transfer from the URI. + * @param blockDelay + * The delay between each block transfer from the URI. * @since 1.1.0 */ - void setBlockDelay(Integer blockDelay); + public void setBlockDelay(Integer blockDelay) { + this.blockDelay = blockDelay; + } /** * Gets the timeout for transferring a block from the URI. @@ -85,32 +131,44 @@ public interface AdvancedPackageDownloadOptions { * @since 1.1.0 */ @XmlElement(name = "blockTimeout") - Integer getBlockTimeout(); + public Integer getBlockTimeout() { + return blockTimeout; + } /** * Sets the timeout for transferring a block from the URI. * - * @param blockTimeout The timeout for transferring a block from the URI. + * @param blockTimeout + * The timeout for transferring a block from the URI. * @since 1.1.0 */ - void setBlockTimeout(Integer blockTimeout); + public void setBlockTimeout(Integer blockTimeout) { + this.blockTimeout = blockTimeout; + } /** - * Gets the size in {@code Byte}s of the blocks to be transfer to cause a {@link org.eclipse.kapua.service.device.management.registry.operation.notification.ManagementOperationNotification} to be sent from the {@link org.eclipse.kapua.service.device.registry.Device}. + * Gets the size in {@code Byte}s of the blocks to be transfer to cause a {@link org.eclipse.kapua.service.device.management.registry.operation.notification.ManagementOperationNotification} to be + * sent from the {@link org.eclipse.kapua.service.device.registry.Device}. * * @return The size in {@code Byte}s of the blocks to be transfer to cause a {@link org.eclipse.kapua.service.device.management.registry.operation.notification.ManagementOperationNotification}. * @since 1.1.0 */ @XmlElement(name = "notifyBlockSize") - Integer getNotifyBlockSize(); + public Integer getNotifyBlockSize() { + return notifyBlockSize; + } /** - * Sets the size in {@code Byte}s of the blocks to be transfer to cause a {@link org.eclipse.kapua.service.device.management.registry.operation.notification.ManagementOperationNotification} to be sent from the {@link org.eclipse.kapua.service.device.registry.Device}. + * Sets the size in {@code Byte}s of the blocks to be transfer to cause a {@link org.eclipse.kapua.service.device.management.registry.operation.notification.ManagementOperationNotification} to be + * sent from the {@link org.eclipse.kapua.service.device.registry.Device}. * - * @param notifyBlockSize The size in {@code Byte}s of the blocks to be transfer to cause a {@link org.eclipse.kapua.service.device.management.registry.operation.notification.ManagementOperationNotification}. + * @param notifyBlockSize + * The size in {@code Byte}s of the blocks to be transfer to cause a {@link org.eclipse.kapua.service.device.management.registry.operation.notification.ManagementOperationNotification}. * @since 1.1.0 */ - void setNotifyBlockSize(Integer notifyBlockSize); + public void setNotifyBlockSize(Integer notifyBlockSize) { + this.notifyBlockSize = notifyBlockSize; + } /** * Gets the URI for the executable shell script to verify the installing of the downloaded file. @@ -119,13 +177,18 @@ public interface AdvancedPackageDownloadOptions { * @since 1.1.0 */ @XmlElement(name = "installVerifierURI") - String getInstallVerifierURI(); + public String getInstallVerifierURI() { + return installVerifierURI; + } /** * Sets the URI for the executable shell script to verify the installing of the downloaded file. * - * @param installVerifiesURI The URI for the executable shell script to verify the installing of the downloaded file. + * @param installVerifiesURI + * The URI for the executable shell script to verify the installing of the downloaded file. * @since 1.1.0 */ - void setInstallVerifierURI(String installVerifiesURI); + public void setInstallVerifierURI(String installVerifiesURI) { + this.installVerifierURI = installVerifiesURI; + } } diff --git a/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/download/DevicePackageDownloadOperation.java b/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/download/DevicePackageDownloadOperation.java index 2f874f1141e..6f893f294ce 100644 --- a/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/download/DevicePackageDownloadOperation.java +++ b/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/download/DevicePackageDownloadOperation.java @@ -12,10 +12,6 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.packages.model.download; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.model.id.KapuaIdAdapter; -import org.eclipse.kapua.service.device.management.packages.model.DevicePackageXmlRegistry; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; @@ -23,6 +19,9 @@ import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; +import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.id.KapuaIdAdapter; + /** * Device download package operation entity definition. * @@ -30,8 +29,13 @@ */ @XmlRootElement(name = "packageDownloadOperation") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = DevicePackageXmlRegistry.class, factoryMethod = "newDevicePackageDownloadOperation") -public interface DevicePackageDownloadOperation { +@XmlType +public class DevicePackageDownloadOperation { + + private KapuaId id; + private Integer size; + private Integer progress; + private DevicePackageDownloadStatus status; /** * Get the download package identifier @@ -40,14 +44,18 @@ public interface DevicePackageDownloadOperation { */ @XmlElement(name = "id") @XmlJavaTypeAdapter(KapuaIdAdapter.class) - KapuaId getId(); + public KapuaId getId() { + return id; + } /** * Set the download package identifier * * @param id */ - void setId(KapuaId id); + public void setId(KapuaId id) { + this.id = id; + } /** * Get the package size @@ -55,14 +63,18 @@ public interface DevicePackageDownloadOperation { * @return */ @XmlElement(name = "size") - Integer getSize(); + public Integer getSize() { + return size; + } /** * Set the package size * * @param downloadSize */ - void setSize(Integer downloadSize); + public void setSize(Integer downloadSize) { + this.size = downloadSize; + } /** * Get the download progress @@ -70,14 +82,18 @@ public interface DevicePackageDownloadOperation { * @return */ @XmlElement(name = "progress") - Integer getProgress(); + public Integer getProgress() { + return progress; + } /** * Set the download progress * * @param downloadProgress */ - void setProgress(Integer downloadProgress); + public void setProgress(Integer downloadProgress) { + this.progress = downloadProgress; + } /** * Get the download status @@ -85,13 +101,17 @@ public interface DevicePackageDownloadOperation { * @return */ @XmlElement(name = "status") - DevicePackageDownloadStatus getStatus(); + public DevicePackageDownloadStatus getStatus() { + return status; + } /** * Set the download status * * @param status */ - void setStatus(DevicePackageDownloadStatus status); + public void setStatus(DevicePackageDownloadStatus status) { + this.status = status; + } } diff --git a/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/download/DevicePackageDownloadOptions.java b/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/download/DevicePackageDownloadOptions.java index cd7f3cdeeb3..ab38d2c13ae 100644 --- a/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/download/DevicePackageDownloadOptions.java +++ b/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/download/DevicePackageDownloadOptions.java @@ -19,5 +19,6 @@ * * @since 1.1.0 */ -public interface DevicePackageDownloadOptions extends DevicePackageOptions { +public class DevicePackageDownloadOptions extends DevicePackageOptions { + } diff --git a/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/download/DevicePackageDownloadRequest.java b/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/download/DevicePackageDownloadRequest.java index 3a20b13fa61..9d0be8bc06c 100644 --- a/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/download/DevicePackageDownloadRequest.java +++ b/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/download/DevicePackageDownloadRequest.java @@ -12,15 +12,15 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.packages.model.download; -import org.eclipse.kapua.service.device.management.packages.model.DevicePackageXmlRegistry; -import org.eclipse.kapua.service.device.management.packages.model.FileType; +import java.net.URI; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; -import java.net.URI; + +import org.eclipse.kapua.service.device.management.packages.model.FileType; /** * {@link DevicePackageDownloadRequest} definition. @@ -31,8 +31,25 @@ */ @XmlRootElement(name = "downloadRequest") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = DevicePackageXmlRegistry.class, factoryMethod = "newDevicePackageDownloadRequest") -public interface DevicePackageDownloadRequest { +@XmlType +public class DevicePackageDownloadRequest { + + private URI uri; + private String name; + private String version; + + private String username; + private String password; + + private String fileHash; + private FileType fileType; + + private Boolean install; + + private Boolean reboot; + private Integer rebootDelay; + + private AdvancedPackageDownloadOptions advancedOptions; /** * Gets the download URI of the file. @@ -41,15 +58,20 @@ public interface DevicePackageDownloadRequest { * @since 1.0.0 */ @XmlElement(name = "uri") - URI getUri(); + public URI getUri() { + return uri; + } /** * Sets the download URI of the file. * - * @param uri The download URI of the file. + * @param uri + * The download URI of the file. * @since 1.0.0 */ - void setUri(URI uri); + public void setUri(URI uri) { + this.uri = uri; + } /** * Gets the package name. @@ -58,15 +80,20 @@ public interface DevicePackageDownloadRequest { * @since 1.0.0 */ @XmlElement(name = "name") - String getName(); + public String getName() { + return name; + } /** * Sets the package name. * - * @param name The package name. + * @param name + * The package name. * @since 1.0.0 */ - void setName(String name); + public void setName(String name) { + this.name = name; + } /** * Gets the package version. @@ -75,15 +102,20 @@ public interface DevicePackageDownloadRequest { * @since 1.0.0 */ @XmlElement(name = "version") - String getVersion(); + public String getVersion() { + return version; + } /** * Set the package version. * - * @param version The package version. + * @param version + * The package version. * @since 1.0.0 */ - void setVersion(String version); + public void setVersion(String version) { + this.version = version; + } /** * Gets the username to provide as a credential when accessing the URI. @@ -91,15 +123,20 @@ public interface DevicePackageDownloadRequest { * @return The username to provide as a credential when accessing the URI. * @since 1.1.0 */ - String getUsername(); + public String getUsername() { + return username; + } /** * Sets the username to provide as a credential when accessing the URI. * - * @param username The username to provide as a credential when accessing the URI. + * @param username + * The username to provide as a credential when accessing the URI. * @since 1.1.0 */ - void setUsername(String username); + public void setUsername(String username) { + this.username = username; + } /** * Gets the password to provide as a credential when accessing the URI. @@ -107,37 +144,46 @@ public interface DevicePackageDownloadRequest { * @return The password to provide as a credential when accessing the URI. * @since 1.1.0 */ - String getPassword(); + public String getPassword() { + return password; + } /** * Sets the password to provide as a credential when accessing the URI. * - * @param password The password to provide as a credential when accessing the URI. + * @param password + * The password to provide as a credential when accessing the URI. * @since 1.1.0 */ - void setPassword(String password); + public void setPassword(String password) { + this.password = password; + } /** * Gets the file hash to verify the downloaded file. *

        * It must be specifies as {@code {HASH_ALGORITHM}:{HASH_VALUE}} *

        - * Example: - * MD5:46cbc7f212b94187cb6480fe9429a89c + * Example: MD5:46cbc7f212b94187cb6480fe9429a89c * * @return The file hash to verify the downloaded file. * @since 1.1.0 */ - String getFileHash(); + public String getFileHash() { + return fileHash; + } /** * Sets the file hash to verify the downloaded file. * - * @param fileHash The file hash to verify the downloaded file. + * @param fileHash + * The file hash to verify the downloaded file. * @see DevicePackageDownloadRequest#getFileHash() * @since 1.1.0 */ - void setFileHash(String fileHash); + public void setFileHash(String fileHash) { + this.fileHash = fileHash; + } /** * Gets the {@link FileType} of the target file to download. @@ -145,15 +191,20 @@ public interface DevicePackageDownloadRequest { * @return The {@link FileType} of the target file to download. * @since 1.1.0 */ - FileType getFileType(); + public FileType getFileType() { + return fileType; + } /** * Sets the {@link FileType} of the target file to download. * - * @param fileType The {@link FileType} of the target file to download. + * @param fileType + * The {@link FileType} of the target file to download. * @since 1.1.0 */ - void setFileType(FileType fileType); + public void setFileType(FileType fileType) { + this.fileType = fileType; + } /** * Gets whether or not install the file right after it has been downloaded. @@ -162,15 +213,20 @@ public interface DevicePackageDownloadRequest { * @since 1.0.0 */ @XmlElement(name = "install") - Boolean getInstall(); + public Boolean getInstall() { + return install; + } /** * Sets whether or not install the file right after it has been downloaded. * - * @param install Whether or not install the file right after it has been downloaded. + * @param install + * Whether or not install the file right after it has been downloaded. * @since 1.0.0 */ - void setInstall(Boolean install); + public void setInstall(Boolean install) { + this.install = install; + } /** * Gets whether or not reboot the device after the operation has been completed. @@ -179,15 +235,20 @@ public interface DevicePackageDownloadRequest { * @since 1.0.0 */ @XmlElement(name = "reboot") - Boolean getReboot(); + public Boolean getReboot() { + return reboot; + } /** * Sets whether or not reboot the device after the operation has been completed. * - * @param reboot Whether or not reboot the device after the operation has been completed. + * @param reboot + * Whether or not reboot the device after the operation has been completed. * @since 1.0.0 */ - void setReboot(Boolean reboot); + public void setReboot(Boolean reboot) { + this.reboot = reboot; + } /** * Gets the delay after which the device is rebooted when the operation has been completed. @@ -196,15 +257,20 @@ public interface DevicePackageDownloadRequest { * @since 1.0.0 */ @XmlElement(name = "rebootDelay") - Integer getRebootDelay(); + public Integer getRebootDelay() { + return rebootDelay; + } /** * Sets the delay after which the device is rebooted when the operation has been completed. * - * @param rebootDelay The delay after which the device is rebooted when the operation has been completed. + * @param rebootDelay + * The delay after which the device is rebooted when the operation has been completed. * @since 1.0.0 */ - void setRebootDelay(Integer rebootDelay); + public void setRebootDelay(Integer rebootDelay) { + this.rebootDelay = rebootDelay; + } /** * Gets the {@link AdvancedPackageDownloadOptions} to tune the download operation. @@ -213,13 +279,22 @@ public interface DevicePackageDownloadRequest { * @since 1.1.0 */ @XmlElement(name = "advancedOptions") - AdvancedPackageDownloadOptions getAdvancedOptions(); + public AdvancedPackageDownloadOptions getAdvancedOptions() { + if (advancedOptions == null) { + advancedOptions = new AdvancedPackageDownloadOptions(); + } + + return advancedOptions; + } /** * Sets the {@link AdvancedPackageDownloadOptions} to tune the download operation. * - * @param advancedOptions The {@link AdvancedPackageDownloadOptions} to tune the download operation. + * @param advancedOptions + * The {@link AdvancedPackageDownloadOptions} to tune the download operation. * @since 1.1.0 */ - void setAdvancedOptions(AdvancedPackageDownloadOptions advancedOptions); + public void setAdvancedOptions(AdvancedPackageDownloadOptions advancedOptions) { + this.advancedOptions = advancedOptions; + } } diff --git a/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/install/DevicePackageInstallOperation.java b/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/install/DevicePackageInstallOperation.java index 1912435d74b..0d3a5ac8c8c 100644 --- a/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/install/DevicePackageInstallOperation.java +++ b/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/install/DevicePackageInstallOperation.java @@ -12,10 +12,6 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.packages.model.install; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.model.id.KapuaIdAdapter; -import org.eclipse.kapua.service.device.management.packages.model.DevicePackageXmlRegistry; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; @@ -23,6 +19,9 @@ import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; +import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.id.KapuaIdAdapter; + /** * {@link DevicePackageInstallOperation} definition. * @@ -30,8 +29,13 @@ */ @XmlRootElement(name = "packageInstallOperation") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = DevicePackageXmlRegistry.class, factoryMethod = "newDevicePackageInstallOperation") -public interface DevicePackageInstallOperation { +@XmlType +public class DevicePackageInstallOperation { + + private KapuaId id; + private String name; + private String version; + private DevicePackageInstallStatus status; /** * Get the package identifier @@ -40,14 +44,18 @@ public interface DevicePackageInstallOperation { */ @XmlElement(name = "id") @XmlJavaTypeAdapter(KapuaIdAdapter.class) - KapuaId getId(); + public KapuaId getId() { + return id; + } /** * Set the package identifier * * @param id */ - void setId(KapuaId id); + public void setId(KapuaId id) { + this.id = id; + } /** * Get the package name @@ -55,14 +63,18 @@ public interface DevicePackageInstallOperation { * @return */ @XmlElement(name = "name") - String getName(); + public String getName() { + return name; + } /** * Set the package name * * @param packageName */ - void setName(String packageName); + public void setName(String packageName) { + this.name = packageName; + } /** * Get the package version @@ -70,14 +82,18 @@ public interface DevicePackageInstallOperation { * @return */ @XmlElement(name = "version") - String getVersion(); + public String getVersion() { + return version; + } /** * Set the package version * * @param version */ - void setVersion(String version); + public void setVersion(String version) { + this.version = version; + } /** * Get the package install status @@ -85,12 +101,17 @@ public interface DevicePackageInstallOperation { * @return */ @XmlElement(name = "status") - DevicePackageInstallStatus getStatus(); + public DevicePackageInstallStatus getStatus() { + return status; + } /** * Set the package install status * * @param status */ - void setStatus(DevicePackageInstallStatus status); + public void setStatus(DevicePackageInstallStatus status) { + this.status = status; + } + } diff --git a/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/install/DevicePackageInstallOptions.java b/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/install/DevicePackageInstallOptions.java index ca4f5815ecf..c2c122c342d 100644 --- a/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/install/DevicePackageInstallOptions.java +++ b/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/install/DevicePackageInstallOptions.java @@ -19,5 +19,6 @@ * * @since 1.1.0 */ -public interface DevicePackageInstallOptions extends DevicePackageOptions { +public class DevicePackageInstallOptions extends DevicePackageOptions { + } diff --git a/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/install/DevicePackageInstallRequest.java b/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/install/DevicePackageInstallRequest.java index 9911293de15..4821c9096d2 100644 --- a/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/install/DevicePackageInstallRequest.java +++ b/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/install/DevicePackageInstallRequest.java @@ -17,61 +17,83 @@ * * @since 1.0 */ -public interface DevicePackageInstallRequest { +public class DevicePackageInstallRequest { + + private String name; + private String version; + private Boolean reboot; + private Integer rebootDelay; /** * Get the package name * * @return */ - String getName(); + public String getName() { + return name; + } /** * Set the package name * * @param name */ - void setName(String name); + public void setName(String name) { + this.name = name; + } /** * Get the package version * * @return */ - String getVersion(); + public String getVersion() { + return version; + } /** * Set the package version * * @param version */ - void setVersion(String version); + public void setVersion(String version) { + this.version = version; + } /** * Get the device reboot flag * * @return */ - Boolean isReboot(); + public Boolean isReboot() { + return reboot; + } /** * Set the device reboot flag * * @param reboot */ - void setReboot(Boolean reboot); + public void setReboot(Boolean reboot) { + this.reboot = reboot; + } /** * Get the reboot delay * * @return */ - Integer getRebootDelay(); + public Integer getRebootDelay() { + return rebootDelay; + } /** * Set the reboot delay * * @param rebootDelay */ - void setRebootDelay(Integer rebootDelay); + public void setRebootDelay(Integer rebootDelay) { + this.rebootDelay = rebootDelay; + } + } diff --git a/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/uninstall/DevicePackageUninstallOperation.java b/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/uninstall/DevicePackageUninstallOperation.java index eb72ce0f767..2725c56c1e0 100644 --- a/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/uninstall/DevicePackageUninstallOperation.java +++ b/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/uninstall/DevicePackageUninstallOperation.java @@ -12,15 +12,14 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.packages.model.uninstall; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.device.management.packages.model.DevicePackageXmlRegistry; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; +import org.eclipse.kapua.model.id.KapuaId; + /** * {@link DevicePackageUninstallOperation} definition. * @@ -28,8 +27,13 @@ */ @XmlRootElement(name = "devicePackageUninstallOperation") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = DevicePackageXmlRegistry.class, factoryMethod = "newDevicePackageUninstallOperation") -public interface DevicePackageUninstallOperation { +@XmlType +public class DevicePackageUninstallOperation { + + private KapuaId id; + private String name; + private String version; + private DevicePackageUninstallStatus status; /** * Get the package identifier @@ -37,14 +41,18 @@ public interface DevicePackageUninstallOperation { * @return */ @XmlElement(name = "id") - KapuaId getId(); + public KapuaId getId() { + return id; + } /** * Set the package identifier * * @param id */ - void setId(KapuaId id); + public void setId(KapuaId id) { + this.id = id; + } /** * Get the package name @@ -52,14 +60,18 @@ public interface DevicePackageUninstallOperation { * @return */ @XmlElement(name = "name") - String getName(); + public String getName() { + return name; + } /** * Set the package name * * @param packageName */ - void setName(String packageName); + public void setName(String packageName) { + this.name = packageName; + } /** * Get the package version @@ -67,14 +79,18 @@ public interface DevicePackageUninstallOperation { * @return */ @XmlElement(name = "version") - String getVersion(); + public String getVersion() { + return version; + } /** * Set the package version * * @param version */ - void setVersion(String version); + public void setVersion(String version) { + this.version = version; + } /** * Get the package uninstall status @@ -82,12 +98,17 @@ public interface DevicePackageUninstallOperation { * @return */ @XmlElement(name = "status") - DevicePackageUninstallStatus getStatus(); + public DevicePackageUninstallStatus getStatus() { + return status; + } /** * Set the package uninstall status * * @param status */ - void setStatus(DevicePackageUninstallStatus status); + public void setStatus(DevicePackageUninstallStatus status) { + this.status = status; + } + } diff --git a/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/uninstall/DevicePackageUninstallOptions.java b/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/uninstall/DevicePackageUninstallOptions.java index 405b00e5b37..981ad7d383c 100644 --- a/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/uninstall/DevicePackageUninstallOptions.java +++ b/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/uninstall/DevicePackageUninstallOptions.java @@ -19,5 +19,6 @@ * * @since 1.1.0 */ -public interface DevicePackageUninstallOptions extends DevicePackageOptions { +public class DevicePackageUninstallOptions extends DevicePackageOptions { + } diff --git a/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/uninstall/DevicePackageUninstallRequest.java b/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/uninstall/DevicePackageUninstallRequest.java index 6e4cebf5dc0..fd546d84474 100644 --- a/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/uninstall/DevicePackageUninstallRequest.java +++ b/service/device/management/packages/api/src/main/java/org/eclipse/kapua/service/device/management/packages/model/uninstall/DevicePackageUninstallRequest.java @@ -12,8 +12,6 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.packages.model.uninstall; -import org.eclipse.kapua.service.device.management.packages.model.DevicePackageXmlRegistry; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; @@ -31,10 +29,14 @@ "name", "version", "reboot", - "rebootDelay" }, - factoryClass = DevicePackageXmlRegistry.class, - factoryMethod = "newDevicePackageUninstallRequest") -public interface DevicePackageUninstallRequest { + "rebootDelay" }) +public class DevicePackageUninstallRequest { + + public String name; + public String version; + + public Boolean reboot; + public Integer rebootDelay; /** * Get package name @@ -42,14 +44,18 @@ public interface DevicePackageUninstallRequest { * @return */ @XmlElement(name = "name") - String getName(); + public String getName() { + return name; + } /** * Set package name * * @param name */ - void setName(String name); + public void setName(String name) { + this.name = name; + } /** * Get package version @@ -57,14 +63,18 @@ public interface DevicePackageUninstallRequest { * @return */ @XmlElement(name = "version") - String getVersion(); + public String getVersion() { + return version; + } /** * Set package version * * @param version */ - void setVersion(String version); + public void setVersion(String version) { + this.version = version; + } /** * Get the device reboot flag @@ -72,14 +82,18 @@ public interface DevicePackageUninstallRequest { * @return */ @XmlElement(name = "reboot") - Boolean isReboot(); + public Boolean isReboot() { + return reboot; + } /** * Set the device reboot flag * * @param reboot */ - void setReboot(Boolean reboot); + public void setReboot(Boolean reboot) { + this.reboot = reboot; + } /** * Get the reboot delay @@ -87,12 +101,17 @@ public interface DevicePackageUninstallRequest { * @return */ @XmlElement(name = "rebootDelay") - Integer getRebootDelay(); + public Integer getRebootDelay() { + return rebootDelay; + } /** * Set the reboot delay * * @param rebootDelay */ - void setRebootDelay(Integer rebootDelay); + public void setRebootDelay(Integer rebootDelay) { + this.rebootDelay = rebootDelay; + } + } diff --git a/service/device/management/packages/internal/pom.xml b/service/device/management/packages/internal/pom.xml index 6c6ecdf1f37..4db8733a892 100644 --- a/service/device/management/packages/internal/pom.xml +++ b/service/device/management/packages/internal/pom.xml @@ -19,7 +19,7 @@ org.eclipse.kapua kapua-device-management-packages - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-device-management-packages-internal diff --git a/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/internal/DeviceManagementPackagesModule.java b/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/internal/DeviceManagementPackagesModule.java index a7b5dbf623d..c7994fc7d7d 100644 --- a/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/internal/DeviceManagementPackagesModule.java +++ b/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/internal/DeviceManagementPackagesModule.java @@ -20,8 +20,6 @@ import org.eclipse.kapua.commons.core.SimpleJaxbClassProvider; import org.eclipse.kapua.commons.jpa.KapuaJpaTxManagerFactory; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; -import org.eclipse.kapua.service.device.management.packages.DevicePackageFactory; import org.eclipse.kapua.service.device.management.packages.DevicePackageManagementService; import org.eclipse.kapua.service.device.management.packages.internal.setting.PackageManagementServiceSetting; import org.eclipse.kapua.service.device.management.packages.model.install.DevicePackageInstallRequest; @@ -38,7 +36,6 @@ public class DeviceManagementPackagesModule extends AbstractKapuaModule { @Override protected void configureModule() { - bind(DevicePackageFactory.class).to(DevicePackageFactoryImpl.class).in(Singleton.class); bind(PackageManagementServiceSetting.class).in(Singleton.class); final Multibinder jaxbClassProviderMultibinder = Multibinder.newSetBinder(binder(), JaxbClassProvider.class); jaxbClassProviderMultibinder.addBinding() @@ -52,26 +49,22 @@ protected void configureModule() { @Inject DevicePackageManagementService devicePackageManagementService( AuthorizationService authorizationService, - PermissionFactory permissionFactory, DeviceEventService deviceEventService, DeviceEventFactory deviceEventFactory, DeviceRegistryService deviceRegistryService, DeviceManagementOperationRegistryService deviceManagementOperationRegistryService, DeviceManagementOperationFactory deviceManagementOperationFactory, - DevicePackageFactory devicePackageFactory, KapuaJpaTxManagerFactory jpaTxManagerFactory, PackageManagementServiceSetting packageManagementServiceSetting ) { return new DevicePackageManagementServiceImpl( jpaTxManagerFactory.create("kapua-device_management_operation_registry"), authorizationService, - permissionFactory, deviceEventService, deviceEventFactory, deviceRegistryService, deviceManagementOperationRegistryService, deviceManagementOperationFactory, - devicePackageFactory, packageManagementServiceSetting ); } diff --git a/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/internal/DevicePackageFactoryImpl.java b/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/internal/DevicePackageFactoryImpl.java deleted file mode 100644 index 27ebc05a402..00000000000 --- a/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/internal/DevicePackageFactoryImpl.java +++ /dev/null @@ -1,127 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.packages.internal; - -import org.eclipse.kapua.service.device.management.packages.DevicePackageFactory; -import org.eclipse.kapua.service.device.management.packages.model.DevicePackage; -import org.eclipse.kapua.service.device.management.packages.model.DevicePackageBundleInfo; -import org.eclipse.kapua.service.device.management.packages.model.DevicePackageBundleInfos; -import org.eclipse.kapua.service.device.management.packages.model.DevicePackages; -import org.eclipse.kapua.service.device.management.packages.model.download.AdvancedPackageDownloadOptions; -import org.eclipse.kapua.service.device.management.packages.model.download.DevicePackageDownloadOperation; -import org.eclipse.kapua.service.device.management.packages.model.download.DevicePackageDownloadOptions; -import org.eclipse.kapua.service.device.management.packages.model.download.DevicePackageDownloadRequest; -import org.eclipse.kapua.service.device.management.packages.model.download.internal.AdvancedPackageDownloadOptionsImpl; -import org.eclipse.kapua.service.device.management.packages.model.download.internal.DevicePackageDownloadOperationImpl; -import org.eclipse.kapua.service.device.management.packages.model.download.internal.DevicePackageDownloadOptionsImpl; -import org.eclipse.kapua.service.device.management.packages.model.download.internal.DevicePackageDownloadRequestImpl; -import org.eclipse.kapua.service.device.management.packages.model.install.DevicePackageInstallOperation; -import org.eclipse.kapua.service.device.management.packages.model.install.DevicePackageInstallOptions; -import org.eclipse.kapua.service.device.management.packages.model.install.DevicePackageInstallRequest; -import org.eclipse.kapua.service.device.management.packages.model.install.internal.DevicePackageInstallOperationImpl; -import org.eclipse.kapua.service.device.management.packages.model.install.internal.DevicePackageInstallOptionsImpl; -import org.eclipse.kapua.service.device.management.packages.model.install.internal.DevicePackageInstallRequestImpl; -import org.eclipse.kapua.service.device.management.packages.model.internal.DevicePackageBundleInfoImpl; -import org.eclipse.kapua.service.device.management.packages.model.internal.DevicePackageBundleInfosImpl; -import org.eclipse.kapua.service.device.management.packages.model.internal.DevicePackageImpl; -import org.eclipse.kapua.service.device.management.packages.model.internal.DevicePackagesImpl; -import org.eclipse.kapua.service.device.management.packages.model.uninstall.DevicePackageUninstallOperation; -import org.eclipse.kapua.service.device.management.packages.model.uninstall.DevicePackageUninstallOptions; -import org.eclipse.kapua.service.device.management.packages.model.uninstall.DevicePackageUninstallRequest; -import org.eclipse.kapua.service.device.management.packages.model.uninstall.internal.DevicePackageUninstallOperationImpl; -import org.eclipse.kapua.service.device.management.packages.model.uninstall.internal.DevicePackageUninstallOptionsImpl; -import org.eclipse.kapua.service.device.management.packages.model.uninstall.internal.DevicePackageUninstallRequestImpl; - -import javax.inject.Singleton; - -/** - * {@link DevicePackageFactory} implementation. - * - * @since 1.0.0 - */ -@Singleton -public class DevicePackageFactoryImpl implements DevicePackageFactory { - - @Override - public DevicePackages newDeviceDeploymentPackages() { - return new DevicePackagesImpl(); - } - - @Override - public DevicePackage newDeviceDeploymentPackage() { - return new DevicePackageImpl(); - } - - @Override - public DevicePackageBundleInfo newDevicePackageBundleInfo() { - return new DevicePackageBundleInfoImpl(); - } - - @Override - public DevicePackageBundleInfos newDevicePackageBundleInfos() { - return new DevicePackageBundleInfosImpl(); - } - - // Download operation - @Override - public DevicePackageDownloadRequest newPackageDownloadRequest() { - return new DevicePackageDownloadRequestImpl(); - } - - @Override - public DevicePackageDownloadOperation newPackageDownloadOperation() { - return new DevicePackageDownloadOperationImpl(); - } - - @Override - public DevicePackageDownloadOptions newPackageDownloadOptions() { - return new DevicePackageDownloadOptionsImpl(); - } - - @Override - public AdvancedPackageDownloadOptions newAdvancedPackageDownloadOptions() { - return new AdvancedPackageDownloadOptionsImpl(); - } - - // Install operation - @Override - public DevicePackageInstallRequest newPackageInstallRequest() { - return new DevicePackageInstallRequestImpl(); - } - - @Override - public DevicePackageInstallOptions newPackageInstallOptions() { - return new DevicePackageInstallOptionsImpl(); - } - - @Override - public DevicePackageInstallOperation newPackageInstallOperation() { - return new DevicePackageInstallOperationImpl(); - } - - // Uninstall operation - @Override - public DevicePackageUninstallRequest newPackageUninstallRequest() { - return new DevicePackageUninstallRequestImpl(); - } - - @Override - public DevicePackageUninstallOptions newPackageUninstallOptions() { - return new DevicePackageUninstallOptionsImpl(); - } - - @Override - public DevicePackageUninstallOperation newPackageUninstallOperation() { - return new DevicePackageUninstallOperationImpl(); - } -} diff --git a/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/internal/DevicePackageManagementServiceImpl.java b/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/internal/DevicePackageManagementServiceImpl.java index c2916002560..3aa37d401c3 100644 --- a/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/internal/DevicePackageManagementServiceImpl.java +++ b/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/internal/DevicePackageManagementServiceImpl.java @@ -12,7 +12,15 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.packages.internal; -import com.google.common.base.MoreObjects; +import java.net.MalformedURLException; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Map; + +import javax.inject.Inject; +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.KapuaIllegalArgumentException; import org.eclipse.kapua.commons.model.domains.Domains; @@ -25,14 +33,13 @@ import org.eclipse.kapua.model.type.ObjectTypeConverter; import org.eclipse.kapua.model.type.ObjectValueConverter; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; +import org.eclipse.kapua.service.authorization.permission.Permission; import org.eclipse.kapua.service.device.management.commons.AbstractDeviceManagementTransactionalServiceImpl; import org.eclipse.kapua.service.device.management.commons.call.DeviceCallBuilder; import org.eclipse.kapua.service.device.management.message.KapuaMethod; import org.eclipse.kapua.service.device.management.message.notification.NotifyStatus; import org.eclipse.kapua.service.device.management.message.request.KapuaRequestMessage; import org.eclipse.kapua.service.device.management.message.response.KapuaResponseMessage; -import org.eclipse.kapua.service.device.management.packages.DevicePackageFactory; import org.eclipse.kapua.service.device.management.packages.DevicePackageManagementService; import org.eclipse.kapua.service.device.management.packages.internal.setting.PackageManagementServiceSetting; import org.eclipse.kapua.service.device.management.packages.internal.setting.PackageManagementServiceSettingKeys; @@ -48,7 +55,6 @@ import org.eclipse.kapua.service.device.management.packages.model.download.DevicePackageDownloadOperation; import org.eclipse.kapua.service.device.management.packages.model.download.DevicePackageDownloadOptions; import org.eclipse.kapua.service.device.management.packages.model.download.DevicePackageDownloadRequest; -import org.eclipse.kapua.service.device.management.packages.model.download.internal.DevicePackageDownloadOperationImpl; import org.eclipse.kapua.service.device.management.packages.model.install.DevicePackageInstallOperation; import org.eclipse.kapua.service.device.management.packages.model.install.DevicePackageInstallOptions; import org.eclipse.kapua.service.device.management.packages.model.install.DevicePackageInstallRequest; @@ -67,13 +73,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.inject.Inject; -import javax.inject.Singleton; -import java.net.MalformedURLException; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.Map; +import com.google.common.base.MoreObjects; /** * {@link DevicePackageManagementService} implementation. @@ -89,7 +89,6 @@ public class DevicePackageManagementServiceImpl extends AbstractDeviceManagement private final DeviceManagementOperationRegistryService deviceManagementOperationRegistryService; private final DeviceManagementOperationFactory deviceManagementOperationFactory; - private final DevicePackageFactory devicePackageFactory; private static final String SCOPE_ID = "scopeId"; private static final String DEVICE_ID = "deviceId"; @@ -98,23 +97,19 @@ public class DevicePackageManagementServiceImpl extends AbstractDeviceManagement public DevicePackageManagementServiceImpl( TxManager txManager, AuthorizationService authorizationService, - PermissionFactory permissionFactory, DeviceEventService deviceEventService, DeviceEventFactory deviceEventFactory, DeviceRegistryService deviceRegistryService, DeviceManagementOperationRegistryService deviceManagementOperationRegistryService, DeviceManagementOperationFactory deviceManagementOperationFactory, - DevicePackageFactory devicePackageFactory, PackageManagementServiceSetting packageManagementServiceSetting) { super(txManager, authorizationService, - permissionFactory, deviceEventService, deviceEventFactory, deviceRegistryService); this.deviceManagementOperationRegistryService = deviceManagementOperationRegistryService; this.deviceManagementOperationFactory = deviceManagementOperationFactory; - this.devicePackageFactory = devicePackageFactory; this.packageManagementServiceSetting = packageManagementServiceSetting; } // Installed @@ -125,7 +120,7 @@ public DevicePackages getInstalled(KapuaId scopeId, KapuaId deviceId, Long timeo ArgumentValidator.notNull(scopeId, SCOPE_ID); ArgumentValidator.notNull(deviceId, DEVICE_ID); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE_MANAGEMENT, Actions.read, scopeId)); + authorizationService.checkPermission(new Permission(Domains.DEVICE_MANAGEMENT, Actions.read, scopeId)); // Prepare the request PackageRequestChannel packageRequestChannel = new PackageRequestChannel(); packageRequestChannel.setAppName(PackageAppProperties.APP_NAME); @@ -161,13 +156,13 @@ public DevicePackages getInstalled(KapuaId scopeId, KapuaId deviceId, Long timeo // Create event createDeviceEvent(scopeId, deviceId, packageRequestMessage, responseMessage); // Check response - return checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getDevicePackages().orElse(devicePackageFactory.newDeviceDeploymentPackages())); + return checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getDevicePackages().orElse(new DevicePackages())); } // Download @Override public KapuaId downloadExec(KapuaId scopeId, KapuaId deviceId, DevicePackageDownloadRequest packageDownloadRequest, Long timeout) throws KapuaException { - DevicePackageDownloadOptions packageDownloadOptions = devicePackageFactory.newPackageDownloadOptions(); + DevicePackageDownloadOptions packageDownloadOptions = new DevicePackageDownloadOptions(); packageDownloadOptions.setTimeout(timeout); return downloadExec(scopeId, deviceId, packageDownloadRequest, packageDownloadOptions); @@ -191,7 +186,7 @@ public KapuaId downloadExec(KapuaId scopeId, KapuaId deviceId, DevicePackageDown verifyOverflowPackageFields(packageDownloadRequest); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE_MANAGEMENT, Actions.write, scopeId)); + authorizationService.checkPermission(new Permission(Domains.DEVICE_MANAGEMENT, Actions.write, scopeId)); // Generate requestId KapuaId operationId = new KapuaEid(IdGenerator.generate()); // Prepare the request @@ -220,10 +215,14 @@ public KapuaId downloadExec(KapuaId scopeId, KapuaId deviceId, DevicePackageDown AdvancedPackageDownloadOptions advancedOptions = packageDownloadRequest.getAdvancedOptions(); packageRequestPayload.setPackageDownloadRestart(advancedOptions.getRestart()); - packageRequestPayload.setPackageDownloadBlockSize(MoreObjects.firstNonNull(advancedOptions.getBlockSize(), packageManagementServiceSetting.getInt(PackageManagementServiceSettingKeys.PACKAGE_MANAGEMENT_SERVICE_SETTING_DOWDLOAD_DEFAULT_BLOCK_SIZE))); - packageRequestPayload.setPackageDownloadBlockDelay(MoreObjects.firstNonNull(advancedOptions.getBlockDelay(), packageManagementServiceSetting.getInt(PackageManagementServiceSettingKeys.PACKAGE_MANAGEMENT_SERVICE_SETTING_DOWDLOAD_DEFAULT_BLOCK_DELAY))); - packageRequestPayload.setPackageDownloadBlockTimeout(MoreObjects.firstNonNull(advancedOptions.getBlockTimeout(), packageManagementServiceSetting.getInt(PackageManagementServiceSettingKeys.PACKAGE_MANAGEMENT_SERVICE_SETTING_DOWDLOAD_DEFAULT_BLOCK_TIMEOUT))); - packageRequestPayload.setPackageDownloadBlockSize(MoreObjects.firstNonNull(advancedOptions.getNotifyBlockSize(), packageManagementServiceSetting.getInt(PackageManagementServiceSettingKeys.PACKAGE_MANAGEMENT_SERVICE_SETTING_DOWDLOAD_DEFAULT_NOTIFY_BLOCK_SIZE))); + packageRequestPayload.setPackageDownloadBlockSize(MoreObjects.firstNonNull(advancedOptions.getBlockSize(), + packageManagementServiceSetting.getInt(PackageManagementServiceSettingKeys.PACKAGE_MANAGEMENT_SERVICE_SETTING_DOWDLOAD_DEFAULT_BLOCK_SIZE))); + packageRequestPayload.setPackageDownloadBlockDelay(MoreObjects.firstNonNull(advancedOptions.getBlockDelay(), + packageManagementServiceSetting.getInt(PackageManagementServiceSettingKeys.PACKAGE_MANAGEMENT_SERVICE_SETTING_DOWDLOAD_DEFAULT_BLOCK_DELAY))); + packageRequestPayload.setPackageDownloadBlockTimeout(MoreObjects.firstNonNull(advancedOptions.getBlockTimeout(), + packageManagementServiceSetting.getInt(PackageManagementServiceSettingKeys.PACKAGE_MANAGEMENT_SERVICE_SETTING_DOWDLOAD_DEFAULT_BLOCK_TIMEOUT))); + packageRequestPayload.setPackageDownloadBlockSize(MoreObjects.firstNonNull(advancedOptions.getNotifyBlockSize(), + packageManagementServiceSetting.getInt(PackageManagementServiceSettingKeys.PACKAGE_MANAGEMENT_SERVICE_SETTING_DOWDLOAD_DEFAULT_NOTIFY_BLOCK_SIZE))); packageRequestPayload.setPackageDownloadInstallVerifierURI(advancedOptions.getInstallVerifierURI()); // Message @@ -271,7 +270,7 @@ public DevicePackageDownloadOperation downloadStatus(KapuaId scopeId, KapuaId de ArgumentValidator.notNull(scopeId, SCOPE_ID); ArgumentValidator.notNull(deviceId, DEVICE_ID); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE_MANAGEMENT, Actions.read, scopeId)); + authorizationService.checkPermission(new Permission(Domains.DEVICE_MANAGEMENT, Actions.read, scopeId)); // Prepare the request PackageRequestChannel packageRequestChannel = new PackageRequestChannel(); packageRequestChannel.setAppName(PackageAppProperties.APP_NAME); @@ -310,7 +309,7 @@ public DevicePackageDownloadOperation downloadStatus(KapuaId scopeId, KapuaId de return checkResponseAcceptedOrThrowError(responseMessage, () -> { PackageResponsePayload responsePayload = responseMessage.getPayload(); - DevicePackageDownloadOperation downloadOperation = new DevicePackageDownloadOperationImpl(); + DevicePackageDownloadOperation downloadOperation = new DevicePackageDownloadOperation(); downloadOperation.setId(responsePayload.getPackageDownloadOperationId()); downloadOperation.setStatus(responsePayload.getPackageDownloadOperationStatus()); downloadOperation.setSize(responsePayload.getPackageDownloadOperationSize()); @@ -326,7 +325,7 @@ public void downloadStop(KapuaId scopeId, KapuaId deviceId, Long timeout) throws ArgumentValidator.notNull(scopeId, SCOPE_ID); ArgumentValidator.notNull(deviceId, DEVICE_ID); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE_MANAGEMENT, Actions.write, scopeId)); + authorizationService.checkPermission(new Permission(Domains.DEVICE_MANAGEMENT, Actions.write, scopeId)); // Prepare the request PackageRequestChannel packageRequestChannel = new PackageRequestChannel(); packageRequestChannel.setAppName(PackageAppProperties.APP_NAME); @@ -368,7 +367,7 @@ public void downloadStop(KapuaId scopeId, KapuaId deviceId, Long timeout) throws @Override public KapuaId installExec(KapuaId scopeId, KapuaId deviceId, DevicePackageInstallRequest packageInstallRequest, Long timeout) throws KapuaException { - DevicePackageInstallOptions packageInstallOptions = devicePackageFactory.newPackageInstallOptions(); + DevicePackageInstallOptions packageInstallOptions = new DevicePackageInstallOptions(); packageInstallOptions.setTimeout(timeout); return installExec(scopeId, deviceId, packageInstallRequest, packageInstallOptions); @@ -382,7 +381,7 @@ public KapuaId installExec(KapuaId scopeId, KapuaId deviceId, DevicePackageInsta ArgumentValidator.notNull(deployInstallRequest, "deployInstallRequest"); ArgumentValidator.notNull(packageInstallOptions, "packageInstallOptions"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE_MANAGEMENT, Actions.write, scopeId)); + authorizationService.checkPermission(new Permission(Domains.DEVICE_MANAGEMENT, Actions.write, scopeId)); // Generate requestId KapuaId operationId = new KapuaEid(IdGenerator.generate()); // Prepare the request @@ -443,7 +442,7 @@ public DevicePackageInstallOperation installStatus(KapuaId scopeId, KapuaId devi ArgumentValidator.notNull(scopeId, SCOPE_ID); ArgumentValidator.notNull(deviceId, DEVICE_ID); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE_MANAGEMENT, Actions.read, scopeId)); + authorizationService.checkPermission(new Permission(Domains.DEVICE_MANAGEMENT, Actions.read, scopeId)); // Prepare the request PackageRequestChannel packageRequestChannel = new PackageRequestChannel(); packageRequestChannel.setAppName(PackageAppProperties.APP_NAME); @@ -479,27 +478,28 @@ public DevicePackageInstallOperation installStatus(KapuaId scopeId, KapuaId devi // Create event createDeviceEvent(scopeId, deviceId, packageRequestMessage, responseMessage); // Check response - return checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getDevicePackageInstallOperation().orElse(devicePackageFactory.newPackageInstallOperation())); + return checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getDevicePackageInstallOperation().orElse(new DevicePackageInstallOperation())); } // Uninstall @Override public KapuaId uninstallExec(KapuaId scopeId, KapuaId deviceId, DevicePackageUninstallRequest packageUninstallRequest, Long timeout) throws KapuaException { - DevicePackageUninstallOptions packageUninstallOptions = devicePackageFactory.newPackageUninstallOptions(); + DevicePackageUninstallOptions packageUninstallOptions = new DevicePackageUninstallOptions(); packageUninstallOptions.setTimeout(timeout); return uninstallExec(scopeId, deviceId, packageUninstallRequest, packageUninstallOptions); } @Override - public KapuaId uninstallExec(KapuaId scopeId, KapuaId deviceId, DevicePackageUninstallRequest packageUninstallRequest, DevicePackageUninstallOptions packageUninstallOptions) throws KapuaException { + public KapuaId uninstallExec(KapuaId scopeId, KapuaId deviceId, DevicePackageUninstallRequest packageUninstallRequest, DevicePackageUninstallOptions packageUninstallOptions) + throws KapuaException { // Argument Validation ArgumentValidator.notNull(scopeId, SCOPE_ID); ArgumentValidator.notNull(deviceId, DEVICE_ID); ArgumentValidator.notNull(packageUninstallRequest, "packageUninstallRequest"); ArgumentValidator.notNull(packageUninstallOptions, "packageUninstallOptions"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE_MANAGEMENT, Actions.write, scopeId)); + authorizationService.checkPermission(new Permission(Domains.DEVICE_MANAGEMENT, Actions.write, scopeId)); // Generate requestId KapuaId operationId = new KapuaEid(IdGenerator.generate()); // Prepare the request @@ -560,7 +560,7 @@ public DevicePackageUninstallOperation uninstallStatus(KapuaId scopeId, KapuaId ArgumentValidator.notNull(scopeId, SCOPE_ID); ArgumentValidator.notNull(deviceId, DEVICE_ID); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE_MANAGEMENT, Actions.read, scopeId)); + authorizationService.checkPermission(new Permission(Domains.DEVICE_MANAGEMENT, Actions.read, scopeId)); // Prepare the request PackageRequestChannel packageRequestChannel = new PackageRequestChannel(); packageRequestChannel.setAppName(PackageAppProperties.APP_NAME); @@ -596,7 +596,7 @@ public DevicePackageUninstallOperation uninstallStatus(KapuaId scopeId, KapuaId // Create event createDeviceEvent(scopeId, deviceId, packageRequestMessage, responseMessage); // Check response - return checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getDevicePackageUninstallOperation().orElse(devicePackageFactory.newPackageUninstallOperation())); + return checkResponseAcceptedOrThrowError(responseMessage, () -> responseMessage.getPayload().getDevicePackageUninstallOperation().orElse(new DevicePackageUninstallOperation())); } private void verifyOverflowPackageFields(DevicePackageDownloadRequest packageDownloadRequest) throws KapuaIllegalArgumentException { @@ -629,7 +629,7 @@ private List extractInputProperties(KapuaRequ // Device Management Operations protected KapuaId createManagementOperation(KapuaId scopeId, KapuaId deviceId, KapuaId operationId, KapuaRequestMessage requestMessage) throws KapuaException { - final DeviceManagementOperationCreator deviceManagementOperationCreator = deviceManagementOperationFactory.newCreator(scopeId); + final DeviceManagementOperationCreator deviceManagementOperationCreator = new DeviceManagementOperationCreator(scopeId); deviceManagementOperationCreator.setDeviceId(deviceId); deviceManagementOperationCreator.setOperationId(operationId); deviceManagementOperationCreator.setStartedOn(new Date()); diff --git a/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/model/download/internal/AdvancedPackageDownloadOptionsImpl.java b/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/model/download/internal/AdvancedPackageDownloadOptionsImpl.java deleted file mode 100644 index 9974d18459d..00000000000 --- a/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/model/download/internal/AdvancedPackageDownloadOptionsImpl.java +++ /dev/null @@ -1,119 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2019, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.packages.model.download.internal; - -import org.eclipse.kapua.service.device.management.packages.model.download.AdvancedPackageDownloadOptions; - -/** - * {@link AdvancedPackageDownloadOptions} implementation. - * - * @since 1.1.0 - */ -public class AdvancedPackageDownloadOptionsImpl implements AdvancedPackageDownloadOptions { - - private Boolean restart; - private Integer blockSize; - private Integer blockDelay; - private Integer blockTimeout; - private Integer notifyBlockSize; - private String installVerifierURI; - - /** - * Constructor. - * - * @since 1.1.0 - */ - public AdvancedPackageDownloadOptionsImpl() { - } - - /** - * Clone Constructor. - * - * @param advancedPackageDownloadOptions The {@link AdvancedPackageDownloadOptions} to clone. - * @since 1.1.0 - */ - public AdvancedPackageDownloadOptionsImpl(AdvancedPackageDownloadOptions advancedPackageDownloadOptions) { - super(); - - setRestart(advancedPackageDownloadOptions.getRestart()); - setBlockSize(advancedPackageDownloadOptions.getBlockSize()); - setBlockDelay(advancedPackageDownloadOptions.getBlockDelay()); - setBlockTimeout(advancedPackageDownloadOptions.getBlockTimeout()); - setNotifyBlockSize(advancedPackageDownloadOptions.getNotifyBlockSize()); - setInstallVerifierURI(advancedPackageDownloadOptions.getInstallVerifierURI()); - } - - @Override - public Boolean getRestart() { - return restart; - } - - @Override - public void setRestart(Boolean restart) { - this.restart = restart; - } - - @Override - public Integer getBlockSize() { - return blockSize; - } - - @Override - public void setBlockSize(Integer blockSize) { - this.blockSize = blockSize; - } - - @Override - public Integer getBlockDelay() { - return blockDelay; - } - - @Override - public void setBlockDelay(Integer blockDelay) { - this.blockDelay = blockDelay; - } - - @Override - public Integer getBlockTimeout() { - return blockTimeout; - } - - @Override - public void setBlockTimeout(Integer blockTimeout) { - this.blockTimeout = blockTimeout; - } - - @Override - public Integer getNotifyBlockSize() { - return notifyBlockSize; - } - - @Override - public void setNotifyBlockSize(Integer notifyBlockSize) { - this.notifyBlockSize = notifyBlockSize; - } - - @Override - public String getInstallVerifierURI() { - return installVerifierURI; - } - - @Override - public void setInstallVerifierURI(String installVerifierURI) { - this.installVerifierURI = installVerifierURI; - } - - public static AdvancedPackageDownloadOptionsImpl parse(AdvancedPackageDownloadOptions advancedPackageDownloadOptions) { - return advancedPackageDownloadOptions != null ? (advancedPackageDownloadOptions instanceof AdvancedPackageDownloadOptionsImpl ? (AdvancedPackageDownloadOptionsImpl) advancedPackageDownloadOptions : new AdvancedPackageDownloadOptionsImpl(advancedPackageDownloadOptions)) : null; - } -} diff --git a/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/model/download/internal/DevicePackageDownloadOperationImpl.java b/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/model/download/internal/DevicePackageDownloadOperationImpl.java deleted file mode 100644 index 8f067a9cbe8..00000000000 --- a/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/model/download/internal/DevicePackageDownloadOperationImpl.java +++ /dev/null @@ -1,79 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.packages.model.download.internal; - -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.device.management.packages.model.download.DevicePackageDownloadOperation; -import org.eclipse.kapua.service.device.management.packages.model.download.DevicePackageDownloadStatus; - -/** - * Device download package operation entity. - * - * @since 1.0 - */ -public class DevicePackageDownloadOperationImpl implements DevicePackageDownloadOperation { - - - private KapuaId id; - private Integer size; - private Integer progress; - private DevicePackageDownloadStatus status; - - /** - * Constructor. - * - * @since 1.0.0 - */ - public DevicePackageDownloadOperationImpl() { - } - - @Override - public KapuaId getId() { - return id; - } - - @Override - public void setId(KapuaId id) { - this.id = id; - } - - @Override - public Integer getSize() { - return size; - } - - @Override - public void setSize(Integer size) { - this.size = size; - } - - @Override - public Integer getProgress() { - return progress; - } - - @Override - public void setProgress(Integer progress) { - this.progress = progress; - } - - @Override - public DevicePackageDownloadStatus getStatus() { - return status; - } - - @Override - public void setStatus(DevicePackageDownloadStatus status) { - this.status = status; - } -} diff --git a/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/model/download/internal/DevicePackageDownloadOptionsImpl.java b/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/model/download/internal/DevicePackageDownloadOptionsImpl.java deleted file mode 100644 index 80ae4602392..00000000000 --- a/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/model/download/internal/DevicePackageDownloadOptionsImpl.java +++ /dev/null @@ -1,24 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2019, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.packages.model.download.internal; - -import org.eclipse.kapua.service.device.management.packages.model.download.DevicePackageDownloadOptions; -import org.eclipse.kapua.service.device.management.packages.model.internal.DevicePackageOptionsImpl; - -/** - * {@link DevicePackageDownloadOptions} implementation. - * - * @since 1.1.0 - */ -public class DevicePackageDownloadOptionsImpl extends DevicePackageOptionsImpl implements DevicePackageDownloadOptions { -} diff --git a/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/model/download/internal/DevicePackageDownloadRequestImpl.java b/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/model/download/internal/DevicePackageDownloadRequestImpl.java deleted file mode 100644 index fb272a0cb26..00000000000 --- a/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/model/download/internal/DevicePackageDownloadRequestImpl.java +++ /dev/null @@ -1,158 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.packages.model.download.internal; - -import org.eclipse.kapua.service.device.management.packages.model.FileType; -import org.eclipse.kapua.service.device.management.packages.model.download.AdvancedPackageDownloadOptions; -import org.eclipse.kapua.service.device.management.packages.model.download.DevicePackageDownloadRequest; - -import java.net.URI; - -/** - * {@link DevicePackageDownloadRequest} implementation. - * - * @since 1.0.0 - */ -public class DevicePackageDownloadRequestImpl implements DevicePackageDownloadRequest { - - private URI uri; - private String name; - private String version; - - private String username; - private String password; - - private String fileHash; - private FileType fileType; - - private Boolean install; - - private Boolean reboot; - private Integer rebootDelay; - - private AdvancedPackageDownloadOptionsImpl advancedOptions; - - @Override - public URI getUri() { - return uri; - } - - @Override - public void setUri(URI uri) { - this.uri = uri; - } - - @Override - public String getName() { - return name; - } - - @Override - public void setName(String name) { - this.name = name; - } - - @Override - public String getVersion() { - return version; - } - - @Override - public void setVersion(String version) { - this.version = version; - } - - @Override - public Boolean getInstall() { - return install; - } - - @Override - public String getUsername() { - return username; - } - - @Override - public void setUsername(String username) { - this.username = username; - } - - @Override - public String getPassword() { - return password; - } - - @Override - public void setPassword(String password) { - this.password = password; - } - - @Override - public String getFileHash() { - return fileHash; - } - - @Override - public void setFileHash(String fileHash) { - this.fileHash = fileHash; - } - - @Override - public FileType getFileType() { - return fileType; - } - - @Override - public void setFileType(FileType fileType) { - this.fileType = fileType; - } - - @Override - public void setInstall(Boolean install) { - this.install = install; - } - - @Override - public Boolean getReboot() { - return reboot; - } - - @Override - public void setReboot(Boolean reboot) { - this.reboot = reboot; - } - - @Override - public Integer getRebootDelay() { - return rebootDelay; - } - - @Override - public void setRebootDelay(Integer rebootDelay) { - this.rebootDelay = rebootDelay; - } - - @Override - public AdvancedPackageDownloadOptions getAdvancedOptions() { - if (advancedOptions == null) { - advancedOptions = new AdvancedPackageDownloadOptionsImpl(); - } - - return advancedOptions; - } - - @Override - public void setAdvancedOptions(AdvancedPackageDownloadOptions advancedOptions) { - this.advancedOptions = AdvancedPackageDownloadOptionsImpl.parse(advancedOptions); - } -} diff --git a/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/model/install/internal/DevicePackageInstallOperationImpl.java b/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/model/install/internal/DevicePackageInstallOperationImpl.java deleted file mode 100644 index c018ff3544e..00000000000 --- a/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/model/install/internal/DevicePackageInstallOperationImpl.java +++ /dev/null @@ -1,70 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.packages.model.install.internal; - -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.device.management.packages.model.install.DevicePackageInstallOperation; -import org.eclipse.kapua.service.device.management.packages.model.install.DevicePackageInstallStatus; - -/** - * {@link DevicePackageInstallOperation} implementation. - * - * @since 1.0.0 - */ -public class DevicePackageInstallOperationImpl implements DevicePackageInstallOperation { - - private KapuaId id; - private String name; - private String version; - private DevicePackageInstallStatus status; - - @Override - public KapuaId getId() { - return id; - } - - @Override - public void setId(KapuaId id) { - this.id = id; - } - - @Override - public String getName() { - return name; - } - - @Override - public void setName(String name) { - this.name = name; - } - - @Override - public String getVersion() { - return version; - } - - @Override - public void setVersion(String version) { - this.version = version; - } - - @Override - public DevicePackageInstallStatus getStatus() { - return status; - } - - @Override - public void setStatus(DevicePackageInstallStatus status) { - this.status = status; - } -} diff --git a/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/model/install/internal/DevicePackageInstallOptionsImpl.java b/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/model/install/internal/DevicePackageInstallOptionsImpl.java deleted file mode 100644 index eb7fee1f396..00000000000 --- a/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/model/install/internal/DevicePackageInstallOptionsImpl.java +++ /dev/null @@ -1,24 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2019, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.packages.model.install.internal; - -import org.eclipse.kapua.service.device.management.packages.model.install.DevicePackageInstallOptions; -import org.eclipse.kapua.service.device.management.packages.model.internal.DevicePackageOptionsImpl; - -/** - * {@link DevicePackageInstallOptions} implementation - * - * @since 1.1.0 - */ -public class DevicePackageInstallOptionsImpl extends DevicePackageOptionsImpl implements DevicePackageInstallOptions { -} diff --git a/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/model/install/internal/DevicePackageInstallRequestImpl.java b/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/model/install/internal/DevicePackageInstallRequestImpl.java deleted file mode 100644 index 57d5b2ff5cd..00000000000 --- a/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/model/install/internal/DevicePackageInstallRequestImpl.java +++ /dev/null @@ -1,69 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.packages.model.install.internal; - -import org.eclipse.kapua.service.device.management.packages.model.install.DevicePackageInstallRequest; - -/** - * Device package install request. - * - * @since 1.0 - * - */ -public class DevicePackageInstallRequestImpl implements DevicePackageInstallRequest { - - private String name; - private String version; - private Boolean reboot; - private Integer rebootDelay; - - @Override - public String getName() { - return name; - } - - @Override - public void setName(String name) { - this.name = name; - } - - @Override - public String getVersion() { - return version; - } - - @Override - public void setVersion(String version) { - this.version = version; - } - - @Override - public Boolean isReboot() { - return reboot; - } - - @Override - public void setReboot(Boolean reboot) { - this.reboot = reboot; - } - - @Override - public Integer getRebootDelay() { - return rebootDelay; - } - - @Override - public void setRebootDelay(Integer rebootDelay) { - this.rebootDelay = rebootDelay; - } -} diff --git a/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/model/internal/DevicePackageBundleInfoImpl.java b/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/model/internal/DevicePackageBundleInfoImpl.java deleted file mode 100644 index 7f6c725fa2e..00000000000 --- a/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/model/internal/DevicePackageBundleInfoImpl.java +++ /dev/null @@ -1,54 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.packages.model.internal; - -import org.eclipse.kapua.service.device.management.packages.model.DevicePackageBundleInfo; - -/** - * {@link DevicePackageBundleInfo} implementation. - * - * @since 1.0.0 - */ -public class DevicePackageBundleInfoImpl implements DevicePackageBundleInfo { - - public String name; - public String version; - - /** - * Constructor. - * - * @since 1.0.0 - */ - public DevicePackageBundleInfoImpl() { - } - - @Override - public String getName() { - return name; - } - - @Override - public void setName(String name) { - this.name = name; - } - - @Override - public String getVersion() { - return version; - } - - @Override - public void setVersion(String version) { - this.version = version; - } -} diff --git a/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/model/internal/DevicePackageBundleInfosImpl.java b/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/model/internal/DevicePackageBundleInfosImpl.java deleted file mode 100644 index 971a0ed28c0..00000000000 --- a/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/model/internal/DevicePackageBundleInfosImpl.java +++ /dev/null @@ -1,45 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.packages.model.internal; - -import org.eclipse.kapua.service.device.management.packages.model.DevicePackageBundleInfo; -import org.eclipse.kapua.service.device.management.packages.model.DevicePackageBundleInfos; - -import java.util.ArrayList; -import java.util.List; - -/** - * {@link DevicePackageBundleInfos} implementation. - * - * @since 1.0.0 - */ -public class DevicePackageBundleInfosImpl implements DevicePackageBundleInfos { - - List bundleInfos; - - /** - * Constructor. - * - * @since 1.0.0 - */ - public DevicePackageBundleInfosImpl() { - } - - @Override - public List getBundlesInfos() { - if (bundleInfos == null) { - bundleInfos = new ArrayList<>(); - } - return bundleInfos; - } -} diff --git a/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/model/internal/DevicePackageImpl.java b/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/model/internal/DevicePackageImpl.java deleted file mode 100644 index 692a2bb3486..00000000000 --- a/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/model/internal/DevicePackageImpl.java +++ /dev/null @@ -1,83 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.packages.model.internal; - -import org.eclipse.kapua.service.device.management.packages.model.DevicePackage; -import org.eclipse.kapua.service.device.management.packages.model.DevicePackageBundleInfos; - -import java.util.Date; - -/** - * {@link DevicePackage} implementation. - * - * @since 1.0.0 - */ -public class DevicePackageImpl implements DevicePackage { - - private String name; - private String version; - private DevicePackageBundleInfos bundleInfos; - private Date installDate; - - /** - * Constructor. - * - * @since 1.0.0 - */ - public DevicePackageImpl() { - } - - @Override - public String getName() { - return name; - } - - @Override - public void setName(String name) { - this.name = name; - } - - @Override - public String getVersion() { - return version; - } - - @Override - public void setVersion(String version) { - this.version = version; - } - - @Override - public DevicePackageBundleInfos getBundleInfos() { - if (bundleInfos == null) { - bundleInfos = new DevicePackageBundleInfosImpl(); - } - - return bundleInfos; - } - - @Override - public void setBundleInfos(DevicePackageBundleInfos bundleInfos) { - this.bundleInfos = bundleInfos; - } - - @Override - public Date getInstallDate() { - return installDate; - } - - @Override - public void setInstallDate(Date installDate) { - this.installDate = installDate; - } -} diff --git a/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/model/internal/DevicePackageOptionsImpl.java b/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/model/internal/DevicePackageOptionsImpl.java deleted file mode 100644 index 85c0043e552..00000000000 --- a/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/model/internal/DevicePackageOptionsImpl.java +++ /dev/null @@ -1,35 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2019, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.packages.model.internal; - -import org.eclipse.kapua.service.device.management.packages.model.DevicePackageOptions; - -/** - * {@link DevicePackageOptions} {@code abstract} implementation. - * - * @since 1.1.0 - */ -public abstract class DevicePackageOptionsImpl implements DevicePackageOptions { - - private Long timeout; - - @Override - public Long getTimeout() { - return timeout; - } - - @Override - public void setTimeout(Long timeout) { - this.timeout = timeout; - } -} diff --git a/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/model/internal/DevicePackagesImpl.java b/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/model/internal/DevicePackagesImpl.java deleted file mode 100644 index 08c80aa6e81..00000000000 --- a/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/model/internal/DevicePackagesImpl.java +++ /dev/null @@ -1,42 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - * Red Hat Inc - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.packages.model.internal; - -import org.eclipse.kapua.service.device.management.packages.model.DevicePackage; -import org.eclipse.kapua.service.device.management.packages.model.DevicePackages; - -import java.util.ArrayList; -import java.util.List; - -/** - * {@link DevicePackages} implementation. - * - * @since 1.0.0 - */ -public class DevicePackagesImpl implements DevicePackages { - - private static final long serialVersionUID = 2450088980495469562L; - - public List deploymentPackages; - - @Override - public List getPackages() { - if (deploymentPackages == null) { - deploymentPackages = new ArrayList<>(); - } - - return deploymentPackages; - } - -} diff --git a/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/model/uninstall/internal/DevicePackageUninstallOperationImpl.java b/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/model/uninstall/internal/DevicePackageUninstallOperationImpl.java deleted file mode 100644 index 59c5aaee911..00000000000 --- a/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/model/uninstall/internal/DevicePackageUninstallOperationImpl.java +++ /dev/null @@ -1,70 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.packages.model.uninstall.internal; - -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.device.management.packages.model.uninstall.DevicePackageUninstallOperation; -import org.eclipse.kapua.service.device.management.packages.model.uninstall.DevicePackageUninstallStatus; - -/** - * {@link DevicePackageUninstallOperation} implementation. - * - * @since 1.0.0 - */ -public class DevicePackageUninstallOperationImpl implements DevicePackageUninstallOperation { - - private KapuaId id; - private String name; - private String version; - private DevicePackageUninstallStatus status; - - @Override - public KapuaId getId() { - return id; - } - - @Override - public void setId(KapuaId id) { - this.id = id; - } - - @Override - public String getName() { - return name; - } - - @Override - public void setName(String name) { - this.name = name; - } - - @Override - public String getVersion() { - return version; - } - - @Override - public void setVersion(String version) { - this.version = version; - } - - @Override - public DevicePackageUninstallStatus getStatus() { - return status; - } - - @Override - public void setStatus(DevicePackageUninstallStatus status) { - this.status = status; - } -} diff --git a/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/model/uninstall/internal/DevicePackageUninstallOptionsImpl.java b/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/model/uninstall/internal/DevicePackageUninstallOptionsImpl.java deleted file mode 100644 index 83c70875213..00000000000 --- a/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/model/uninstall/internal/DevicePackageUninstallOptionsImpl.java +++ /dev/null @@ -1,24 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2019, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.packages.model.uninstall.internal; - -import org.eclipse.kapua.service.device.management.packages.model.internal.DevicePackageOptionsImpl; -import org.eclipse.kapua.service.device.management.packages.model.uninstall.DevicePackageUninstallOptions; - -/** - * {@link DevicePackageUninstallOptions} implementation. - * - * @since 1.1.0 - */ -public class DevicePackageUninstallOptionsImpl extends DevicePackageOptionsImpl implements DevicePackageUninstallOptions { -} diff --git a/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/model/uninstall/internal/DevicePackageUninstallRequestImpl.java b/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/model/uninstall/internal/DevicePackageUninstallRequestImpl.java deleted file mode 100644 index 468c96f19a1..00000000000 --- a/service/device/management/packages/internal/src/main/java/org/eclipse/kapua/service/device/management/packages/model/uninstall/internal/DevicePackageUninstallRequestImpl.java +++ /dev/null @@ -1,70 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.packages.model.uninstall.internal; - -import org.eclipse.kapua.service.device.management.packages.model.uninstall.DevicePackageUninstallRequest; - -/** - * Device package uninstall request. - * - * @since 1.0 - * - */ -public class DevicePackageUninstallRequestImpl implements DevicePackageUninstallRequest { - - public String name; - public String version; - - public Boolean reboot; - public Integer rebootDelay; - - @Override - public String getName() { - return name; - } - - @Override - public void setName(String name) { - this.name = name; - } - - @Override - public String getVersion() { - return version; - } - - @Override - public void setVersion(String version) { - this.version = version; - } - - @Override - public Boolean isReboot() { - return reboot; - } - - @Override - public void setReboot(Boolean reboot) { - this.reboot = reboot; - } - - @Override - public Integer getRebootDelay() { - return rebootDelay; - } - - @Override - public void setRebootDelay(Integer rebootDelay) { - this.rebootDelay = rebootDelay; - } -} diff --git a/service/device/management/packages/job/pom.xml b/service/device/management/packages/job/pom.xml index 096810c4c1b..1751ed77474 100644 --- a/service/device/management/packages/job/pom.xml +++ b/service/device/management/packages/job/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-device-management-packages - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-device-management-packages-job diff --git a/service/device/management/packages/job/src/main/java/org/eclipse/kapua/service/device/management/packages/job/AbstractDevicePackageTargetProcessor.java b/service/device/management/packages/job/src/main/java/org/eclipse/kapua/service/device/management/packages/job/AbstractDevicePackageTargetProcessor.java index 9657e50dacb..8257556fa72 100644 --- a/service/device/management/packages/job/src/main/java/org/eclipse/kapua/service/device/management/packages/job/AbstractDevicePackageTargetProcessor.java +++ b/service/device/management/packages/job/src/main/java/org/eclipse/kapua/service/device/management/packages/job/AbstractDevicePackageTargetProcessor.java @@ -12,10 +12,11 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.packages.job; +import javax.inject.Inject; + import org.eclipse.kapua.KapuaEntityNotFoundException; import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.commons.security.KapuaSecurityUtils; -import org.eclipse.kapua.job.engine.JobEngineFactory; import org.eclipse.kapua.job.engine.JobEngineService; import org.eclipse.kapua.job.engine.JobStartOptions; import org.eclipse.kapua.job.engine.commons.operation.AbstractDeviceTargetProcessor; @@ -32,8 +33,6 @@ import org.eclipse.kapua.service.job.targets.JobTarget; import org.eclipse.kapua.service.job.targets.JobTargetStatus; -import javax.inject.Inject; - /** * {@link AbstractDevicePackageTargetProcessor} for {@link DevicePackageManagementService} operations. * @@ -49,12 +48,10 @@ public abstract class AbstractDevicePackageTargetProcessor extends AbstractDevic JobDeviceManagementOperationFactory jobDeviceManagementOperationFactory; @Inject JobEngineService jobEngineService; - @Inject - JobEngineFactory jobEngineFactory; protected void createJobDeviceManagementOperation(KapuaId scopeId, KapuaId jobId, JobTarget jobTarget, KapuaId operationId) throws KapuaException { // Save the jobId-deviceManagementOperationId pair to track resuming - JobDeviceManagementOperationCreator jobDeviceManagementOperationCreator = jobDeviceManagementOperationFactory.newCreator(scopeId); + JobDeviceManagementOperationCreator jobDeviceManagementOperationCreator = new JobDeviceManagementOperationCreator(scopeId); jobDeviceManagementOperationCreator.setJobId(jobId); jobDeviceManagementOperationCreator.setDeviceManagementOperationId(operationId); @@ -82,7 +79,7 @@ protected void createJobDeviceManagementOperation(KapuaId scopeId, KapuaId jobId return; } // Enqueue the job - JobStartOptions jobStartOptions = jobEngineFactory.newJobStartOptions(); + JobStartOptions jobStartOptions = new JobStartOptions(); jobStartOptions.addTargetIdToSublist(jobTarget.getId()); jobStartOptions.setFromStepIndex(jobTarget.getStepIndex()); jobStartOptions.setEnqueue(true); diff --git a/service/device/management/packages/job/src/main/java/org/eclipse/kapua/service/device/management/packages/job/DevicePackageDownloadTargetProcessor.java b/service/device/management/packages/job/src/main/java/org/eclipse/kapua/service/device/management/packages/job/DevicePackageDownloadTargetProcessor.java index cc868c49c1f..fd1ea813b7f 100644 --- a/service/device/management/packages/job/src/main/java/org/eclipse/kapua/service/device/management/packages/job/DevicePackageDownloadTargetProcessor.java +++ b/service/device/management/packages/job/src/main/java/org/eclipse/kapua/service/device/management/packages/job/DevicePackageDownloadTargetProcessor.java @@ -12,11 +12,14 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.packages.job; +import javax.batch.runtime.context.JobContext; +import javax.batch.runtime.context.StepContext; +import javax.inject.Inject; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.commons.security.KapuaSecurityUtils; import org.eclipse.kapua.job.engine.commons.wrappers.JobTargetWrapper; import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.device.management.packages.DevicePackageFactory; import org.eclipse.kapua.service.device.management.packages.DevicePackageManagementService; import org.eclipse.kapua.service.device.management.packages.job.definition.DevicePackageDownloadPropertyKeys; import org.eclipse.kapua.service.device.management.packages.model.download.DevicePackageDownloadOptions; @@ -25,10 +28,6 @@ import org.eclipse.kapua.service.job.targets.JobTarget; import org.eclipse.kapua.service.job.targets.JobTargetStatus; -import javax.batch.runtime.context.JobContext; -import javax.batch.runtime.context.StepContext; -import javax.inject.Inject; - /** * {@link TargetProcessor} for {@link DevicePackageManagementService#downloadExec(KapuaId, KapuaId, DevicePackageDownloadRequest, Long)}. * @@ -39,8 +38,6 @@ public class DevicePackageDownloadTargetProcessor extends AbstractDevicePackageT @Inject DevicePackageManagementService devicePackageManagementService; @Inject - DevicePackageFactory devicePackageFactory; - @Inject JobContext jobContext; @Inject StepContext stepContext; @@ -63,7 +60,7 @@ public void processTarget(JobTarget jobTarget) throws KapuaException { DevicePackageDownloadRequest packageDownloadRequest = stepContextWrapper.getStepProperty(DevicePackageDownloadPropertyKeys.PACKAGE_DOWNLOAD_REQUEST, DevicePackageDownloadRequest.class); Long timeout = stepContextWrapper.getStepProperty(DevicePackageDownloadPropertyKeys.TIMEOUT, Long.class); // Send the request - DevicePackageDownloadOptions packageDownloadOptions = devicePackageFactory.newPackageDownloadOptions(); + DevicePackageDownloadOptions packageDownloadOptions = new DevicePackageDownloadOptions(); packageDownloadOptions.setTimeout(timeout); KapuaId operationId = KapuaSecurityUtils.doPrivileged(() -> devicePackageManagementService.downloadExec(scopeId, jobTarget.getJobTargetId(), packageDownloadRequest, packageDownloadOptions)); diff --git a/service/device/management/packages/job/src/main/java/org/eclipse/kapua/service/device/management/packages/job/DevicePackageUninstallTargetProcessor.java b/service/device/management/packages/job/src/main/java/org/eclipse/kapua/service/device/management/packages/job/DevicePackageUninstallTargetProcessor.java index 1b8d9171a2c..c1a50784a9e 100644 --- a/service/device/management/packages/job/src/main/java/org/eclipse/kapua/service/device/management/packages/job/DevicePackageUninstallTargetProcessor.java +++ b/service/device/management/packages/job/src/main/java/org/eclipse/kapua/service/device/management/packages/job/DevicePackageUninstallTargetProcessor.java @@ -12,11 +12,14 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.packages.job; +import javax.batch.runtime.context.JobContext; +import javax.batch.runtime.context.StepContext; +import javax.inject.Inject; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.commons.security.KapuaSecurityUtils; import org.eclipse.kapua.job.engine.commons.wrappers.JobTargetWrapper; import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.device.management.packages.DevicePackageFactory; import org.eclipse.kapua.service.device.management.packages.DevicePackageManagementService; import org.eclipse.kapua.service.device.management.packages.job.definition.DevicePackageUninstallPropertyKeys; import org.eclipse.kapua.service.device.management.packages.model.uninstall.DevicePackageUninstallOptions; @@ -25,10 +28,6 @@ import org.eclipse.kapua.service.job.targets.JobTarget; import org.eclipse.kapua.service.job.targets.JobTargetStatus; -import javax.batch.runtime.context.JobContext; -import javax.batch.runtime.context.StepContext; -import javax.inject.Inject; - /** * {@link TargetProcessor} for {@link DevicePackageManagementService#uninstallExec(KapuaId, KapuaId, DevicePackageUninstallRequest, Long)}. * @@ -39,8 +38,6 @@ public class DevicePackageUninstallTargetProcessor extends AbstractDevicePackage @Inject DevicePackageManagementService devicePackageManagementService; @Inject - DevicePackageFactory devicePackageFactory; - @Inject JobContext jobContext; @Inject StepContext stepContext; @@ -59,10 +56,11 @@ public void processTarget(JobTarget jobTarget) throws KapuaException { DevicePackageUninstallRequest packageUninstallRequest = stepContextWrapper.getStepProperty(DevicePackageUninstallPropertyKeys.PACKAGE_UNINSTALL_REQUEST, DevicePackageUninstallRequest.class); Long timeout = stepContextWrapper.getStepProperty(DevicePackageUninstallPropertyKeys.TIMEOUT, Long.class); // Send the request - DevicePackageUninstallOptions packageUninstallOptions = devicePackageFactory.newPackageUninstallOptions(); + DevicePackageUninstallOptions packageUninstallOptions = new DevicePackageUninstallOptions(); packageUninstallOptions.setTimeout(timeout); - KapuaId operationId = KapuaSecurityUtils.doPrivileged(() -> devicePackageManagementService.uninstallExec(scopeId, jobTarget.getJobTargetId(), packageUninstallRequest, packageUninstallOptions)); + KapuaId operationId = KapuaSecurityUtils.doPrivileged( + () -> devicePackageManagementService.uninstallExec(scopeId, jobTarget.getJobTargetId(), packageUninstallRequest, packageUninstallOptions)); // Save the jobId-deviceManagementOperationId pair to track resuming createJobDeviceManagementOperation(scopeId, jobId, jobTarget, operationId); } diff --git a/service/device/management/packages/pom.xml b/service/device/management/packages/pom.xml index f49ae48699d..3b1dbb8ae5e 100644 --- a/service/device/management/packages/pom.xml +++ b/service/device/management/packages/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-device-management - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT pom diff --git a/service/device/management/pom.xml b/service/device/management/pom.xml index 61e4ac4c1bd..36b942bf72f 100644 --- a/service/device/management/pom.xml +++ b/service/device/management/pom.xml @@ -19,7 +19,7 @@ kapua-device org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-device-management diff --git a/service/device/management/registry/api/pom.xml b/service/device/management/registry/api/pom.xml index 97531a18804..23e7fd0dfce 100644 --- a/service/device/management/registry/api/pom.xml +++ b/service/device/management/registry/api/pom.xml @@ -19,7 +19,7 @@ kapua-device-management-registry org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-device-management-registry-api diff --git a/service/device/management/registry/api/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/DeviceManagementOperationCreator.java b/service/device/management/registry/api/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/DeviceManagementOperationCreator.java index 7ee48462520..bb431e1e181 100644 --- a/service/device/management/registry/api/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/DeviceManagementOperationCreator.java +++ b/service/device/management/registry/api/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/DeviceManagementOperationCreator.java @@ -12,12 +12,9 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.registry.operation; -import org.eclipse.kapua.model.KapuaEntityCreator; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.model.id.KapuaIdAdapter; -import org.eclipse.kapua.model.xml.DateXmlAdapter; -import org.eclipse.kapua.service.device.management.message.KapuaMethod; -import org.eclipse.kapua.service.device.management.message.notification.NotifyStatus; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; @@ -26,57 +23,116 @@ import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; -import java.util.Date; -import java.util.List; + +import org.eclipse.kapua.model.KapuaEntityCreator; +import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.id.KapuaIdAdapter; +import org.eclipse.kapua.model.xml.DateXmlAdapter; +import org.eclipse.kapua.service.device.management.message.KapuaMethod; +import org.eclipse.kapua.service.device.management.message.notification.NotifyStatus; @XmlRootElement(name = "deviceManagementOperationCreator") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = DeviceManagementOperationXmlRegistry.class, factoryMethod = "newDeviceManagementOperationCreator") -public interface DeviceManagementOperationCreator extends KapuaEntityCreator { +@XmlType +public class DeviceManagementOperationCreator extends KapuaEntityCreator { + + private Date startedOn; + private KapuaId deviceId; + private KapuaId operationId; + private String appId; + private KapuaMethod action; + private String resource; + private NotifyStatus status; + private List inputProperties; + + public DeviceManagementOperationCreator() { + } + + public DeviceManagementOperationCreator(KapuaId scopeId) { + super(scopeId); + } + + public DeviceManagementOperationCreator(KapuaEntityCreator entityCreator) { + super(entityCreator); + } @XmlElement(name = "startedOn") @XmlJavaTypeAdapter(DateXmlAdapter.class) - public Date getStartedOn(); + public Date getStartedOn() { + return startedOn; + } - void setStartedOn(Date startedOn); + public void setStartedOn(Date startedOn) { + this.startedOn = startedOn; + } @XmlElement(name = "deviceId") @XmlJavaTypeAdapter(KapuaIdAdapter.class) - KapuaId getDeviceId(); - - void setDeviceId(KapuaId deviceId); + public KapuaId getDeviceId() { + return deviceId; + } + public void setDeviceId(KapuaId deviceId) { + this.deviceId = deviceId; + } @XmlElement(name = "operationId") @XmlJavaTypeAdapter(KapuaIdAdapter.class) - KapuaId getOperationId(); - - void setOperationId(KapuaId operationId); + public KapuaId getOperationId() { + return operationId; + } + public void setOperationId(KapuaId operationId) { + this.operationId = operationId; + } @XmlElement(name = "appId") - String getAppId(); + public String getAppId() { + return appId; + } - void setAppId(String appId); + public void setAppId(String appId) { + this.appId = appId; + } @XmlElement(name = "action") - KapuaMethod getAction(); + public KapuaMethod getAction() { + return action.normalizeAction(); + } - void setAction(KapuaMethod action); + public void setAction(KapuaMethod action) { + this.action = action.normalizeAction(); + } @XmlElement(name = "resource") - String getResource(); + public String getResource() { + return resource; + } - void setResource(String resource); + public void setResource(String resource) { + this.resource = resource; + } @XmlElement(name = "status") - NotifyStatus getStatus(); + public NotifyStatus getStatus() { + return status; + } - void setStatus(NotifyStatus status); + public void setStatus(NotifyStatus status) { + this.status = status; + } @XmlElementWrapper(name = "operationProperties") @XmlElement(name = "operationProperty") -

        List

        getInputProperties(); + public List getInputProperties() { + if (inputProperties == null) { + inputProperties = new ArrayList<>(); + } + + return inputProperties; + } - void setInputProperties(List inputProperties); + public void setInputProperties(List inputProperties) { + this.inputProperties = inputProperties; + } } diff --git a/service/device/management/registry/api/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/DeviceManagementOperationFactory.java b/service/device/management/registry/api/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/DeviceManagementOperationFactory.java index 157f43cab15..05f03b72284 100644 --- a/service/device/management/registry/api/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/DeviceManagementOperationFactory.java +++ b/service/device/management/registry/api/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/DeviceManagementOperationFactory.java @@ -20,14 +20,17 @@ * @see org.eclipse.kapua.model.KapuaEntityFactory * @since 1.0.0 */ -public interface DeviceManagementOperationFactory extends KapuaEntityFactory { +public interface DeviceManagementOperationFactory extends KapuaEntityFactory { /** * Instantiates a new {@link DeviceManagementOperationProperty}. * - * @param name The name to set in the {@link DeviceManagementOperationProperty} - * @param propertyType The property type to set in the {@link DeviceManagementOperationProperty} - * @param propertyValue The property value to set in the {@link DeviceManagementOperationProperty} + * @param name + * The name to set in the {@link DeviceManagementOperationProperty} + * @param propertyType + * The property type to set in the {@link DeviceManagementOperationProperty} + * @param propertyValue + * The property value to set in the {@link DeviceManagementOperationProperty} * @return The newly instantiated {@link DeviceManagementOperationProperty} * @since 1.0.0 */ diff --git a/service/device/management/registry/api/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/DeviceManagementOperationListResult.java b/service/device/management/registry/api/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/DeviceManagementOperationListResult.java index 303304154d3..377b61fb8a6 100644 --- a/service/device/management/registry/api/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/DeviceManagementOperationListResult.java +++ b/service/device/management/registry/api/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/DeviceManagementOperationListResult.java @@ -12,13 +12,13 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.registry.operation; -import org.eclipse.kapua.model.query.KapuaListResult; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; +import org.eclipse.kapua.model.query.KapuaListResult; + /** * {@link DeviceManagementOperationListResult} definition. * @@ -26,7 +26,7 @@ */ @XmlRootElement(name = "deviceManagementOperationListResult") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = DeviceManagementOperationXmlRegistry.class, factoryMethod = "newDeviceManagementOperationListResult") -public interface DeviceManagementOperationListResult extends KapuaListResult { +@XmlType +public class DeviceManagementOperationListResult extends KapuaListResult { } diff --git a/service/device/management/registry/api/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/DeviceManagementOperationQuery.java b/service/device/management/registry/api/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/DeviceManagementOperationQuery.java index fd82bbd6242..c82becf2fcf 100644 --- a/service/device/management/registry/api/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/DeviceManagementOperationQuery.java +++ b/service/device/management/registry/api/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/DeviceManagementOperationQuery.java @@ -12,13 +12,16 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.registry.operation; -import org.eclipse.kapua.model.query.KapuaQuery; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; +import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.query.KapuaQuery; +import org.eclipse.kapua.model.query.KapuaSortCriteria; +import org.eclipse.kapua.model.query.SortOrder; + /** * {@link DeviceManagementOperation} {@link KapuaQuery} definition. * @@ -27,6 +30,34 @@ */ @XmlRootElement(name = "query") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = DeviceManagementOperationXmlRegistry.class, factoryMethod = "newQuery") -public interface DeviceManagementOperationQuery extends KapuaQuery { +@XmlType +public class DeviceManagementOperationQuery extends KapuaQuery { + + /** + * Constructor. + * + * @since 1.1.0 + */ + private DeviceManagementOperationQuery() { + super(); + } + + /** + * Constructor. + * + * @param scopeId + * The {@link #getScopeId()}. + * @since 1.1.0 + */ + public DeviceManagementOperationQuery(KapuaId scopeId) { + this(); + + setScopeId(scopeId); + } + + @Override + public KapuaSortCriteria getDefaultSortCriteria() { + return fieldSortCriteria(DeviceManagementOperationAttributes.STARTED_ON, SortOrder.ASCENDING); + } + } diff --git a/service/device/management/registry/api/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/DeviceManagementOperationXmlRegistry.java b/service/device/management/registry/api/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/DeviceManagementOperationXmlRegistry.java index 42f4859e536..3f14358fbff 100644 --- a/service/device/management/registry/api/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/DeviceManagementOperationXmlRegistry.java +++ b/service/device/management/registry/api/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/DeviceManagementOperationXmlRegistry.java @@ -12,10 +12,10 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.registry.operation; -import org.eclipse.kapua.locator.KapuaLocator; - import javax.xml.bind.annotation.XmlRegistry; +import org.eclipse.kapua.locator.KapuaLocator; + /** * {@link DeviceManagementOperation} xml factory class * @@ -30,16 +30,4 @@ public class DeviceManagementOperationXmlRegistry { DeviceManagementOperation newDeviceManagementOperation() { return factory.newEntity(null); } - - DeviceManagementOperationCreator newDeviceManagementOperationCreator() { - return factory.newCreator(null); - } - - DeviceManagementOperationListResult newDeviceManagementOperationListResult() { - return factory.newListResult(); - } - - DeviceManagementOperationQuery newQuery() { - return factory.newQuery(null); - } } diff --git a/service/device/management/registry/api/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/notification/ManagementOperationNotificationCreator.java b/service/device/management/registry/api/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/notification/ManagementOperationNotificationCreator.java index dd247156e92..ffd005eea70 100644 --- a/service/device/management/registry/api/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/notification/ManagementOperationNotificationCreator.java +++ b/service/device/management/registry/api/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/notification/ManagementOperationNotificationCreator.java @@ -12,13 +12,7 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.registry.operation.notification; -import org.eclipse.kapua.model.KapuaEntityCreator; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.model.id.KapuaIdAdapter; -import org.eclipse.kapua.model.xml.DateXmlAdapter; -import org.eclipse.kapua.service.device.management.message.notification.NotifyStatus; -import org.eclipse.kapua.service.device.management.registry.operation.DeviceManagementOperation; -import org.eclipse.kapua.service.device.management.registry.operation.DeviceManagementOperationStatus; +import java.util.Date; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; @@ -26,7 +20,14 @@ import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; -import java.util.Date; + +import org.eclipse.kapua.model.KapuaEntityCreator; +import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.id.KapuaIdAdapter; +import org.eclipse.kapua.model.xml.DateXmlAdapter; +import org.eclipse.kapua.service.device.management.message.notification.NotifyStatus; +import org.eclipse.kapua.service.device.management.registry.operation.DeviceManagementOperation; +import org.eclipse.kapua.service.device.management.registry.operation.DeviceManagementOperationStatus; /** * {@link ManagementOperationNotificationCreator} definition. @@ -35,8 +36,26 @@ */ @XmlRootElement(name = "deviceManagementOperationNotificationCreator") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = ManagementOperationNotificationXmlRegistry.class, factoryMethod = "newManagementOperationNotificationCreator") -public interface ManagementOperationNotificationCreator extends KapuaEntityCreator { +@XmlType +public class ManagementOperationNotificationCreator extends KapuaEntityCreator { + + private KapuaId operationId; + private Date sentOn; + private DeviceManagementOperationStatus status; + private String resource; + private Integer progress; + private String message; + + public ManagementOperationNotificationCreator() { + } + + public ManagementOperationNotificationCreator(KapuaId scopeId) { + super(scopeId); + } + + public ManagementOperationNotificationCreator(KapuaEntityCreator entityCreator) { + super(entityCreator); + } /** * Gets the {@link DeviceManagementOperation#getId()}. @@ -46,15 +65,20 @@ public interface ManagementOperationNotificationCreator extends KapuaEntityCreat */ @XmlElement(name = "operationId") @XmlJavaTypeAdapter(KapuaIdAdapter.class) - KapuaId getOperationId(); + public KapuaId getOperationId() { + return operationId; + } /** * Sets the {@link DeviceManagementOperation#getId()}. * - * @param operationId The {@link DeviceManagementOperation#getId()}. + * @param operationId + * The {@link DeviceManagementOperation#getId()}. * @since 1.0.0 */ - void setOperationId(KapuaId operationId); + public void setOperationId(KapuaId operationId) { + this.operationId = operationId; + } /** * Gets the {@link Date} of when the notification has been sent to the platform. @@ -64,15 +88,20 @@ public interface ManagementOperationNotificationCreator extends KapuaEntityCreat */ @XmlElement(name = "sentOn") @XmlJavaTypeAdapter(DateXmlAdapter.class) - Date getSentOn(); + public Date getSentOn() { + return sentOn; + } /** * Sets the {@link Date} of when the notification has been sent to the platform. * - * @param sentOn The {@link Date} of when the notification has been sent to the platform. + * @param sentOn + * The {@link Date} of when the notification has been sent to the platform. * @since 1.0.0 */ - void setSentOn(Date sentOn); + public void setSentOn(Date sentOn) { + this.sentOn = sentOn; + } /** * Gets the {@link NotifyStatus} @@ -81,15 +110,20 @@ public interface ManagementOperationNotificationCreator extends KapuaEntityCreat * @since 1.0.0 */ @XmlElement(name = "status") - DeviceManagementOperationStatus getStatus(); + public DeviceManagementOperationStatus getStatus() { + return status; + } /** * Sets the {@link NotifyStatus} * - * @param status The {@link NotifyStatus} + * @param status + * The {@link NotifyStatus} * @since 1.0.0 */ - void setStatus(DeviceManagementOperationStatus status); + public void setStatus(DeviceManagementOperationStatus status) { + this.status = status; + } /** * Gets the {@link DeviceManagementOperation#getResource()} @@ -98,15 +132,20 @@ public interface ManagementOperationNotificationCreator extends KapuaEntityCreat * @since 1.0.0 */ @XmlElement(name = "resource") - String getResource(); + public String getResource() { + return resource; + } /** * Sets the {@link DeviceManagementOperation#getResource()} * - * @param resource The {@link DeviceManagementOperation#getResource()} + * @param resource + * The {@link DeviceManagementOperation#getResource()} * @since 1.0.0 */ - void setResource(String resource); + public void setResource(String resource) { + this.resource = resource; + } /** * Gets the progress percentage of the processing. @@ -115,15 +154,20 @@ public interface ManagementOperationNotificationCreator extends KapuaEntityCreat * @since 1.0.0 */ @XmlElement(name = "progress") - Integer getProgress(); + public Integer getProgress() { + return progress; + } /** * Sets the progress percentage of the processing. * - * @param progress The progress percentage of the processing. + * @param progress + * The progress percentage of the processing. * @since 1.0.0 */ - void setProgress(Integer progress); + public void setProgress(Integer progress) { + this.progress = progress; + } /** * Gets the detailed message related to the {@link NotifyStatus} @@ -131,13 +175,18 @@ public interface ManagementOperationNotificationCreator extends KapuaEntityCreat * @return The detailed message related to the {@link NotifyStatus} * @since 1.2.0 */ - String getMessage(); + public String getMessage() { + return message; + } /** * Sets the detailed message related to the {@link NotifyStatus} * - * @param message The detailed message related to the {@link NotifyStatus} + * @param message + * The detailed message related to the {@link NotifyStatus} * @since 1.2.0 */ - void setMessage(String message); + public void setMessage(String message) { + this.message = message; + } } diff --git a/service/device/management/registry/api/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/notification/ManagementOperationNotificationFactory.java b/service/device/management/registry/api/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/notification/ManagementOperationNotificationFactory.java index b1c814e7366..e21a5916055 100644 --- a/service/device/management/registry/api/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/notification/ManagementOperationNotificationFactory.java +++ b/service/device/management/registry/api/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/notification/ManagementOperationNotificationFactory.java @@ -20,6 +20,6 @@ * @see org.eclipse.kapua.model.KapuaEntityFactory * @since 1.0.0 */ -public interface ManagementOperationNotificationFactory extends KapuaEntityFactory { +public interface ManagementOperationNotificationFactory extends KapuaEntityFactory { } diff --git a/service/device/management/registry/api/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/notification/ManagementOperationNotificationListResult.java b/service/device/management/registry/api/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/notification/ManagementOperationNotificationListResult.java index bc28b4ce399..6060a034194 100644 --- a/service/device/management/registry/api/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/notification/ManagementOperationNotificationListResult.java +++ b/service/device/management/registry/api/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/notification/ManagementOperationNotificationListResult.java @@ -12,13 +12,13 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.registry.operation.notification; -import org.eclipse.kapua.model.query.KapuaListResult; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; +import org.eclipse.kapua.model.query.KapuaListResult; + /** * {@link ManagementOperationNotificationListResult} definition. * @@ -26,7 +26,7 @@ */ @XmlRootElement(name = "managementOperationNotificationListResult") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = ManagementOperationNotificationXmlRegistry.class, factoryMethod = "newManagementOperationNotificationListResult") -public interface ManagementOperationNotificationListResult extends KapuaListResult { +@XmlType +public class ManagementOperationNotificationListResult extends KapuaListResult { } diff --git a/service/device/management/registry/api/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/notification/ManagementOperationNotificationQuery.java b/service/device/management/registry/api/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/notification/ManagementOperationNotificationQuery.java index 6c2c03930c4..c3d3520a710 100644 --- a/service/device/management/registry/api/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/notification/ManagementOperationNotificationQuery.java +++ b/service/device/management/registry/api/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/notification/ManagementOperationNotificationQuery.java @@ -12,13 +12,16 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.registry.operation.notification; -import org.eclipse.kapua.model.query.KapuaQuery; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; +import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.query.KapuaQuery; +import org.eclipse.kapua.model.query.KapuaSortCriteria; +import org.eclipse.kapua.model.query.SortOrder; + /** * {@link ManagementOperationNotification} {@link KapuaQuery} definition. * @@ -27,6 +30,33 @@ */ @XmlRootElement(name = "query") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = ManagementOperationNotificationXmlRegistry.class, factoryMethod = "newQuery") -public interface ManagementOperationNotificationQuery extends KapuaQuery { +@XmlType +public class ManagementOperationNotificationQuery extends KapuaQuery { + + /** + * Constructor. + * + * @since 1.0.0 + */ + private ManagementOperationNotificationQuery() { + super(); + } + + /** + * Constructor. + * + * @param scopeId + * The {@link #getScopeId()}. + * @since 1.0.0 + */ + public ManagementOperationNotificationQuery(KapuaId scopeId) { + this(); + + setScopeId(scopeId); + } + + @Override + public KapuaSortCriteria getDefaultSortCriteria() { + return fieldSortCriteria(ManagementOperationNotificationAttributes.SENT_ON, SortOrder.ASCENDING); + } } diff --git a/service/device/management/registry/api/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/notification/ManagementOperationNotificationXmlRegistry.java b/service/device/management/registry/api/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/notification/ManagementOperationNotificationXmlRegistry.java index 8e9ad286ab4..5bbd900268c 100644 --- a/service/device/management/registry/api/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/notification/ManagementOperationNotificationXmlRegistry.java +++ b/service/device/management/registry/api/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/notification/ManagementOperationNotificationXmlRegistry.java @@ -12,10 +12,10 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.registry.operation.notification; -import org.eclipse.kapua.locator.KapuaLocator; - import javax.xml.bind.annotation.XmlRegistry; +import org.eclipse.kapua.locator.KapuaLocator; + /** * {@link ManagementOperationNotification} xml MANAGEMENT_OPERATION_NOTIFICATION_REGISTRY_FACTORY class * @@ -29,17 +29,4 @@ public class ManagementOperationNotificationXmlRegistry { ManagementOperationNotification newManagementOperationNotification() { return managementOperationNotificationFactory.newEntity(null); } - - ManagementOperationNotificationCreator newManagementOperationNotificationCreator() { - return managementOperationNotificationFactory.newCreator(null); - } - - - ManagementOperationNotificationListResult newManagementOperationNotificationListResult() { - return managementOperationNotificationFactory.newListResult(); - } - - ManagementOperationNotificationQuery newQuery() { - return managementOperationNotificationFactory.newQuery(null); - } } diff --git a/service/device/management/registry/internal/pom.xml b/service/device/management/registry/internal/pom.xml index 77a1f243a52..aebfeccf15a 100644 --- a/service/device/management/registry/internal/pom.xml +++ b/service/device/management/registry/internal/pom.xml @@ -19,7 +19,7 @@ kapua-device-management-registry org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-device-management-registry-internal diff --git a/service/device/management/registry/internal/src/main/java/org/eclipse/kapua/service/device/management/registry/manager/internal/DeviceManagementRegistryManagerServiceImpl.java b/service/device/management/registry/internal/src/main/java/org/eclipse/kapua/service/device/management/registry/manager/internal/DeviceManagementRegistryManagerServiceImpl.java index 4491da0e2fe..a65d7c16721 100644 --- a/service/device/management/registry/internal/src/main/java/org/eclipse/kapua/service/device/management/registry/manager/internal/DeviceManagementRegistryManagerServiceImpl.java +++ b/service/device/management/registry/internal/src/main/java/org/eclipse/kapua/service/device/management/registry/manager/internal/DeviceManagementRegistryManagerServiceImpl.java @@ -12,7 +12,11 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.registry.manager.internal; -import com.google.common.base.Strings; +import java.util.Date; + +import javax.inject.Inject; +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaEntityNotFoundException; import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.model.id.KapuaId; @@ -27,16 +31,13 @@ import org.eclipse.kapua.service.device.management.registry.operation.notification.ManagementOperationNotification; import org.eclipse.kapua.service.device.management.registry.operation.notification.ManagementOperationNotificationAttributes; import org.eclipse.kapua.service.device.management.registry.operation.notification.ManagementOperationNotificationCreator; -import org.eclipse.kapua.service.device.management.registry.operation.notification.ManagementOperationNotificationFactory; import org.eclipse.kapua.service.device.management.registry.operation.notification.ManagementOperationNotificationListResult; import org.eclipse.kapua.service.device.management.registry.operation.notification.ManagementOperationNotificationQuery; import org.eclipse.kapua.service.device.management.registry.operation.notification.ManagementOperationNotificationService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.inject.Inject; -import javax.inject.Singleton; -import java.util.Date; +import com.google.common.base.Strings; @Singleton public class DeviceManagementRegistryManagerServiceImpl implements DeviceManagementRegistryManagerService { @@ -45,22 +46,20 @@ public class DeviceManagementRegistryManagerServiceImpl implements DeviceManagem private final DeviceManagementOperationRegistryService deviceManagementOperationRegistryService; private final ManagementOperationNotificationService managementOperationNotificationService; - private final ManagementOperationNotificationFactory managementOperationNotificationFactory; private static final String LOG_MESSAGE_GENERATING = "Generating..."; @Inject public DeviceManagementRegistryManagerServiceImpl( DeviceManagementOperationRegistryService deviceManagementOperationRegistryService, - ManagementOperationNotificationService managementOperationNotificationService, - ManagementOperationNotificationFactory managementOperationNotificationFactory) { + ManagementOperationNotificationService managementOperationNotificationService) { this.deviceManagementOperationRegistryService = deviceManagementOperationRegistryService; this.managementOperationNotificationService = managementOperationNotificationService; - this.managementOperationNotificationFactory = managementOperationNotificationFactory; } @Override - public void processOperationNotification(KapuaId scopeId, KapuaId operationId, Date updateOn, String resource, NotifyStatus status, Integer progress, String message) throws ManagementOperationNotificationProcessingException { + public void processOperationNotification(KapuaId scopeId, KapuaId operationId, Date updateOn, String resource, NotifyStatus status, Integer progress, String message) + throws ManagementOperationNotificationProcessingException { try { storeManagementNotification(scopeId, operationId, updateOn, status, resource, progress, message); @@ -76,7 +75,6 @@ public void processOperationNotification(KapuaId scopeId, KapuaId operationId, D } } - public void processFailedNotification(KapuaId scopeId, KapuaId operationId, Date updateOn, String resource, String message) throws KapuaException { closeDeviceManagementOperation(scopeId, operationId, updateOn, NotifyStatus.FAILED, message); } @@ -103,7 +101,7 @@ public void processCompletedNotification(KapuaId scopeId, KapuaId operationId, D public void storeManagementNotification(KapuaId scopeId, KapuaId operationId, Date updateOn, NotifyStatus notifyStatus, String resource, Integer progress, String message) throws KapuaException { DeviceManagementOperation deviceManagementOperation = getDeviceManagementOperation(scopeId, operationId); - ManagementOperationNotificationCreator managementOperationNotificationCreator = managementOperationNotificationFactory.newCreator(scopeId); + ManagementOperationNotificationCreator managementOperationNotificationCreator = new ManagementOperationNotificationCreator(scopeId); managementOperationNotificationCreator.setOperationId(deviceManagementOperation.getId()); managementOperationNotificationCreator.setSentOn(updateOn); managementOperationNotificationCreator.setStatus(DeviceManagementOperationStatus.readFrom(notifyStatus)); @@ -148,7 +146,7 @@ public void closeDeviceManagementOperation(KapuaId scopeId, KapuaId operationId, } while (failed); { - ManagementOperationNotificationQuery query = managementOperationNotificationFactory.newQuery(scopeId); + ManagementOperationNotificationQuery query = new ManagementOperationNotificationQuery(scopeId); query.setPredicate(query.attributePredicate(ManagementOperationNotificationAttributes.OPERATION_ID, deviceManagementOperation.getId())); query.setSortCriteria(query.fieldSortCriteria(ManagementOperationNotificationAttributes.SENT_ON, SortOrder.ASCENDING)); diff --git a/service/device/management/registry/internal/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/internal/DeviceManagementOperationCreatorImpl.java b/service/device/management/registry/internal/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/internal/DeviceManagementOperationCreatorImpl.java deleted file mode 100644 index 1c47f3cbd93..00000000000 --- a/service/device/management/registry/internal/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/internal/DeviceManagementOperationCreatorImpl.java +++ /dev/null @@ -1,126 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2017, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.registry.operation.internal; - -import org.eclipse.kapua.commons.model.AbstractKapuaEntityCreator; -import org.eclipse.kapua.commons.model.id.KapuaEid; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.device.management.message.KapuaMethod; -import org.eclipse.kapua.service.device.management.message.notification.NotifyStatus; -import org.eclipse.kapua.service.device.management.registry.operation.DeviceManagementOperation; -import org.eclipse.kapua.service.device.management.registry.operation.DeviceManagementOperationCreator; -import org.eclipse.kapua.service.device.management.registry.operation.DeviceManagementOperationProperty; - -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -public class DeviceManagementOperationCreatorImpl extends AbstractKapuaEntityCreator implements DeviceManagementOperationCreator { - - private Date startedOn; - private KapuaEid deviceId; - private KapuaEid operationId; - private String appId; - private KapuaMethod action; - private String resource; - private NotifyStatus status; - private List inputProperties; - - public DeviceManagementOperationCreatorImpl(KapuaId scopeId) { - super(scopeId); - } - - @Override - public Date getStartedOn() { - return startedOn; - } - - @Override - public void setStartedOn(Date startedOn) { - this.startedOn = startedOn; - } - - @Override - public KapuaEid getDeviceId() { - return deviceId; - } - - @Override - public void setDeviceId(KapuaId deviceId) { - this.deviceId = KapuaEid.parseKapuaId(deviceId); - } - - @Override - public KapuaEid getOperationId() { - return operationId; - } - - @Override - public void setOperationId(KapuaId operationId) { - this.operationId = KapuaEid.parseKapuaId(operationId); - } - - @Override - public String getAppId() { - return appId; - } - - @Override - public void setAppId(String appId) { - this.appId = appId; - } - - @Override - public KapuaMethod getAction() { - return action.normalizeAction(); - } - - @Override - public void setAction(KapuaMethod action) { - this.action = action.normalizeAction(); - } - - @Override - public String getResource() { - return resource; - } - - @Override - public void setResource(String resource) { - this.resource = resource; - } - - @Override - public NotifyStatus getStatus() { - return status; - } - - @Override - public void setStatus(NotifyStatus status) { - this.status = status; - } - - @Override - public List getInputProperties() { - if (inputProperties == null) { - inputProperties = new ArrayList<>(); - } - - return inputProperties; - } - - @Override - public void setInputProperties(List inputProperties) { - this.inputProperties = inputProperties; - } -} diff --git a/service/device/management/registry/internal/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/internal/DeviceManagementOperationFactoryImpl.java b/service/device/management/registry/internal/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/internal/DeviceManagementOperationFactoryImpl.java index 3f1802d340d..26f703a8dc1 100644 --- a/service/device/management/registry/internal/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/internal/DeviceManagementOperationFactoryImpl.java +++ b/service/device/management/registry/internal/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/internal/DeviceManagementOperationFactoryImpl.java @@ -12,16 +12,13 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.registry.operation.internal; +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaEntityCloneException; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.device.management.registry.operation.DeviceManagementOperation; -import org.eclipse.kapua.service.device.management.registry.operation.DeviceManagementOperationCreator; import org.eclipse.kapua.service.device.management.registry.operation.DeviceManagementOperationFactory; -import org.eclipse.kapua.service.device.management.registry.operation.DeviceManagementOperationListResult; import org.eclipse.kapua.service.device.management.registry.operation.DeviceManagementOperationProperty; -import org.eclipse.kapua.service.device.management.registry.operation.DeviceManagementOperationQuery; - -import javax.inject.Singleton; /** * {@link DeviceManagementOperationFactory} implementation @@ -36,21 +33,6 @@ public DeviceManagementOperation newEntity(KapuaId scopeId) { return new DeviceManagementOperationImpl(scopeId); } - @Override - public DeviceManagementOperationCreator newCreator(KapuaId scopeId) { - return new DeviceManagementOperationCreatorImpl(scopeId); - } - - @Override - public DeviceManagementOperationQuery newQuery(KapuaId scopeId) { - return new DeviceManagementOperationQueryImpl(scopeId); - } - - @Override - public DeviceManagementOperationListResult newListResult() { - return new DeviceManagementOperationListResultImpl(); - } - @Override public DeviceManagementOperationProperty newStepProperty(String name, String propertyType, String propertyValue) { return new DeviceManagementOperationPropertyImpl(name, propertyType, propertyValue); diff --git a/service/device/management/registry/internal/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/internal/DeviceManagementOperationListResultImpl.java b/service/device/management/registry/internal/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/internal/DeviceManagementOperationListResultImpl.java deleted file mode 100644 index 70231c167da..00000000000 --- a/service/device/management/registry/internal/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/internal/DeviceManagementOperationListResultImpl.java +++ /dev/null @@ -1,26 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2017, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.registry.operation.internal; - -import org.eclipse.kapua.commons.model.query.KapuaListResultImpl; -import org.eclipse.kapua.service.device.management.registry.operation.DeviceManagementOperation; -import org.eclipse.kapua.service.device.management.registry.operation.DeviceManagementOperationListResult; - -/** - * {@link DeviceManagementOperationListResultImpl} definition. - * - * @since 1.0.0 - */ -public class DeviceManagementOperationListResultImpl extends KapuaListResultImpl implements DeviceManagementOperationListResult { - -} diff --git a/service/device/management/registry/internal/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/internal/DeviceManagementOperationQueryImpl.java b/service/device/management/registry/internal/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/internal/DeviceManagementOperationQueryImpl.java deleted file mode 100644 index cbc9aa3054d..00000000000 --- a/service/device/management/registry/internal/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/internal/DeviceManagementOperationQueryImpl.java +++ /dev/null @@ -1,54 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2017, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.registry.operation.internal; - -import org.eclipse.kapua.commons.model.query.AbstractKapuaQuery; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.model.query.KapuaSortCriteria; -import org.eclipse.kapua.model.query.SortOrder; -import org.eclipse.kapua.service.device.management.registry.operation.DeviceManagementOperationAttributes; -import org.eclipse.kapua.service.device.management.registry.operation.DeviceManagementOperationQuery; - -/** - * {@link DeviceManagementOperationQuery} implementation. - * - * @since 1.1.0 - */ -public class DeviceManagementOperationQueryImpl extends AbstractKapuaQuery implements DeviceManagementOperationQuery { - - /** - * Constructor. - * - * @since 1.1.0 - */ - private DeviceManagementOperationQueryImpl() { - super(); - } - - /** - * Constructor. - * - * @param scopeId The {@link #getScopeId()}. - * @since 1.1.0 - */ - public DeviceManagementOperationQueryImpl(KapuaId scopeId) { - this(); - - setScopeId(scopeId); - } - - @Override - public KapuaSortCriteria getDefaultSortCriteria() { - return fieldSortCriteria(DeviceManagementOperationAttributes.STARTED_ON, SortOrder.ASCENDING); - } -} diff --git a/service/device/management/registry/internal/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/internal/DeviceManagementOperationRegistryServiceImpl.java b/service/device/management/registry/internal/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/internal/DeviceManagementOperationRegistryServiceImpl.java index 497af251b39..4846a29db87 100644 --- a/service/device/management/registry/internal/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/internal/DeviceManagementOperationRegistryServiceImpl.java +++ b/service/device/management/registry/internal/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/internal/DeviceManagementOperationRegistryServiceImpl.java @@ -12,6 +12,11 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.registry.operation.internal; +import java.util.Date; + +import javax.inject.Inject; +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaEntityNotFoundException; import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.commons.model.domains.Domains; @@ -20,7 +25,7 @@ import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; +import org.eclipse.kapua.service.authorization.permission.Permission; import org.eclipse.kapua.service.device.management.message.notification.NotifyStatus; import org.eclipse.kapua.service.device.management.registry.operation.DeviceManagementOperation; import org.eclipse.kapua.service.device.management.registry.operation.DeviceManagementOperationCreator; @@ -32,16 +37,11 @@ import org.eclipse.kapua.service.device.registry.DeviceRepository; import org.eclipse.kapua.storage.TxManager; -import javax.inject.Inject; -import javax.inject.Singleton; -import java.util.Date; - @Singleton public class DeviceManagementOperationRegistryServiceImpl implements DeviceManagementOperationRegistryService { private final AuthorizationService authorizationService; - private final PermissionFactory permissionFactory; private final DeviceRepository deviceRepository; private final TxManager txManager; private final DeviceManagementOperationRepository repository; @@ -50,13 +50,11 @@ public class DeviceManagementOperationRegistryServiceImpl @Inject public DeviceManagementOperationRegistryServiceImpl( AuthorizationService authorizationService, - PermissionFactory permissionFactory, DeviceRepository deviceRepository, TxManager txManager, DeviceManagementOperationRepository repository, DeviceManagementOperationFactory entityFactory) { this.authorizationService = authorizationService; - this.permissionFactory = permissionFactory; this.deviceRepository = deviceRepository; this.txManager = txManager; this.repository = repository; @@ -75,7 +73,7 @@ public DeviceManagementOperation create(DeviceManagementOperationCreator creator ArgumentValidator.notNull(creator.getAppId(), "creator.appId"); ArgumentValidator.notNull(creator.getAction(), "creator.action"); // Check access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE_MANAGEMENT_REGISTRY, Actions.write, null)); + authorizationService.checkPermission(new Permission(Domains.DEVICE_MANAGEMENT_REGISTRY, Actions.write, null)); return txManager.execute(tx -> { // Check device existence @@ -111,7 +109,7 @@ public DeviceManagementOperation update(DeviceManagementOperation entity) throws ArgumentValidator.notNull(entity.getAppId(), "deviceManagementOperation.appId"); ArgumentValidator.notNull(entity.getAction(), "deviceManagementOperation.action"); // Check access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE_MANAGEMENT_REGISTRY, Actions.write, null)); + authorizationService.checkPermission(new Permission(Domains.DEVICE_MANAGEMENT_REGISTRY, Actions.write, null)); return txManager.execute(tx -> { // Check device existence @@ -133,7 +131,7 @@ public DeviceManagementOperation find(KapuaId scopeId, KapuaId entityId) throws ArgumentValidator.notNull(scopeId, "scopeId"); ArgumentValidator.notNull(entityId, "deviceManagementOperationId"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE_MANAGEMENT_REGISTRY, Actions.read, scopeId)); + authorizationService.checkPermission(new Permission(Domains.DEVICE_MANAGEMENT_REGISTRY, Actions.read, scopeId)); // Do find return txManager.execute(tx -> repository.find(tx, scopeId, entityId)) .orElse(null); @@ -147,7 +145,7 @@ public DeviceManagementOperation findByOperationId(KapuaId scopeId, KapuaId oper ArgumentValidator.notNull(operationId, "operationId"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE_MANAGEMENT_REGISTRY, Actions.read, scopeId)); + authorizationService.checkPermission(new Permission(Domains.DEVICE_MANAGEMENT_REGISTRY, Actions.read, scopeId)); // Do find return txManager.execute(tx -> repository.findByOperationId(tx, scopeId, operationId)) .orElse(null); @@ -158,7 +156,7 @@ public DeviceManagementOperationListResult query(KapuaQuery query) throws KapuaE // Argument Validation ArgumentValidator.notNull(query, "query"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE_MANAGEMENT_REGISTRY, Actions.read, query.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.DEVICE_MANAGEMENT_REGISTRY, Actions.read, query.getScopeId())); // Do query return txManager.execute(tx -> repository.query(tx, query)); } @@ -179,7 +177,7 @@ public long count(KapuaQuery query) throws KapuaException { // Argument Validation ArgumentValidator.notNull(query, "query"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE_MANAGEMENT_REGISTRY, Actions.read, query.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.DEVICE_MANAGEMENT_REGISTRY, Actions.read, query.getScopeId())); // Do count return txManager.execute(tx -> repository.count(tx, query)); } @@ -191,7 +189,7 @@ public void delete(KapuaId scopeId, KapuaId entityId) throws KapuaException { ArgumentValidator.notNull(entityId, "deviceManagementOperationId"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE_MANAGEMENT_REGISTRY, Actions.delete, scopeId)); + authorizationService.checkPermission(new Permission(Domains.DEVICE_MANAGEMENT_REGISTRY, Actions.delete, scopeId)); // Do delete txManager.execute(tx -> repository.delete(tx, scopeId, entityId)); diff --git a/service/device/management/registry/internal/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/internal/DeviceManagementOperationRepositoryImplJpaRepository.java b/service/device/management/registry/internal/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/internal/DeviceManagementOperationRepositoryImplJpaRepository.java index 0912d291a5a..32914d8fbfd 100644 --- a/service/device/management/registry/internal/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/internal/DeviceManagementOperationRepositoryImplJpaRepository.java +++ b/service/device/management/registry/internal/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/internal/DeviceManagementOperationRepositoryImplJpaRepository.java @@ -12,6 +12,8 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.registry.operation.internal; +import java.util.Optional; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.commons.jpa.KapuaJpaRepositoryConfiguration; import org.eclipse.kapua.commons.jpa.KapuaUpdatableEntityJpaRepository; @@ -21,13 +23,12 @@ import org.eclipse.kapua.service.device.management.registry.operation.DeviceManagementOperationRepository; import org.eclipse.kapua.storage.TxContext; -import java.util.Optional; - public class DeviceManagementOperationRepositoryImplJpaRepository extends KapuaUpdatableEntityJpaRepository implements DeviceManagementOperationRepository { + public DeviceManagementOperationRepositoryImplJpaRepository(KapuaJpaRepositoryConfiguration jpaRepoConfig) { - super(DeviceManagementOperationImpl.class, DeviceManagementOperation.TYPE, () -> new DeviceManagementOperationListResultImpl(), jpaRepoConfig); + super(DeviceManagementOperationImpl.class, DeviceManagementOperation.TYPE, () -> new DeviceManagementOperationListResult(), jpaRepoConfig); } @Override diff --git a/service/device/management/registry/internal/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/internal/DeviceManagementRegistryOperationModule.java b/service/device/management/registry/internal/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/internal/DeviceManagementRegistryOperationModule.java index 5b25ca4fd4f..3fb99dc939c 100644 --- a/service/device/management/registry/internal/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/internal/DeviceManagementRegistryOperationModule.java +++ b/service/device/management/registry/internal/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/internal/DeviceManagementRegistryOperationModule.java @@ -12,20 +12,21 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.registry.operation.internal; -import com.google.inject.Provides; +import javax.inject.Singleton; + import org.eclipse.kapua.commons.core.AbstractKapuaModule; import org.eclipse.kapua.commons.jpa.KapuaJpaRepositoryConfiguration; import org.eclipse.kapua.commons.jpa.KapuaJpaTxManagerFactory; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; import org.eclipse.kapua.service.device.management.registry.operation.DeviceManagementOperationFactory; import org.eclipse.kapua.service.device.management.registry.operation.DeviceManagementOperationRegistryService; import org.eclipse.kapua.service.device.management.registry.operation.DeviceManagementOperationRepository; import org.eclipse.kapua.service.device.registry.DeviceRepository; -import javax.inject.Singleton; +import com.google.inject.Provides; public class DeviceManagementRegistryOperationModule extends AbstractKapuaModule { + @Override protected void configureModule() { bind(DeviceManagementOperationFactory.class).to(DeviceManagementOperationFactoryImpl.class); @@ -35,14 +36,12 @@ protected void configureModule() { @Singleton DeviceManagementOperationRegistryService deviceManagementOperationRegistryService( AuthorizationService authorizationService, - PermissionFactory permissionFactory, DeviceRepository deviceRepository, DeviceManagementOperationRepository repository, DeviceManagementOperationFactory entityFactory, KapuaJpaTxManagerFactory jpaTxManagerFactory) { return new DeviceManagementOperationRegistryServiceImpl( authorizationService, - permissionFactory, deviceRepository, jpaTxManagerFactory.create("kapua-device_management_operation_registry"), repository, diff --git a/service/device/management/registry/internal/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/notification/internal/DeviceManagementRegistryNotificationModule.java b/service/device/management/registry/internal/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/notification/internal/DeviceManagementRegistryNotificationModule.java index 7488732846c..bfe7671f10e 100644 --- a/service/device/management/registry/internal/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/notification/internal/DeviceManagementRegistryNotificationModule.java +++ b/service/device/management/registry/internal/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/notification/internal/DeviceManagementRegistryNotificationModule.java @@ -12,20 +12,21 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.registry.operation.notification.internal; -import com.google.inject.Provides; +import javax.inject.Singleton; + import org.eclipse.kapua.commons.core.AbstractKapuaModule; import org.eclipse.kapua.commons.jpa.KapuaJpaRepositoryConfiguration; import org.eclipse.kapua.commons.jpa.KapuaJpaTxManagerFactory; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; import org.eclipse.kapua.service.device.management.registry.operation.DeviceManagementOperationRepository; import org.eclipse.kapua.service.device.management.registry.operation.notification.ManagementOperationNotificationFactory; import org.eclipse.kapua.service.device.management.registry.operation.notification.ManagementOperationNotificationRepository; import org.eclipse.kapua.service.device.management.registry.operation.notification.ManagementOperationNotificationService; -import javax.inject.Singleton; +import com.google.inject.Provides; public class DeviceManagementRegistryNotificationModule extends AbstractKapuaModule { + @Override protected void configureModule() { bind(ManagementOperationNotificationFactory.class).to(ManagementOperationNotificationFactoryImpl.class); @@ -35,14 +36,12 @@ protected void configureModule() { @Singleton ManagementOperationNotificationService managementOperationNotificationService( AuthorizationService authorizationService, - PermissionFactory permissionFactory, ManagementOperationNotificationFactory entityFactory, ManagementOperationNotificationRepository repository, DeviceManagementOperationRepository deviceManagementOperationRepository, KapuaJpaTxManagerFactory jpaTxManagerFactory) { return new ManagementOperationNotificationServiceImpl( authorizationService, - permissionFactory, entityFactory, jpaTxManagerFactory.create("kapua-device_management_operation_registry"), repository, diff --git a/service/device/management/registry/internal/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/notification/internal/ManagementOperationNotificationCreatorImpl.java b/service/device/management/registry/internal/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/notification/internal/ManagementOperationNotificationCreatorImpl.java deleted file mode 100644 index 390b1285293..00000000000 --- a/service/device/management/registry/internal/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/notification/internal/ManagementOperationNotificationCreatorImpl.java +++ /dev/null @@ -1,95 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2017, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.registry.operation.notification.internal; - -import org.eclipse.kapua.commons.model.AbstractKapuaEntityCreator; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.device.management.registry.operation.DeviceManagementOperationStatus; -import org.eclipse.kapua.service.device.management.registry.operation.notification.ManagementOperationNotification; -import org.eclipse.kapua.service.device.management.registry.operation.notification.ManagementOperationNotificationCreator; - -import java.util.Date; - -public class ManagementOperationNotificationCreatorImpl extends AbstractKapuaEntityCreator implements ManagementOperationNotificationCreator { - - private KapuaId operationId; - private Date sentOn; - private DeviceManagementOperationStatus status; - private String resource; - private Integer progress; - private String message; - - public ManagementOperationNotificationCreatorImpl(KapuaId scopeId) { - super(scopeId); - } - - @Override - public KapuaId getOperationId() { - return operationId; - } - - @Override - public void setOperationId(KapuaId operationId) { - this.operationId = operationId; - } - - @Override - public Date getSentOn() { - return sentOn; - } - - @Override - public void setSentOn(Date sentOn) { - this.sentOn = sentOn; - } - - @Override - public DeviceManagementOperationStatus getStatus() { - return status; - } - - @Override - public void setStatus(DeviceManagementOperationStatus status) { - this.status = status; - } - - @Override - public String getResource() { - return resource; - } - - @Override - public void setResource(String resource) { - this.resource = resource; - } - - @Override - public Integer getProgress() { - return progress; - } - - @Override - public void setProgress(Integer progress) { - this.progress = progress; - } - - @Override - public String getMessage() { - return message; - } - - @Override - public void setMessage(String message) { - this.message = message; - } -} diff --git a/service/device/management/registry/internal/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/notification/internal/ManagementOperationNotificationFactoryImpl.java b/service/device/management/registry/internal/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/notification/internal/ManagementOperationNotificationFactoryImpl.java index a6303dc87c9..d7ec4a6efc4 100644 --- a/service/device/management/registry/internal/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/notification/internal/ManagementOperationNotificationFactoryImpl.java +++ b/service/device/management/registry/internal/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/notification/internal/ManagementOperationNotificationFactoryImpl.java @@ -12,14 +12,11 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.registry.operation.notification.internal; +import javax.inject.Singleton; + import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.device.management.registry.operation.notification.ManagementOperationNotification; -import org.eclipse.kapua.service.device.management.registry.operation.notification.ManagementOperationNotificationCreator; import org.eclipse.kapua.service.device.management.registry.operation.notification.ManagementOperationNotificationFactory; -import org.eclipse.kapua.service.device.management.registry.operation.notification.ManagementOperationNotificationListResult; -import org.eclipse.kapua.service.device.management.registry.operation.notification.ManagementOperationNotificationQuery; - -import javax.inject.Singleton; /** * {@link ManagementOperationNotificationFactory} implementation. @@ -34,21 +31,6 @@ public ManagementOperationNotification newEntity(KapuaId scopeId) { return new ManagementOperationNotificationImpl(scopeId); } - @Override - public ManagementOperationNotificationCreator newCreator(KapuaId scopeId) { - return new ManagementOperationNotificationCreatorImpl(scopeId); - } - - @Override - public ManagementOperationNotificationQuery newQuery(KapuaId scopeId) { - return new ManagementOperationNotificationQueryImpl(scopeId); - } - - @Override - public ManagementOperationNotificationListResult newListResult() { - return new ManagementOperationNotificationListResultImpl(); - } - @Override public ManagementOperationNotification clone(ManagementOperationNotification managementOperationNotification) { return new ManagementOperationNotificationImpl(managementOperationNotification); diff --git a/service/device/management/registry/internal/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/notification/internal/ManagementOperationNotificationImplJpaRepository.java b/service/device/management/registry/internal/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/notification/internal/ManagementOperationNotificationImplJpaRepository.java index 0851913ef21..48e3e245194 100644 --- a/service/device/management/registry/internal/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/notification/internal/ManagementOperationNotificationImplJpaRepository.java +++ b/service/device/management/registry/internal/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/notification/internal/ManagementOperationNotificationImplJpaRepository.java @@ -21,7 +21,8 @@ public class ManagementOperationNotificationImplJpaRepository extends KapuaEntityJpaRepository implements ManagementOperationNotificationRepository { + public ManagementOperationNotificationImplJpaRepository(KapuaJpaRepositoryConfiguration configuration) { - super(ManagementOperationNotificationImpl.class, ManagementOperationNotification.TYPE, () -> new ManagementOperationNotificationListResultImpl(), configuration); + super(ManagementOperationNotificationImpl.class, ManagementOperationNotification.TYPE, () -> new ManagementOperationNotificationListResult(), configuration); } } diff --git a/service/device/management/registry/internal/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/notification/internal/ManagementOperationNotificationListResultImpl.java b/service/device/management/registry/internal/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/notification/internal/ManagementOperationNotificationListResultImpl.java deleted file mode 100644 index 55063328ae2..00000000000 --- a/service/device/management/registry/internal/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/notification/internal/ManagementOperationNotificationListResultImpl.java +++ /dev/null @@ -1,26 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2017, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.registry.operation.notification.internal; - -import org.eclipse.kapua.commons.model.query.KapuaListResultImpl; -import org.eclipse.kapua.service.device.management.registry.operation.notification.ManagementOperationNotification; -import org.eclipse.kapua.service.device.management.registry.operation.notification.ManagementOperationNotificationListResult; - -/** - * {@link ManagementOperationNotificationListResultImpl} definition. - * - * @since 1.0.0 - */ -public class ManagementOperationNotificationListResultImpl extends KapuaListResultImpl implements ManagementOperationNotificationListResult { - -} diff --git a/service/device/management/registry/internal/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/notification/internal/ManagementOperationNotificationQueryImpl.java b/service/device/management/registry/internal/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/notification/internal/ManagementOperationNotificationQueryImpl.java deleted file mode 100644 index eb34a1c1bfb..00000000000 --- a/service/device/management/registry/internal/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/notification/internal/ManagementOperationNotificationQueryImpl.java +++ /dev/null @@ -1,54 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2017, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.management.registry.operation.notification.internal; - -import org.eclipse.kapua.commons.model.query.AbstractKapuaQuery; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.model.query.KapuaSortCriteria; -import org.eclipse.kapua.model.query.SortOrder; -import org.eclipse.kapua.service.device.management.registry.operation.notification.ManagementOperationNotificationAttributes; -import org.eclipse.kapua.service.device.management.registry.operation.notification.ManagementOperationNotificationQuery; - -/** - * {@link ManagementOperationNotificationQuery} implementation. - * - * @since 1.0.0 - */ -public class ManagementOperationNotificationQueryImpl extends AbstractKapuaQuery implements ManagementOperationNotificationQuery { - - /** - * Constructor. - * - * @since 1.0.0 - */ - private ManagementOperationNotificationQueryImpl() { - super(); - } - - /** - * Constructor. - * - * @param scopeId The {@link #getScopeId()}. - * @since 1.0.0 - */ - public ManagementOperationNotificationQueryImpl(KapuaId scopeId) { - this(); - - setScopeId(scopeId); - } - - @Override - public KapuaSortCriteria getDefaultSortCriteria() { - return fieldSortCriteria(ManagementOperationNotificationAttributes.SENT_ON, SortOrder.ASCENDING); - } -} diff --git a/service/device/management/registry/internal/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/notification/internal/ManagementOperationNotificationServiceImpl.java b/service/device/management/registry/internal/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/notification/internal/ManagementOperationNotificationServiceImpl.java index 3fed314c565..4f90bb251a8 100644 --- a/service/device/management/registry/internal/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/notification/internal/ManagementOperationNotificationServiceImpl.java +++ b/service/device/management/registry/internal/src/main/java/org/eclipse/kapua/service/device/management/registry/operation/notification/internal/ManagementOperationNotificationServiceImpl.java @@ -12,6 +12,9 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.registry.operation.notification.internal; +import javax.inject.Inject; +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaEntityNotFoundException; import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.commons.model.domains.Domains; @@ -20,7 +23,7 @@ import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; +import org.eclipse.kapua.service.authorization.permission.Permission; import org.eclipse.kapua.service.device.management.registry.operation.DeviceManagementOperation; import org.eclipse.kapua.service.device.management.registry.operation.DeviceManagementOperationRepository; import org.eclipse.kapua.service.device.management.registry.operation.notification.ManagementOperationNotification; @@ -31,14 +34,10 @@ import org.eclipse.kapua.service.device.management.registry.operation.notification.ManagementOperationNotificationService; import org.eclipse.kapua.storage.TxManager; -import javax.inject.Inject; -import javax.inject.Singleton; - @Singleton public class ManagementOperationNotificationServiceImpl implements ManagementOperationNotificationService { private final AuthorizationService authorizationService; - private final PermissionFactory permissionFactory; private final ManagementOperationNotificationFactory entityFactory; private final TxManager txManager; private final ManagementOperationNotificationRepository repository; @@ -47,13 +46,11 @@ public class ManagementOperationNotificationServiceImpl implements ManagementOpe @Inject public ManagementOperationNotificationServiceImpl( AuthorizationService authorizationService, - PermissionFactory permissionFactory, ManagementOperationNotificationFactory entityFactory, TxManager txManager, ManagementOperationNotificationRepository repository, DeviceManagementOperationRepository deviceManagementOperationRepository) { this.authorizationService = authorizationService; - this.permissionFactory = permissionFactory; this.entityFactory = entityFactory; this.txManager = txManager; this.repository = repository; @@ -71,7 +68,7 @@ public ManagementOperationNotification create(ManagementOperationNotificationCre ArgumentValidator.notNull(creator.getProgress(), "managementOperationNotificationCreator.progress"); ArgumentValidator.notNegative(creator.getProgress(), "managementOperationNotificationCreator.progress"); // Check access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE_MANAGEMENT_REGISTRY, Actions.write, null)); + authorizationService.checkPermission(new Permission(Domains.DEVICE_MANAGEMENT_REGISTRY, Actions.write, null)); return txManager.execute(tx -> { // Check operation existence @@ -97,7 +94,7 @@ public ManagementOperationNotification find(KapuaId scopeId, KapuaId entityId) t ArgumentValidator.notNull(scopeId, "scopeId"); ArgumentValidator.notNull(entityId, "managementOperationNotificationId"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE_MANAGEMENT_REGISTRY, Actions.read, scopeId)); + authorizationService.checkPermission(new Permission(Domains.DEVICE_MANAGEMENT_REGISTRY, Actions.read, scopeId)); // Do find return txManager.execute(tx -> repository.find(tx, scopeId, entityId)) .orElse(null); @@ -108,7 +105,7 @@ public ManagementOperationNotificationListResult query(KapuaQuery query) throws // Argument Validation ArgumentValidator.notNull(query, "query"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE_MANAGEMENT_REGISTRY, Actions.read, query.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.DEVICE_MANAGEMENT_REGISTRY, Actions.read, query.getScopeId())); // Do query return txManager.execute(tx -> repository.query(tx, query)); } @@ -118,7 +115,7 @@ public long count(KapuaQuery query) throws KapuaException { // Argument Validation ArgumentValidator.notNull(query, "query"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE_MANAGEMENT_REGISTRY, Actions.read, query.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.DEVICE_MANAGEMENT_REGISTRY, Actions.read, query.getScopeId())); // Do count return txManager.execute(tx -> repository.count(tx, query)); } @@ -130,7 +127,7 @@ public void delete(KapuaId scopeId, KapuaId entityId) throws KapuaException { ArgumentValidator.notNull(entityId, "managementOperationNotificationId"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE_MANAGEMENT_REGISTRY, Actions.delete, null)); + authorizationService.checkPermission(new Permission(Domains.DEVICE_MANAGEMENT_REGISTRY, Actions.delete, null)); // Do delete txManager.execute(tx -> repository.delete(tx, scopeId, entityId)); diff --git a/service/device/management/registry/pom.xml b/service/device/management/registry/pom.xml index a0e4a1cbdd3..f9eda1a7aba 100644 --- a/service/device/management/registry/pom.xml +++ b/service/device/management/registry/pom.xml @@ -19,7 +19,7 @@ kapua-device-management org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT pom diff --git a/service/device/management/request/api/pom.xml b/service/device/management/request/api/pom.xml index e8a6a98be0b..94412f2fcb3 100644 --- a/service/device/management/request/api/pom.xml +++ b/service/device/management/request/api/pom.xml @@ -18,7 +18,7 @@ kapua-device-management-request org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-device-management-request-api diff --git a/service/device/management/request/internal/pom.xml b/service/device/management/request/internal/pom.xml index 4da3264c8b5..f6aea23cf2c 100644 --- a/service/device/management/request/internal/pom.xml +++ b/service/device/management/request/internal/pom.xml @@ -19,7 +19,7 @@ kapua-device-management-request org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-device-management-request-internal diff --git a/service/device/management/request/internal/src/main/java/org/eclipse/kapua/service/device/management/request/internal/DeviceManagementRequestModule.java b/service/device/management/request/internal/src/main/java/org/eclipse/kapua/service/device/management/request/internal/DeviceManagementRequestModule.java index dcef1639d6c..ec8332ca9e5 100644 --- a/service/device/management/request/internal/src/main/java/org/eclipse/kapua/service/device/management/request/internal/DeviceManagementRequestModule.java +++ b/service/device/management/request/internal/src/main/java/org/eclipse/kapua/service/device/management/request/internal/DeviceManagementRequestModule.java @@ -19,7 +19,6 @@ import org.eclipse.kapua.commons.core.SimpleJaxbClassProvider; import org.eclipse.kapua.commons.jpa.KapuaJpaTxManagerFactory; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; import org.eclipse.kapua.service.device.management.request.DeviceRequestManagementService; import org.eclipse.kapua.service.device.management.request.GenericRequestFactory; import org.eclipse.kapua.service.device.management.request.message.request.GenericRequestChannel; @@ -55,7 +54,6 @@ protected void configureModule() { @Inject DeviceRequestManagementService deviceRequestManagementService( AuthorizationService authorizationService, - PermissionFactory permissionFactory, DeviceEventService deviceEventService, DeviceEventFactory deviceEventFactory, DeviceRegistryService deviceRegistryService, @@ -65,7 +63,6 @@ DeviceRequestManagementService deviceRequestManagementService( return new DeviceRequestManagementServiceImpl( jpaTxManagerFactory.create("kapua-device_management_operation_registry"), authorizationService, - permissionFactory, deviceEventService, deviceEventFactory, deviceRegistryService, diff --git a/service/device/management/request/internal/src/main/java/org/eclipse/kapua/service/device/management/request/internal/DeviceRequestManagementServiceImpl.java b/service/device/management/request/internal/src/main/java/org/eclipse/kapua/service/device/management/request/internal/DeviceRequestManagementServiceImpl.java index 170292467a1..0b36280140e 100644 --- a/service/device/management/request/internal/src/main/java/org/eclipse/kapua/service/device/management/request/internal/DeviceRequestManagementServiceImpl.java +++ b/service/device/management/request/internal/src/main/java/org/eclipse/kapua/service/device/management/request/internal/DeviceRequestManagementServiceImpl.java @@ -13,13 +13,17 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.management.request.internal; +import java.util.Date; + +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.commons.model.domains.Domains; import org.eclipse.kapua.commons.util.ArgumentValidator; import org.eclipse.kapua.model.domain.Actions; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; +import org.eclipse.kapua.service.authorization.permission.Permission; import org.eclipse.kapua.service.device.management.commons.AbstractDeviceManagementTransactionalServiceImpl; import org.eclipse.kapua.service.device.management.commons.call.DeviceCallBuilder; import org.eclipse.kapua.service.device.management.exception.DeviceManagementRequestBadMethodException; @@ -36,9 +40,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.inject.Singleton; -import java.util.Date; - /** * {@link DeviceRequestManagementService} implementation. * @@ -54,14 +55,12 @@ public class DeviceRequestManagementServiceImpl extends AbstractDeviceManagement public DeviceRequestManagementServiceImpl( TxManager txManager, AuthorizationService authorizationService, - PermissionFactory permissionFactory, DeviceEventService deviceEventService, DeviceEventFactory deviceEventFactory, DeviceRegistryService deviceRegistryService, GenericRequestFactory genericRequestFactory) { super(txManager, authorizationService, - permissionFactory, deviceEventService, deviceEventFactory, deviceRegistryService); @@ -80,24 +79,24 @@ public GenericResponseMessage exec(KapuaId scopeId, KapuaId deviceId, GenericReq // Check Access Actions action; switch (requestInput.getChannel().getMethod()) { - case EXECUTE: - action = Actions.execute; - break; - case READ: - case OPTIONS: - action = Actions.read; - break; - case CREATE: - case WRITE: - action = Actions.write; - break; - case DELETE: - action = Actions.delete; - break; - default: - throw new DeviceManagementRequestBadMethodException(requestInput.getChannel().getMethod()); + case EXECUTE: + action = Actions.execute; + break; + case READ: + case OPTIONS: + action = Actions.read; + break; + case CREATE: + case WRITE: + action = Actions.write; + break; + case DELETE: + action = Actions.delete; + break; + default: + throw new DeviceManagementRequestBadMethodException(requestInput.getChannel().getMethod()); } - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE_MANAGEMENT, action, requestInput.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.DEVICE_MANAGEMENT, action, requestInput.getScopeId())); // Prepare the request GenericRequestChannel genericRequestChannel = genericRequestFactory.newRequestChannel(); genericRequestChannel.setAppName(requestInput.getChannel().getAppName()); diff --git a/service/device/management/request/pom.xml b/service/device/management/request/pom.xml index 354f6bca1d9..de72c32255a 100644 --- a/service/device/management/request/pom.xml +++ b/service/device/management/request/pom.xml @@ -18,7 +18,7 @@ kapua-device-management org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT pom diff --git a/service/device/pom.xml b/service/device/pom.xml index ed1e9ee0fe5..2aa1cae273e 100644 --- a/service/device/pom.xml +++ b/service/device/pom.xml @@ -17,7 +17,7 @@ org.eclipse.kapua kapua-service - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-device diff --git a/service/device/registry/api/pom.xml b/service/device/registry/api/pom.xml index 129d1e33bec..f10b762ad1c 100644 --- a/service/device/registry/api/pom.xml +++ b/service/device/registry/api/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-device-registry - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-device-registry-api diff --git a/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/DeviceCreator.java b/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/DeviceCreator.java index 7ce14db5eb7..3e5b6e7fdb2 100644 --- a/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/DeviceCreator.java +++ b/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/DeviceCreator.java @@ -12,8 +12,12 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.registry; +import java.util.ArrayList; +import java.util.HashSet; import java.util.List; import java.util.Set; + +import javax.validation.constraints.NotNull; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; @@ -21,6 +25,7 @@ import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; +import org.eclipse.kapua.model.KapuaEntityCreator; import org.eclipse.kapua.model.KapuaUpdatableEntityCreator; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.model.id.KapuaIdAdapter; @@ -29,12 +34,10 @@ import org.eclipse.kapua.service.device.registry.event.DeviceEvent; /** - * {@link DeviceCreator} encapsulates all the information needed to create a new {@link Device} in the system.
        - * The data provided will be used to seed the new {@link Device} and its related information.
        - * The fields of the {@link DeviceCreator} presents the attributes that are searchable for a given device.
        - * The DeviceCreator Properties field can be used to provide additional properties associated to the Device; - * those properties will not be searchable through Device queries.
        - * The clientId field of the Device is used to store the MAC address of the primary network interface of the device. + * {@link DeviceCreator} encapsulates all the information needed to create a new {@link Device} in the system.
        The data provided will be used to seed the new {@link Device} and its related + * information.
        The fields of the {@link DeviceCreator} presents the attributes that are searchable for a given device.
        The DeviceCreator Properties field can be used to provide additional + * properties associated to the Device; those properties will not be searchable through Device queries.
        The clientId field of the Device is used to store the MAC address of the primary network + * interface of the device. * * @since 1.0.0 */ @@ -71,8 +74,56 @@ "extendedProperties", "tagIds", "tamperStatus" -}, factoryClass = DeviceXmlRegistry.class, factoryMethod = "newDeviceCreator") -public interface DeviceCreator extends KapuaUpdatableEntityCreator { +}) +public class DeviceCreator extends KapuaUpdatableEntityCreator { + + private static final long serialVersionUID = 8497299443773395462L; + private KapuaId groupId; + private String clientId; + private DeviceStatus status = DeviceStatus.ENABLED; + private KapuaId connectionId; + private KapuaId lastEventId; + private String displayName; + private String serialNumber; + private String modelId; + private String modelName; + private String imei; + private String imsi; + private String iccid; + private String biosVersion; + private String firmwareVersion; + private String osVersion; + private String jvmVersion; + private String osgiFrameworkVersion; + private String applicationFrameworkVersion; + private String connectionInterface; + private String connectionIp; + private String applicationIdentifiers; + private String acceptEncoding; + private String customAttribute1; + private String customAttribute2; + private String customAttribute3; + private String customAttribute4; + private String customAttribute5; + private List extendedProperties; + private String tamperStatus; + private Set tagIds; + + public DeviceCreator() { + } + + public DeviceCreator(KapuaId scopeId) { + super(scopeId); + } + + public DeviceCreator(KapuaEntityCreator entityCreator) { + super(entityCreator); + } + + public DeviceCreator(KapuaId scopeId, String clientId) { + super(scopeId); + this.clientId = clientId; + } /** * Gets the {@link Group#getId()}. @@ -82,15 +133,20 @@ public interface DeviceCreator extends KapuaUpdatableEntityCreator { */ @XmlElement(name = "groupId") @XmlJavaTypeAdapter(KapuaIdAdapter.class) - KapuaId getGroupId(); + public KapuaId getGroupId() { + return groupId; + } /** * Sets the {@link Group#getId()}. * - * @param groupId The {@link Group#getId()}. + * @param groupId + * The {@link Group#getId()}. * @since 1.0.0 */ - void setGroupId(KapuaId groupId); + public void setGroupId(KapuaId groupId) { + this.groupId = groupId; + } /** * Gets the client identifier. @@ -99,15 +155,20 @@ public interface DeviceCreator extends KapuaUpdatableEntityCreator { * @since 1.0.0 */ @XmlElement(name = "clientId") - String getClientId(); + public String getClientId() { + return clientId; + } /** * Sets the client identifier. * - * @param clientId The client identifier. + * @param clientId + * The client identifier. * @since 1.0.0 */ - void setClientId(String clientId); + public void setClientId(String clientId) { + this.clientId = clientId; + } /** * Gets the {@link DeviceConnection#getId()}. @@ -117,15 +178,20 @@ public interface DeviceCreator extends KapuaUpdatableEntityCreator { */ @XmlElement(name = "connectionId") @XmlJavaTypeAdapter(KapuaIdAdapter.class) - KapuaId getConnectionId(); + public KapuaId getConnectionId() { + return connectionId; + } /** * Sets the {@link DeviceConnection#getId()}. * - * @param connectionId The {@link DeviceConnection#getId()}. + * @param connectionId + * The {@link DeviceConnection#getId()}. * @since 1.0.0 */ - void setConnectionId(KapuaId connectionId); + public void setConnectionId(KapuaId connectionId) { + this.connectionId = connectionId; + } /** * Gets the {@link DeviceStatus}. @@ -134,15 +200,20 @@ public interface DeviceCreator extends KapuaUpdatableEntityCreator { * @since 1.0.0 */ @XmlElement(name = "status") - DeviceStatus getStatus(); + public DeviceStatus getStatus() { + return status; + } /** * Sets the {@link DeviceStatus}. * - * @param status The {@link DeviceStatus}. + * @param status + * The {@link DeviceStatus}. * @since 1.0.0 */ - void setStatus(DeviceStatus status); + public void setStatus(DeviceStatus status) { + this.status = status; + } /** * Gets the display name. @@ -151,15 +222,20 @@ public interface DeviceCreator extends KapuaUpdatableEntityCreator { * @since 1.0.0 */ @XmlElement(name = "displayName") - String getDisplayName(); + public String getDisplayName() { + return displayName; + } /** * Sets the display name. * - * @param diplayName The display name. + * @param displayName + * The display name. * @since 1.0.0 */ - void setDisplayName(String diplayName); + public void setDisplayName(String displayName) { + this.displayName = displayName; + } /** * Gets the last {@link DeviceEvent#getId()}. @@ -169,15 +245,20 @@ public interface DeviceCreator extends KapuaUpdatableEntityCreator { */ @XmlElement(name = "lastEventId") @XmlJavaTypeAdapter(KapuaIdAdapter.class) - KapuaId getLastEventId(); + public KapuaId getLastEventId() { + return lastEventId; + } /** * Sets the last {@link DeviceEvent#getId()}. * - * @param lastEventId The last {@link DeviceEvent#getId()}. + * @param lastEventId + * The last {@link DeviceEvent#getId()}. * @since 1.0.0 */ - void setLastEventId(KapuaId lastEventId); + public void setLastEventId(KapuaId lastEventId) { + this.lastEventId = lastEventId; + } /** * Gets the serial number. @@ -186,15 +267,20 @@ public interface DeviceCreator extends KapuaUpdatableEntityCreator { * @since 1.0.0 */ @XmlElement(name = "serialNumber") - String getSerialNumber(); + public String getSerialNumber() { + return serialNumber; + } /** * Sets the serial number. * - * @param serialNumber The serial number. + * @param serialNumber + * The serial number. * @since 1.0.0 */ - void setSerialNumber(String serialNumber); + public void setSerialNumber(String serialNumber) { + this.serialNumber = serialNumber; + } /** * Gets the model identifier. @@ -203,15 +289,20 @@ public interface DeviceCreator extends KapuaUpdatableEntityCreator { * @since 1.0.0 */ @XmlElement(name = "modelId") - String getModelId(); + public String getModelId() { + return modelId; + } /** * Sets the model identifier. * - * @param modelId The model identifier. + * @param modelId + * The model identifier. * @since 1.0.0 */ - void setModelId(String modelId); + public void setModelId(String modelId) { + this.modelId = modelId; + } /** * Gets the model name. @@ -220,15 +311,20 @@ public interface DeviceCreator extends KapuaUpdatableEntityCreator { * @since 1.0.0 */ @XmlElement(name = "modelName") - String getModelName(); + public String getModelName() { + return modelName; + } /** * Sets the model name. * - * @param modelName The model name. + * @param modelName + * The model name. * @since 1.0.0 */ - void setModelName(String modelName); + public void setModelName(String modelName) { + this.modelName = modelName; + } /** * Gets the modem imei. @@ -237,15 +333,20 @@ public interface DeviceCreator extends KapuaUpdatableEntityCreator { * @since 1.0.0 */ @XmlElement(name = "imei") - String getImei(); + public String getImei() { + return imei; + } /** * Sets the modem imei. * - * @param imei The modem imei. + * @param imei + * The modem imei. * @since 1.0.0 */ - void setImei(String imei); + public void setImei(String imei) { + this.imei = imei; + } /** * Gets the modem imsi. @@ -254,15 +355,20 @@ public interface DeviceCreator extends KapuaUpdatableEntityCreator { * @since 1.0.0 */ @XmlElement(name = "imsi") - String getImsi(); + public String getImsi() { + return this.imsi; + } /** * Sets the modem imsi. * - * @param imsi The modem imsi. + * @param imsi + * The modem imsi. * @since 1.0.0 */ - void setImsi(String imsi); + public void setImsi(String imsi) { + this.imsi = imsi; + } /** * Gets the modem iccid. @@ -271,15 +377,20 @@ public interface DeviceCreator extends KapuaUpdatableEntityCreator { * @since 1.0.0 */ @XmlElement(name = "iccid") - String getIccid(); + public String getIccid() { + return iccid; + } /** * Sets the modem iccid. * - * @param iccid The modem iccid. + * @param iccid + * The modem iccid. * @since 1.0.0 */ - void setIccid(String iccid); + public void setIccid(String iccid) { + this.iccid = iccid; + } /** * Gets the bios version. @@ -288,15 +399,20 @@ public interface DeviceCreator extends KapuaUpdatableEntityCreator { * @since 1.0.0 */ @XmlElement(name = "biosVersion") - String getBiosVersion(); + public String getBiosVersion() { + return biosVersion; + } /** * Sets the bios version. * - * @param biosVersion The bios version. + * @param biosVersion + * The bios version. * @since 1.0.0 */ - void setBiosVersion(String biosVersion); + public void setBiosVersion(String biosVersion) { + this.biosVersion = biosVersion; + } /** * Gets the firmware version. @@ -305,15 +421,20 @@ public interface DeviceCreator extends KapuaUpdatableEntityCreator { * @since 1.0.0 */ @XmlElement(name = "firmwareVersion") - String getFirmwareVersion(); + public String getFirmwareVersion() { + return firmwareVersion; + } /** * Sets the firmware version. * - * @param firmwareVersion The firmware version. + * @param firmwareVersion + * The firmware version. * @since 1.0.0 */ - void setFirmwareVersion(String firmwareVersion); + public void setFirmwareVersion(String firmwareVersion) { + this.firmwareVersion = firmwareVersion; + } /** * Gets the OS version. @@ -322,15 +443,20 @@ public interface DeviceCreator extends KapuaUpdatableEntityCreator { * @since 1.0.0 */ @XmlElement(name = "osVersion") - String getOsVersion(); + public String getOsVersion() { + return osVersion; + } /** * Sets the OS version. * - * @param osVersion The OS version. + * @param osVersion + * The OS version. * @since 1.0.0 */ - void setOsVersion(String osVersion); + public void setOsVersion(String osVersion) { + this.osVersion = osVersion; + } /** * Gets the JVM version. @@ -339,15 +465,20 @@ public interface DeviceCreator extends KapuaUpdatableEntityCreator { * @since 1.0.0 */ @XmlElement(name = "jvmVersion") - String getJvmVersion(); + public String getJvmVersion() { + return jvmVersion; + } /** * Sets the JVM version. * - * @param jvmVersion The JVM version. + * @param jvmVersion + * The JVM version. * @since 1.0.0 */ - void setJvmVersion(String jvmVersion); + public void setJvmVersion(String jvmVersion) { + this.jvmVersion = jvmVersion; + } /** * Gets the OSGi framework version. @@ -356,15 +487,20 @@ public interface DeviceCreator extends KapuaUpdatableEntityCreator { * @since 1.0.0 */ @XmlElement(name = "osgiFrameworkVersion") - String getOsgiFrameworkVersion(); + public String getOsgiFrameworkVersion() { + return osgiFrameworkVersion; + } /** * Sets the OSGi framework version. * - * @param osgiFrameworkVersion The OSGi framework version. + * @param osgiFrameworkVersion + * The OSGi framework version. * @since 1.0.0 */ - void setOsgiFrameworkVersion(String osgiFrameworkVersion); + public void setOsgiFrameworkVersion(String osgiFrameworkVersion) { + this.osgiFrameworkVersion = osgiFrameworkVersion; + } /** * Gets the application framework version. @@ -373,15 +509,20 @@ public interface DeviceCreator extends KapuaUpdatableEntityCreator { * @since 1.0.0 */ @XmlElement(name = "applicationFrameworkVersion") - String getApplicationFrameworkVersion(); + public String getApplicationFrameworkVersion() { + return applicationFrameworkVersion; + } /** * Sets the application framework version. * - * @param appFrameworkVersion The application framework version. + * @param appFrameworkVersion + * The application framework version. * @since 1.0.0 */ - void setApplicationFrameworkVersion(String appFrameworkVersion); + public void setApplicationFrameworkVersion(String appFrameworkVersion) { + this.applicationFrameworkVersion = appFrameworkVersion; + } /** * Gets the device network interfaces name. @@ -390,15 +531,20 @@ public interface DeviceCreator extends KapuaUpdatableEntityCreator { * @since 1.0.0 */ @XmlElement(name = "connectionInterface") - String getConnectionInterface(); + public String getConnectionInterface() { + return connectionInterface; + } /** * Sets the device network interfaces name. * - * @param connectionInterface The device network interfaces name. + * @param connectionInterface + * The device network interfaces name. * @since 1.0.0 */ - void setConnectionInterface(String connectionInterface); + public void setConnectionInterface(String connectionInterface) { + this.connectionInterface = connectionInterface; + } /** * Gets the device network interfaces IP. @@ -407,15 +553,20 @@ public interface DeviceCreator extends KapuaUpdatableEntityCreator { * @since 1.0.0 */ @XmlElement(name = "connectionIp") - String getConnectionIp(); + public String getConnectionIp() { + return connectionIp; + } /** * Sets the device network interfaces IP. * - * @param connectionIp The device network interfaces IP. + * @param connectionIp + * The device network interfaces IP. * @since 1.0.0 */ - void setConnectionIp(String connectionIp); + public void setConnectionIp(String connectionIp) { + this.connectionIp = connectionIp; + } /** * Gets the application identifiers supported. @@ -424,15 +575,20 @@ public interface DeviceCreator extends KapuaUpdatableEntityCreator { * @since 1.0.0 */ @XmlElement(name = "applicationIdentifiers") - String getApplicationIdentifiers(); + public String getApplicationIdentifiers() { + return applicationIdentifiers; + } /** * Sets the application identifiers supported. * - * @param applicationIdentifiers The application identifiers supported. + * @param applicationIdentifiers + * The application identifiers supported. * @since 1.0.0 */ - void setApplicationIdentifiers(String applicationIdentifiers); + public void setApplicationIdentifiers(String applicationIdentifiers) { + this.applicationIdentifiers = applicationIdentifiers; + } /** * Gets the accept encodings. @@ -441,15 +597,20 @@ public interface DeviceCreator extends KapuaUpdatableEntityCreator { * @since 1.0.0 */ @XmlElement(name = "acceptEncoding") - String getAcceptEncoding(); + public String getAcceptEncoding() { + return acceptEncoding; + } /** * Sets the accept encodings. * - * @param acceptEncoding The accept encodings. + * @param acceptEncoding + * The accept encodings. * @since 1.0.0 */ - void setAcceptEncoding(String acceptEncoding); + public void setAcceptEncoding(String acceptEncoding) { + this.acceptEncoding = acceptEncoding; + } /** * Gets the custom attribute 1. @@ -458,15 +619,20 @@ public interface DeviceCreator extends KapuaUpdatableEntityCreator { * @since 1.0.0 */ @XmlElement(name = "customAttribute1") - String getCustomAttribute1(); + public String getCustomAttribute1() { + return customAttribute1; + } /** * Sets the custom attribute 1. * - * @param customAttribute1 The custom attribute 1. + * @param customAttribute1 + * The custom attribute 1. * @since 1.0.0 */ - void setCustomAttribute1(String customAttribute1); + public void setCustomAttribute1(String customAttribute1) { + this.customAttribute1 = customAttribute1; + } /** * Gets the custom attribute 2. @@ -475,15 +641,20 @@ public interface DeviceCreator extends KapuaUpdatableEntityCreator { * @since 1.0.0 */ @XmlElement(name = "customAttribute2") - String getCustomAttribute2(); + public String getCustomAttribute2() { + return customAttribute2; + } /** * Sets the custom attribute 2. * - * @param customAttribute2 The custom attribute 2. + * @param customAttribute2 + * The custom attribute 2. * @since 1.0.0 */ - void setCustomAttribute2(String customAttribute2); + public void setCustomAttribute2(String customAttribute2) { + this.customAttribute2 = customAttribute2; + } /** * Gets the custom attribute 3. @@ -492,15 +663,20 @@ public interface DeviceCreator extends KapuaUpdatableEntityCreator { * @since 1.0.0 */ @XmlElement(name = "customAttribute3") - String getCustomAttribute3(); + public String getCustomAttribute3() { + return customAttribute3; + } /** * Sets the custom attribute 3. * - * @param customAttribute3 The custom attribute 3. + * @param customAttribute3 + * The custom attribute 3. * @since 1.0.0 */ - void setCustomAttribute3(String customAttribute3); + public void setCustomAttribute3(String customAttribute3) { + this.customAttribute3 = customAttribute3; + } /** * Gets the custom attribute 4. @@ -509,15 +685,20 @@ public interface DeviceCreator extends KapuaUpdatableEntityCreator { * @since 1.0.0 */ @XmlElement(name = "customAttribute4") - String getCustomAttribute4(); + public String getCustomAttribute4() { + return customAttribute4; + } /** * Sets the custom attribute 4. * - * @param customAttribute4 The custom attribute 4. + * @param customAttribute4 + * The custom attribute 4. * @since 1.0.0 */ - void setCustomAttribute4(String customAttribute4); + public void setCustomAttribute4(String customAttribute4) { + this.customAttribute4 = customAttribute4; + } /** * Gets the custom attribute 5. @@ -526,15 +707,20 @@ public interface DeviceCreator extends KapuaUpdatableEntityCreator { * @since 1.0.0 */ @XmlElement(name = "customAttribute5") - String getCustomAttribute5(); + public String getCustomAttribute5() { + return customAttribute5; + } /** * Sets the custom attribute 5. * - * @param customAttribute5 The custom attribute 5. + * @param customAttribute5 + * The custom attribute 5. * @since 1.0.0 */ - void setCustomAttribute5(String customAttribute5); + public void setCustomAttribute5(String customAttribute5) { + this.customAttribute5 = customAttribute5; + } /** * Gets the {@link DeviceExtendedProperty} {@link List}. @@ -543,23 +729,35 @@ public interface DeviceCreator extends KapuaUpdatableEntityCreator { * @since 1.5.0 */ @XmlElement(name = "extendedProperties") - List getExtendedProperties(); + public List getExtendedProperties() { + if (extendedProperties == null) { + extendedProperties = new ArrayList<>(); + } + + return extendedProperties; + } /** * Add a {@link DeviceExtendedProperty} to the {@link List}. * - * @param extendedProperty The {@link DeviceExtendedProperty} to add. + * @param extendedProperty + * The {@link DeviceExtendedProperty} to add. * @since 1.5.0 */ - void addExtendedProperty(DeviceExtendedProperty extendedProperty); + public void addExtendedProperty(@NotNull DeviceExtendedProperty extendedProperty) { + getExtendedProperties().add(extendedProperty); + } /** * Sets the {@link DeviceExtendedProperty} {@link List}. * - * @param extendedProperties The {@link DeviceExtendedProperty} {@link List}. + * @param extendedProperties + * The {@link DeviceExtendedProperty} {@link List}. * @since 1.5.0 */ - void setExtendedProperties(List extendedProperties); + public void setExtendedProperties(List extendedProperties) { + this.extendedProperties = extendedProperties; + } /** * Gets the tamper status. @@ -568,16 +766,20 @@ public interface DeviceCreator extends KapuaUpdatableEntityCreator { * @since 2.0.0 */ @XmlElement(name = "tamperStatus") - String getTamperStatus(); + public String getTamperStatus() { + return tamperStatus; + } /** * Sets the tamper status. * - * @param tamperStatus The tamper status. + * @param tamperStatus + * The tamper status. * @since 2.0.0 */ - void setTamperStatus(String tamperStatus); - + public void setTamperStatus(String tamperStatus) { + this.tamperStatus = tamperStatus; + } /** * Gets the list of tags associated with the device. @@ -587,13 +789,19 @@ public interface DeviceCreator extends KapuaUpdatableEntityCreator { */ @XmlElement(name = "tagIds") @XmlJavaTypeAdapter(KapuaIdAdapter.class) - Set getTagIds(); + public Set getTagIds() { + return tagIds == null ? new HashSet<>() : tagIds; + } /** * Sets the list of tags associated with the device. * - * @param tags The list of tags. + * @param tagIds + * The list of tags. * @since 2.0.0 */ - void setTagIds(Set tags); + public void setTagIds(Set tagIds) { + this.tagIds = tagIds; + } + } diff --git a/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/DeviceFactory.java b/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/DeviceFactory.java index 6a526e6d7b5..1c199ecc111 100644 --- a/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/DeviceFactory.java +++ b/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/DeviceFactory.java @@ -13,7 +13,6 @@ package org.eclipse.kapua.service.device.registry; import org.eclipse.kapua.model.KapuaEntityFactory; -import org.eclipse.kapua.model.id.KapuaId; /** * {@link Device} {@link KapuaEntityFactory} definition. @@ -21,26 +20,17 @@ * @see org.eclipse.kapua.model.KapuaEntityFactory * @since 1.0.0 */ -public interface DeviceFactory extends KapuaEntityFactory { - - /** - * Instantiates a new {@link DeviceCreator} - * - * @param scopeId The scope {@link KapuaId} to set into the {@link DeviceCreator} - * @param clientId The client id to set into the {@link DeviceCreator} - * @return The newly instantiated {@link DeviceCreator}. - * @since 1.0.0 - * @deprecated Since 1.5.0. Please use {@link #newCreator(KapuaId)}. - */ - @Deprecated - DeviceCreator newCreator(KapuaId scopeId, String clientId); +public interface DeviceFactory extends KapuaEntityFactory { /** * Instantiates a new {@link DeviceExtendedProperty}. * - * @param groupName The {@link DeviceExtendedProperty#getGroupName()}. - * @param name The {@link DeviceExtendedProperty#getName()}. - * @param value The {@link DeviceExtendedProperty#getValue()}. + * @param groupName + * The {@link DeviceExtendedProperty#getGroupName()}. + * @param name + * The {@link DeviceExtendedProperty#getName()}. + * @param value + * The {@link DeviceExtendedProperty#getValue()}. * @return The newly instantiated {@link DeviceExtendedProperty}. * @since 1.5.0 */ diff --git a/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/DeviceListResult.java b/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/DeviceListResult.java index 71a32a1b1bd..5745e187b5c 100644 --- a/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/DeviceListResult.java +++ b/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/DeviceListResult.java @@ -21,10 +21,11 @@ * Device list result definition. * * @since 1.0 - * */ @XmlRootElement(name = "devices") -@XmlType(factoryClass = DeviceXmlRegistry.class, factoryMethod = "newDeviceListResult") -public interface DeviceListResult extends KapuaListResult { +@XmlType +public class DeviceListResult extends KapuaListResult { + + private static final long serialVersionUID = -3870951363076544938L; } diff --git a/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/DeviceMatchPredicate.java b/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/DeviceMatchPredicate.java index 7f2611aed25..33b23c9785d 100644 --- a/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/DeviceMatchPredicate.java +++ b/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/DeviceMatchPredicate.java @@ -12,8 +12,34 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.registry; -import org.eclipse.kapua.model.query.predicate.MatchPredicate; +import java.util.Arrays; -public interface DeviceMatchPredicate extends MatchPredicate { +import org.eclipse.kapua.model.query.predicate.AbstractMatchPredicate; +public class DeviceMatchPredicate extends AbstractMatchPredicate { + + /** + * Constructor. + * + * @param matchTerm + * @since 1.3.0 + */ + public DeviceMatchPredicate(T matchTerm) { + this.attributeNames = Arrays.asList( + DeviceAttributes.CLIENT_ID, + DeviceAttributes.DISPLAY_NAME, + DeviceAttributes.SERIAL_NUMBER, + DeviceAttributes.MODEL_ID, + DeviceAttributes.MODEL_NAME, + DeviceAttributes.BIOS_VERSION, + DeviceAttributes.FIRMWARE_VERSION, + DeviceAttributes.OS_VERSION, + DeviceAttributes.JVM_VERSION, + DeviceAttributes.OSGI_FRAMEWORK_VERSION, + DeviceAttributes.APPLICATION_FRAMEWORK_VERSION, + DeviceAttributes.CONNECTION_INTERFACE, + DeviceAttributes.CONNECTION_IP + ); + this.matchTerm = matchTerm; + } } diff --git a/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/DeviceQuery.java b/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/DeviceQuery.java index 69a0ed1f79c..8a7eff8c774 100644 --- a/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/DeviceQuery.java +++ b/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/DeviceQuery.java @@ -12,13 +12,16 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.registry; -import org.eclipse.kapua.model.query.KapuaQuery; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; +import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.query.KapuaQuery; +import org.eclipse.kapua.model.query.KapuaSortCriteria; +import org.eclipse.kapua.model.query.SortOrder; + /** * {@link Device} {@link KapuaQuery} definition. * @@ -27,16 +30,47 @@ */ @XmlRootElement(name = "query") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = DeviceXmlRegistry.class, factoryMethod = "newQuery") -public interface DeviceQuery extends KapuaQuery { +@XmlType +public class DeviceQuery extends KapuaQuery { + + /** + * Constructor. + * + * @since 1.0.0 + */ + private DeviceQuery() { + super(); + } + + /** + * Constructor. + * + * @param scopeId + * The {@link #getScopeId()}. + * @since 1.0.0 + */ + public DeviceQuery(KapuaId scopeId) { + this(); + setScopeId(scopeId); + } + + @Override + public KapuaSortCriteria getDefaultSortCriteria() { + return fieldSortCriteria(DeviceAttributes.CLIENT_ID, SortOrder.ASCENDING); + } /** * Instantiates a new {@link DeviceMatchPredicate}. * - * @param matchTerm The term to use to match. - * @param The type of the term + * @param matchTerm + * The term to use to match. + * @param + * The type of the term * @return The newly instantiated {@link DeviceMatchPredicate}. * @since 1.3.0 */ - DeviceMatchPredicate matchPredicate(T matchTerm); + public DeviceMatchPredicate matchPredicate(T matchTerm) { + return new DeviceMatchPredicate<>(matchTerm); + } + } diff --git a/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/DeviceXmlRegistry.java b/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/DeviceXmlRegistry.java index 573905a636b..758374e1fa3 100644 --- a/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/DeviceXmlRegistry.java +++ b/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/DeviceXmlRegistry.java @@ -12,10 +12,10 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.registry; -import org.eclipse.kapua.locator.KapuaLocator; - import javax.xml.bind.annotation.XmlRegistry; +import org.eclipse.kapua.locator.KapuaLocator; + /** * {@link Device} xml factory class * @@ -36,30 +36,6 @@ public Device newDevice() { return deviceFactory.newEntity(null); } - /** - * Creates a new device creator - * - * @return - * @since 1.0.0 - */ - public DeviceCreator newDeviceCreator() { - return deviceFactory.newCreator(null, null); - } - - /** - * Creates a new device list result - * - * @return - * @since 1.0.0 - */ - public DeviceListResult newDeviceListResult() { - return deviceFactory.newListResult(); - } - - public DeviceQuery newQuery() { - return deviceFactory.newQuery(null); - } - /** * Instantiates a new {@link DeviceExtendedProperty}. * diff --git a/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/connection/DeviceConnectionCreator.java b/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/connection/DeviceConnectionCreator.java index 6ad48d24659..4dedfb495cb 100644 --- a/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/connection/DeviceConnectionCreator.java +++ b/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/connection/DeviceConnectionCreator.java @@ -12,18 +12,44 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.registry.connection; +import javax.xml.bind.annotation.XmlElement; + +import org.eclipse.kapua.model.KapuaEntityCreator; import org.eclipse.kapua.model.KapuaUpdatableEntityCreator; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.device.registry.ConnectionUserCouplingMode; -import javax.xml.bind.annotation.XmlElement; - /** * Device connection creator service definition. * * @since 1.0 */ -public interface DeviceConnectionCreator extends KapuaUpdatableEntityCreator { +public class DeviceConnectionCreator extends KapuaUpdatableEntityCreator { + + private static final long serialVersionUID = 2740394157765904615L; + + private DeviceConnectionStatus status; + private String clientId; + private KapuaId userId; + private ConnectionUserCouplingMode userCouplingMode; + private KapuaId reservedUserId; + private boolean allowUserChange; + private String authenticationType; + private String lastAuthenticationType; + private String protocol; + private String clientIp; + private String serverIp; + + public DeviceConnectionCreator() { + } + + public DeviceConnectionCreator(KapuaId scopeId) { + super(scopeId); + } + + public DeviceConnectionCreator(KapuaEntityCreator entityCreator) { + super(entityCreator); + } /** * Get the device connection status @@ -31,70 +57,90 @@ public interface DeviceConnectionCreator extends KapuaUpdatableEntityCreatortrue if device can changhe user to connect, false if not. */ @XmlElement(name = "allowUserChange") - boolean getAllowUserChange(); + public boolean getAllowUserChange() { + return allowUserChange; + } /** * Sets whether or not the {@link DeviceConnection} can change user on the next login. * * @param allowUserChange */ - void setAllowUserChange(boolean allowUserChange); + public void setAllowUserChange(boolean allowUserChange) { + this.allowUserChange = allowUserChange; + } /** * Gets the allowed authentication type. @@ -117,15 +167,20 @@ public interface DeviceConnectionCreator extends KapuaUpdatableEntityCreator { +public interface DeviceConnectionFactory extends KapuaEntityFactory { } diff --git a/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/connection/DeviceConnectionListResult.java b/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/connection/DeviceConnectionListResult.java index e37886dcaa6..5203c40b686 100644 --- a/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/connection/DeviceConnectionListResult.java +++ b/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/connection/DeviceConnectionListResult.java @@ -23,6 +23,8 @@ * @since 1.0 */ @XmlRootElement(name = "deviceConnections") -@XmlType(factoryClass = DeviceConnectionXmlRegistry.class, factoryMethod = "newDeviceConnectionListResult") -public interface DeviceConnectionListResult extends KapuaListResult { +@XmlType +public class DeviceConnectionListResult extends KapuaListResult { + + private static final long serialVersionUID = -4450707993798807403L; } diff --git a/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/connection/DeviceConnectionQuery.java b/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/connection/DeviceConnectionQuery.java index bed3e6c6c51..0f239d2effd 100644 --- a/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/connection/DeviceConnectionQuery.java +++ b/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/connection/DeviceConnectionQuery.java @@ -12,13 +12,17 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.registry.connection; -import org.eclipse.kapua.model.query.KapuaQuery; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; +import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.query.KapuaQuery; +import org.eclipse.kapua.model.query.KapuaSortCriteria; +import org.eclipse.kapua.model.query.SortOrder; +import org.eclipse.kapua.service.device.registry.DeviceAttributes; + /** * {@link DeviceConnection} {@link KapuaQuery} definition. * @@ -27,6 +31,32 @@ */ @XmlRootElement(name = "query") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = DeviceConnectionXmlRegistry.class, factoryMethod = "newQuery") -public interface DeviceConnectionQuery extends KapuaQuery { +@XmlType +public class DeviceConnectionQuery extends KapuaQuery { + + /** + * Constructor. + * + * @since 1.0.0 + */ + private DeviceConnectionQuery() { + super(); + } + + /** + * Constructor. + * + * @param scopeId + * The {@link #getScopeId()}. + * @since 1.0.0 + */ + public DeviceConnectionQuery(KapuaId scopeId) { + this(); + setScopeId(scopeId); + } + + @Override + public KapuaSortCriteria getDefaultSortCriteria() { + return fieldSortCriteria(DeviceAttributes.CLIENT_ID, SortOrder.ASCENDING); + } } diff --git a/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/connection/DeviceConnectionXmlRegistry.java b/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/connection/DeviceConnectionXmlRegistry.java index b4812c01608..903d35de1b5 100644 --- a/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/connection/DeviceConnectionXmlRegistry.java +++ b/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/connection/DeviceConnectionXmlRegistry.java @@ -12,10 +12,10 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.registry.connection; -import org.eclipse.kapua.locator.KapuaLocator; - import javax.xml.bind.annotation.XmlRegistry; +import org.eclipse.kapua.locator.KapuaLocator; + /** * {@link DeviceConnection} xml factory class * @@ -35,16 +35,4 @@ public DeviceConnection newDeviceConnection() { return deviceConnectionFactory.newEntity(null); } - /** - * Creates a new device list result - * - * @return - */ - public DeviceConnectionListResult newDeviceConnectionListResult() { - return deviceConnectionFactory.newListResult(); - } - - public DeviceConnectionQuery newQuery() { - return deviceConnectionFactory.newQuery(null); - } } diff --git a/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/connection/option/DeviceConnectionOptionCreator.java b/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/connection/option/DeviceConnectionOptionCreator.java index 12d721b6130..3843f476404 100644 --- a/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/connection/option/DeviceConnectionOptionCreator.java +++ b/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/connection/option/DeviceConnectionOptionCreator.java @@ -12,6 +12,7 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.registry.connection.option; +import org.eclipse.kapua.model.KapuaEntityCreator; import org.eclipse.kapua.model.KapuaUpdatableEntityCreator; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.device.registry.ConnectionUserCouplingMode; @@ -21,35 +22,61 @@ * * @since 1.0 */ -public interface DeviceConnectionOptionCreator extends KapuaUpdatableEntityCreator { +public class DeviceConnectionOptionCreator extends KapuaUpdatableEntityCreator { + + private static final long serialVersionUID = 2740394157765904615L; + + private ConnectionUserCouplingMode userCouplingMode; + private KapuaId reservedUserId; + + private String authenticationType; + + public DeviceConnectionOptionCreator() { + } + + public DeviceConnectionOptionCreator(KapuaId scopeId) { + super(scopeId); + } + + public DeviceConnectionOptionCreator(KapuaEntityCreator entityCreator) { + super(entityCreator); + } /** * Get the device connection user coupling mode. * * @return */ - ConnectionUserCouplingMode getUserCouplingMode(); + public ConnectionUserCouplingMode getUserCouplingMode() { + return userCouplingMode; + } /** * Set the device connection user coupling mode. * * @param userCouplingMode */ - void setUserCouplingMode(ConnectionUserCouplingMode userCouplingMode); + public void setUserCouplingMode(ConnectionUserCouplingMode userCouplingMode) { + this.userCouplingMode = userCouplingMode; + } /** * Get the reserved user identifier * * @return */ - KapuaId getReservedUserId(); + public KapuaId getReservedUserId() { + return reservedUserId; + } /** * Set the reserved user identifier * * @param reservedUserId */ - void setReservedUserId(KapuaId reservedUserId); + public void setReservedUserId(KapuaId reservedUserId) { + this.reservedUserId = reservedUserId; + } /** * Gets the allowed authentication type. @@ -57,13 +84,18 @@ public interface DeviceConnectionOptionCreator extends KapuaUpdatableEntityCreat * @return The allowed authentication type. * @since 2.0.0 */ - String getAuthenticationType(); + public String getAuthenticationType() { + return authenticationType; + } /** * Sets the allowed authentication type. * - * @param authenticationType The allowed authentication type. + * @param authenticationType + * The allowed authentication type. * @since 2.0.0 */ - void setAuthenticationType(String authenticationType); + public void setAuthenticationType(String authenticationType) { + this.authenticationType = authenticationType; + } } diff --git a/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/connection/option/DeviceConnectionOptionFactory.java b/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/connection/option/DeviceConnectionOptionFactory.java index 231671e4ec2..6f115996981 100644 --- a/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/connection/option/DeviceConnectionOptionFactory.java +++ b/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/connection/option/DeviceConnectionOptionFactory.java @@ -20,6 +20,6 @@ * @see org.eclipse.kapua.model.KapuaEntityFactory * @since 1.0.0 */ -public interface DeviceConnectionOptionFactory extends KapuaEntityFactory { +public interface DeviceConnectionOptionFactory extends KapuaEntityFactory { } diff --git a/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/connection/option/DeviceConnectionOptionListResult.java b/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/connection/option/DeviceConnectionOptionListResult.java index 35281032b68..cefbaaf77ac 100644 --- a/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/connection/option/DeviceConnectionOptionListResult.java +++ b/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/connection/option/DeviceConnectionOptionListResult.java @@ -23,6 +23,8 @@ * @since 1.0.0 */ @XmlRootElement(name = "deviceConnectionOptions") -@XmlType(factoryClass = DeviceConnectionOptionXmlRegistry.class, factoryMethod = "newDeviceConnectionOptionListResult") -public interface DeviceConnectionOptionListResult extends KapuaListResult { +@XmlType +public class DeviceConnectionOptionListResult extends KapuaListResult { + + private static final long serialVersionUID = -4450707993798807403L; } diff --git a/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/connection/option/DeviceConnectionOptionQuery.java b/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/connection/option/DeviceConnectionOptionQuery.java deleted file mode 100644 index bae0cbe9cb8..00000000000 --- a/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/connection/option/DeviceConnectionOptionQuery.java +++ /dev/null @@ -1,33 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.registry.connection.option; - -import org.eclipse.kapua.model.query.KapuaQuery; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlType; - -/** - * {@link DeviceConnectionOption} {@link KapuaQuery} definition. - * - * @see KapuaQuery - * @since 1.0.0 - */ -@XmlRootElement(name = "query") -@XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = DeviceConnectionOptionXmlRegistry.class, factoryMethod = "newQuery") -public interface DeviceConnectionOptionQuery extends KapuaQuery { - -} diff --git a/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/connection/option/DeviceConnectionOptionXmlRegistry.java b/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/connection/option/DeviceConnectionOptionXmlRegistry.java index c2da267c5a2..054217e2de3 100644 --- a/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/connection/option/DeviceConnectionOptionXmlRegistry.java +++ b/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/connection/option/DeviceConnectionOptionXmlRegistry.java @@ -12,10 +12,10 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.registry.connection.option; -import org.eclipse.kapua.locator.KapuaLocator; - import javax.xml.bind.annotation.XmlRegistry; +import org.eclipse.kapua.locator.KapuaLocator; + /** * {@link DeviceConnectionOptionService} XML factory class * @@ -34,17 +34,4 @@ public class DeviceConnectionOptionXmlRegistry { public DeviceConnectionOption newDeviceConnectionOption() { return deviceConnectionOptionFactory.newEntity(null); } - - /** - * Creates a new device connection options list result - * - * @return - */ - public DeviceConnectionOptionListResult newDeviceConnectionOptionListResult() { - return deviceConnectionOptionFactory.newListResult(); - } - - public DeviceConnectionOptionQuery newQuery() { - return deviceConnectionOptionFactory.newQuery(null); - } } diff --git a/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/event/DeviceEventCreator.java b/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/event/DeviceEventCreator.java index db201dd6ea5..9e1a4e41c63 100644 --- a/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/event/DeviceEventCreator.java +++ b/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/event/DeviceEventCreator.java @@ -12,130 +12,209 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.registry.event; +import java.util.Date; + +import javax.xml.bind.annotation.XmlElement; + import org.eclipse.kapua.message.KapuaPosition; import org.eclipse.kapua.model.KapuaEntityCreator; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.device.management.message.KapuaMethod; import org.eclipse.kapua.service.device.management.message.response.KapuaResponseCode; -import java.util.Date; - /** * Device event creator service definition. * * @since 1.0 */ -public interface DeviceEventCreator extends KapuaEntityCreator { +public class DeviceEventCreator extends KapuaEntityCreator { + + private static final long serialVersionUID = -3982569213440658172L; + @XmlElement(name = "deviceId") + private KapuaId deviceId; + + @XmlElement(name = "receivedOn") + private Date receivedOn; + + @XmlElement(name = "sentOn") + private Date sentOn; + + @XmlElement(name = "position") + private KapuaPosition position; + + @XmlElement(name = "resource") + private String resource; + + @XmlElement(name = "action") + private KapuaMethod action; + + @XmlElement(name = "responseCode") + private KapuaResponseCode responseCode; + + @XmlElement(name = "eventMessage") + private String eventMessage; + + public DeviceEventCreator() { + } + + public DeviceEventCreator(KapuaId scopeId) { + super(scopeId); + } + + public DeviceEventCreator(KapuaEntityCreator entityCreator) { + super(entityCreator); + } + + public DeviceEventCreator(KapuaId scopeId, KapuaId deviceId, Date receivedOn, String resource) { + super(scopeId); + this.action = KapuaMethod.CREATE; + this.deviceId = deviceId; + this.receivedOn = new Date(receivedOn.getTime()); + this.resource = resource; + } /** * Get the device identifier * * @return */ - KapuaId getDeviceId(); + public KapuaId getDeviceId() { + return deviceId; + } /** * Set the device identifier * * @param deviceId */ - void setDeviceId(KapuaId deviceId); + public void setDeviceId(KapuaId deviceId) { + this.deviceId = deviceId; + } /** * Get the sent on date * * @return */ - Date getSentOn(); + public Date getSentOn() { + return sentOn != null ? new Date(sentOn.getTime()) : null; + } /** * Set the sent on date * * @param sentOn */ - void setSentOn(Date sentOn); + public void setSentOn(Date sentOn) { + this.sentOn = sentOn; + } /** * Get the received on date * * @return */ - Date getReceivedOn(); + public Date getReceivedOn() { + return receivedOn != null ? new Date(receivedOn.getTime()) : null; + } /** * Set the received on date * * @param receivedOn */ - void setReceivedOn(Date receivedOn); + public void setReceivedOn(Date receivedOn) { + this.receivedOn = receivedOn; + } /** * Get device position * * @return */ - KapuaPosition getPosition(); + public KapuaPosition getPosition() { + return position; + } /** * Set device position * * @param position */ - void setPosition(KapuaPosition position); + public void setPosition(KapuaPosition position) { + this.position = position; + } /** * Get resource * * @return */ - String getResource(); + public String getResource() { + return resource; + } /** * Set resource * * @param resource */ - void setResource(String resource); + public void setResource(String resource) { + this.resource = resource; + } /** * GHet action * * @return */ - KapuaMethod getAction(); + public KapuaMethod getAction() { + return action.normalizeAction(); + } /** * Set action * * @param action */ - void setAction(KapuaMethod action); + public void setAction(KapuaMethod action) { + this.action = action.normalizeAction(); + } /** * Get response code * * @return */ - KapuaResponseCode getResponseCode(); + public KapuaResponseCode getResponseCode() { + return responseCode; + } /** * Set response code * * @param responseCode */ - void setResponseCode(KapuaResponseCode responseCode); + public void setResponseCode(KapuaResponseCode responseCode) { + this.responseCode = responseCode; + } /** * Get event message * * @return */ - String getEventMessage(); + public String getEventMessage() { + return eventMessage; + } /** * Set event message * * @param eventMessage */ - void setEventMessage(String eventMessage); + public void setEventMessage(String eventMessage) { + this.eventMessage = eventMessage; + } + } diff --git a/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/event/DeviceEventFactory.java b/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/event/DeviceEventFactory.java index f6bd2fe9d1e..038dadb7b8d 100644 --- a/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/event/DeviceEventFactory.java +++ b/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/event/DeviceEventFactory.java @@ -13,9 +13,6 @@ package org.eclipse.kapua.service.device.registry.event; import org.eclipse.kapua.model.KapuaEntityFactory; -import org.eclipse.kapua.model.id.KapuaId; - -import java.util.Date; /** * {@link DeviceEventFactory} definition. @@ -23,18 +20,6 @@ * @see org.eclipse.kapua.model.KapuaEntityFactory * @since 1.0.0 */ -public interface DeviceEventFactory extends KapuaEntityFactory { - - /** - * Instantiates a new {@link DeviceEventCreator} - * - * @param scopeId The scope {@link KapuaId} to be set in the {@link DeviceEventCreator} - * @param deviceId The {@link org.eclipse.kapua.service.device.registry.Device} {@link KapuaId} to be set in the {@link DeviceEventCreator} - * @param receivedOn The received on {@link KapuaId} to be set in the {@link DeviceEventCreator} - * @param resource The resource {@link KapuaId} to be set in the {@link DeviceEventCreator} - * @return The newly instantiated {@link DeviceEventCreator} - * @since 1.0.0 - */ - DeviceEventCreator newCreator(KapuaId scopeId, KapuaId deviceId, Date receivedOn, String resource); +public interface DeviceEventFactory extends KapuaEntityFactory { } diff --git a/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/event/DeviceEventListResult.java b/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/event/DeviceEventListResult.java index a15cf87c0c4..6e834d0ccb3 100644 --- a/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/event/DeviceEventListResult.java +++ b/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/event/DeviceEventListResult.java @@ -23,11 +23,12 @@ * Device event list definition. * * @since 1.0 - * */ @XmlRootElement(name = "deviceEventListResult") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = DeviceEventXmlRegistry.class, factoryMethod = "newDeviceEventListResult") -public interface DeviceEventListResult extends KapuaListResult { +@XmlType +public class DeviceEventListResult extends KapuaListResult { + + private static final long serialVersionUID = 6537888946643944463L; } diff --git a/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/event/DeviceEventQuery.java b/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/event/DeviceEventQuery.java index 3882d9c4392..9b0bd746300 100644 --- a/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/event/DeviceEventQuery.java +++ b/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/event/DeviceEventQuery.java @@ -12,13 +12,16 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.registry.event; -import org.eclipse.kapua.model.query.KapuaQuery; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; +import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.query.KapuaQuery; +import org.eclipse.kapua.model.query.KapuaSortCriteria; +import org.eclipse.kapua.model.query.SortOrder; + /** * {@link DeviceEvent} {@link KapuaQuery} definition. * @@ -27,6 +30,32 @@ */ @XmlRootElement(name = "query") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = DeviceEventXmlRegistry.class, factoryMethod = "newQuery") -public interface DeviceEventQuery extends KapuaQuery { +@XmlType +public class DeviceEventQuery extends KapuaQuery { + + /** + * Constructor. + * + * @since 1.0.0 + */ + private DeviceEventQuery() { + super(); + } + + /** + * Constructor. + * + * @param scopeId + * The {@link #getScopeId()}. + * @since 1.0.0 + */ + public DeviceEventQuery(KapuaId scopeId) { + this(); + setScopeId(scopeId); + } + + @Override + public KapuaSortCriteria getDefaultSortCriteria() { + return fieldSortCriteria(DeviceEventAttributes.RECEIVED_ON, SortOrder.DESCENDING); + } } diff --git a/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/event/DeviceEventXmlRegistry.java b/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/event/DeviceEventXmlRegistry.java index ca95c3f14eb..9e27e692688 100644 --- a/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/event/DeviceEventXmlRegistry.java +++ b/service/device/registry/api/src/main/java/org/eclipse/kapua/service/device/registry/event/DeviceEventXmlRegistry.java @@ -12,10 +12,10 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.registry.event; -import org.eclipse.kapua.locator.KapuaLocator; - import javax.xml.bind.annotation.XmlRegistry; +import org.eclipse.kapua.locator.KapuaLocator; + /** * {@link DeviceEvent} xml factory class. * @@ -35,16 +35,4 @@ public DeviceEvent newDeviceEvent() { return deviceEventFactory.newEntity(null); } - /** - * Creates a new device event list result - * - * @return - */ - public DeviceEventListResult newDeviceEventListResult() { - return deviceEventFactory.newListResult(); - } - - public DeviceEventQuery newQuery() { - return deviceEventFactory.newQuery(null); - } } diff --git a/service/device/registry/internal/pom.xml b/service/device/registry/internal/pom.xml index a45c35fb83a..4865a506f91 100644 --- a/service/device/registry/internal/pom.xml +++ b/service/device/registry/internal/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-device-registry - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-device-registry-internal diff --git a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/connection/listener/internal/DeviceConnectionEventListenerModule.java b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/connection/listener/internal/DeviceConnectionEventListenerModule.java index 7709e703544..53b55a0591d 100644 --- a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/connection/listener/internal/DeviceConnectionEventListenerModule.java +++ b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/connection/listener/internal/DeviceConnectionEventListenerModule.java @@ -12,24 +12,23 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.connection.listener.internal; -import com.google.inject.Module; -import com.google.inject.multibindings.ProvidesIntoSet; +import javax.inject.Named; + import org.eclipse.kapua.commons.core.AbstractKapuaModule; import org.eclipse.kapua.commons.core.ServiceModule; import org.eclipse.kapua.commons.event.ServiceEventHouseKeeperFactoryImpl; -import org.eclipse.kapua.commons.service.event.store.api.EventStoreFactory; import org.eclipse.kapua.commons.service.event.store.api.EventStoreRecordRepository; import org.eclipse.kapua.commons.service.event.store.internal.EventStoreServiceImpl; import org.eclipse.kapua.event.ServiceEventBus; import org.eclipse.kapua.event.ServiceEventBusException; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; import org.eclipse.kapua.service.device.connection.listener.DeviceConnectionEventListenerService; import org.eclipse.kapua.service.device.registry.KapuaDeviceRegistrySettingKeys; import org.eclipse.kapua.service.device.registry.KapuaDeviceRegistrySettings; import org.eclipse.kapua.storage.TxManager; -import javax.inject.Named; +import com.google.inject.Module; +import com.google.inject.multibindings.ProvidesIntoSet; /** * {@code kapua-account-internal} {@link Module} implementation. @@ -45,14 +44,12 @@ protected void configureModule() { @ProvidesIntoSet protected ServiceModule deviceConnectionEventListenerServiceModule(DeviceConnectionEventListenerService deviceConnectionEventListenerService, - AuthorizationService authorizationService, - PermissionFactory permissionFactory, - KapuaDeviceRegistrySettings kapuaDeviceRegistrySettings, - @Named("DeviceRegistryTransactionManager") TxManager txManager, - EventStoreFactory eventStoreFactory, - EventStoreRecordRepository eventStoreRecordRepository, - ServiceEventBus serviceEventBus, - @Named("eventsModuleName") String eventModuleName + AuthorizationService authorizationService, + KapuaDeviceRegistrySettings kapuaDeviceRegistrySettings, + @Named("DeviceRegistryTransactionManager") TxManager txManager, + EventStoreRecordRepository eventStoreRecordRepository, + ServiceEventBus serviceEventBus, + @Named("eventsModuleName") String eventModuleName ) throws ServiceEventBusException { String address = kapuaDeviceRegistrySettings.getString(KapuaDeviceRegistrySettingKeys.DEVICE_EVENT_ADDRESS); @@ -62,9 +59,7 @@ protected ServiceModule deviceConnectionEventListenerServiceModule(DeviceConnect new ServiceEventHouseKeeperFactoryImpl( new EventStoreServiceImpl( authorizationService, - permissionFactory, txManager, - eventStoreFactory, eventStoreRecordRepository ), txManager, diff --git a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/DeviceRegistryModule.java b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/DeviceRegistryModule.java index 789328be072..fd7b7c5af70 100644 --- a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/DeviceRegistryModule.java +++ b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/DeviceRegistryModule.java @@ -25,7 +25,6 @@ import org.eclipse.kapua.commons.jpa.KapuaJpaRepositoryConfiguration; import org.eclipse.kapua.commons.jpa.KapuaJpaTxManagerFactory; import org.eclipse.kapua.commons.model.domains.Domains; -import org.eclipse.kapua.commons.service.event.store.api.EventStoreFactory; import org.eclipse.kapua.commons.service.event.store.api.EventStoreRecordRepository; import org.eclipse.kapua.commons.service.event.store.internal.EventStoreServiceImpl; import org.eclipse.kapua.event.ServiceEventBus; @@ -36,7 +35,6 @@ import org.eclipse.kapua.service.authorization.AuthorizationService; import org.eclipse.kapua.service.authorization.access.GroupQueryHelper; import org.eclipse.kapua.service.authorization.group.GroupService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; import org.eclipse.kapua.service.device.authentication.api.DeviceConnectionCredentialAdapter; import org.eclipse.kapua.service.device.registry.common.DeviceValidation; import org.eclipse.kapua.service.device.registry.common.DeviceValidationImpl; @@ -121,9 +119,6 @@ public Domain deviceEventDomain() { ServiceModule deviceRegistryModule(DeviceConnectionService deviceConnectionService, DeviceRegistryService deviceRegistryService, AuthorizationService authorizationService, - PermissionFactory permissionFactory, - KapuaJpaTxManagerFactory txManagerFactory, - EventStoreFactory eventStoreFactory, EventStoreRecordRepository eventStoreRecordRepository, ServiceEventBus serviceEventBus, KapuaDeviceRegistrySettings kapuaDeviceRegistrySettings, @@ -137,9 +132,7 @@ ServiceModule deviceRegistryModule(DeviceConnectionService deviceConnectionServi new ServiceEventHouseKeeperFactoryImpl( new EventStoreServiceImpl( authorizationService, - permissionFactory, jpaTxManagerFactory.create("kapua-device"), - eventStoreFactory, eventStoreRecordRepository ), jpaTxManagerFactory.create("kapua-device"), @@ -153,22 +146,18 @@ ServiceModule deviceRegistryModule(DeviceConnectionService deviceConnectionServi @Singleton DeviceValidation deviceValidation(KapuaDeviceRegistrySettings deviceRegistrySettings, AuthorizationService authorizationService, - PermissionFactory permissionFactory, GroupService groupService, DeviceConnectionService deviceConnectionService, DeviceEventService deviceEventService, DeviceRepository deviceRepository, - DeviceFactory deviceFactory, TagService tagService) { return new DeviceValidationImpl(deviceRegistrySettings.getInt(KapuaDeviceRegistrySettingKeys.DEVICE_LIFECYCLE_BIRTH_VAR_FIELDS_LENGTH_MAX), deviceRegistrySettings.getInt(KapuaDeviceRegistrySettingKeys.DEVICE_LIFECYCLE_BIRTH_EXTENDED_PROPERTIES_LENGTH_MAX), authorizationService, - permissionFactory, groupService, deviceConnectionService, deviceEventService, deviceRepository, - deviceFactory, tagService); } @@ -177,7 +166,6 @@ DeviceValidation deviceValidation(KapuaDeviceRegistrySettings deviceRegistrySett DeviceRegistryService deviceRegistryService( Map, ServiceConfigurationManager> serviceConfigurationManagersByServiceClass, AuthorizationService authorizationService, - PermissionFactory permissionFactory, DeviceRepository deviceRepository, DeviceFactory deviceFactory, GroupQueryHelper groupQueryHelper, @@ -187,7 +175,6 @@ DeviceRegistryService deviceRegistryService( return new DeviceRegistryServiceImpl( serviceConfigurationManagersByServiceClass.get(DeviceRegistryService.class), authorizationService, - permissionFactory, deviceRegistryTxManager, deviceRepository, deviceFactory, @@ -233,7 +220,6 @@ protected DeviceConnectionRepository deviceConnectionRepository(DeviceRegistryCa @Singleton protected DeviceConnectionOptionService deviceConnectionOptionService( AuthorizationService authorizationService, - PermissionFactory permissionFactory, DeviceConnectionRepository deviceConnectionRepository, DeviceConnectionFactory entityFactory, DeviceConnectionOptionRepository repository, @@ -241,7 +227,6 @@ protected DeviceConnectionOptionService deviceConnectionOptionService( Map availableDeviceConnectionAdapters) { return new DeviceConnectionOptionServiceImpl( authorizationService, - permissionFactory, txManager, deviceConnectionRepository, entityFactory, @@ -259,14 +244,12 @@ protected DeviceConnectionOptionRepository deviceConnectionOptionRepository(Kapu @Singleton protected DeviceEventService deviceEventService( AuthorizationService authorizationService, - PermissionFactory permissionFactory, DeviceRepository deviceRepository, DeviceEventFactory entityFactory, DeviceEventRepository deviceEventRepository, @Named("DeviceRegistryTransactionManager") TxManager txManager) { return new DeviceEventServiceImpl( authorizationService, - permissionFactory, txManager, deviceRepository, entityFactory, diff --git a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/DeviceRegistryServiceConfigurationManagerModule.java b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/DeviceRegistryServiceConfigurationManagerModule.java index df5b64b39bc..8e920c64172 100644 --- a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/DeviceRegistryServiceConfigurationManagerModule.java +++ b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/DeviceRegistryServiceConfigurationManagerModule.java @@ -52,7 +52,6 @@ protected void configureModule() { @Singleton protected ServiceConfigurationManager deviceRegistryServiceConfigurationManager( @Named("DeviceRegistryTransactionManager") TxManager txManager, - DeviceFactory factory, RootUserTester rootUserTester, AccountRelativeFinder accountRelativeFinder, DeviceRepository deviceRepository, @@ -72,7 +71,6 @@ protected ServiceConfigurationManager deviceRegistryServiceConfigurationManager( rootUserTester, accountRelativeFinder, new UsedEntitiesCounterImpl( - factory, deviceRepository), new ResourceBasedServiceConfigurationMetadataProvider(xmlUtil) )); diff --git a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/common/DeviceValidationImpl.java b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/common/DeviceValidationImpl.java index 0cf7699141c..328337a0e7e 100644 --- a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/common/DeviceValidationImpl.java +++ b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/common/DeviceValidationImpl.java @@ -13,13 +13,13 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.registry.common; -import com.google.common.base.Strings; +import java.util.List; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.commons.model.domains.Domains; import org.eclipse.kapua.commons.security.KapuaSecurityUtils; import org.eclipse.kapua.commons.util.ArgumentValidator; import org.eclipse.kapua.model.KapuaEntityAttributes; -import org.eclipse.kapua.model.KapuaUpdatableEntity; import org.eclipse.kapua.model.domain.Actions; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.model.query.KapuaQuery; @@ -27,11 +27,9 @@ import org.eclipse.kapua.service.authorization.group.Group; import org.eclipse.kapua.service.authorization.group.GroupService; import org.eclipse.kapua.service.authorization.permission.Permission; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; import org.eclipse.kapua.service.device.registry.Device; import org.eclipse.kapua.service.device.registry.DeviceCreator; import org.eclipse.kapua.service.device.registry.DeviceExtendedProperty; -import org.eclipse.kapua.service.device.registry.DeviceFactory; import org.eclipse.kapua.service.device.registry.DeviceListResult; import org.eclipse.kapua.service.device.registry.DeviceQuery; import org.eclipse.kapua.service.device.registry.DeviceRegistryService; @@ -43,7 +41,7 @@ import org.eclipse.kapua.service.user.User; import org.eclipse.kapua.storage.TxContext; -import java.util.List; +import com.google.common.base.Strings; /** * Logic used to validate preconditions required to execute the {@link DeviceRegistryServiceImpl} operations. @@ -55,44 +53,42 @@ public final class DeviceValidationImpl implements DeviceValidation { private final Integer birthFieldsClobMaxLength; private final Integer birthFieldsExtendedPropertyValueMaxLength; private final AuthorizationService authorizationService; - private final PermissionFactory permissionFactory; private final GroupService groupService; private final DeviceConnectionService deviceConnectionService; private final DeviceEventService deviceEventService; private final DeviceRepository deviceRepository; - private final DeviceFactory deviceFactory; private final TagService tagService; public DeviceValidationImpl( Integer birthFieldsClobMaxLength, Integer birthFieldsExtendedPropertyValueMaxLength, AuthorizationService authorizationService, - PermissionFactory permissionFactory, GroupService groupService, DeviceConnectionService deviceConnectionService, DeviceEventService deviceEventService, DeviceRepository deviceRepository, - DeviceFactory deviceFactory, TagService tagService) { this.birthFieldsClobMaxLength = birthFieldsClobMaxLength; this.birthFieldsExtendedPropertyValueMaxLength = birthFieldsExtendedPropertyValueMaxLength; this.authorizationService = authorizationService; - this.permissionFactory = permissionFactory; this.groupService = groupService; this.deviceConnectionService = deviceConnectionService; this.deviceEventService = deviceEventService; this.deviceRepository = deviceRepository; - this.deviceFactory = deviceFactory; this.tagService = tagService; } /** * Validates the {@link DeviceCreator}. * - * @param deviceCreator The {@link DeviceCreator} to validate. - * @throws org.eclipse.kapua.KapuaIllegalArgumentException if one of the {@link DeviceCreator} fields is invalid. - * @throws org.eclipse.kapua.service.authorization.exception.SubjectUnauthorizedException if current {@link User} does not have sufficient {@link Permission}s - * @throws KapuaException if there are other errors. + * @param deviceCreator + * The {@link DeviceCreator} to validate. + * @throws org.eclipse.kapua.KapuaIllegalArgumentException + * if one of the {@link DeviceCreator} fields is invalid. + * @throws org.eclipse.kapua.service.authorization.exception.SubjectUnauthorizedException + * if current {@link User} does not have sufficient {@link Permission}s + * @throws KapuaException + * if there are other errors. * @since 1.0.0 */ @Override @@ -259,16 +255,20 @@ public void validateCreatePreconditions(DeviceCreator deviceCreator) throws Kapu } } // Check access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE, Actions.write, deviceCreator.getScopeId(), deviceCreator.getGroupId())); + authorizationService.checkPermission(new Permission(Domains.DEVICE, Actions.write, deviceCreator.getScopeId(), deviceCreator.getGroupId())); } /** - * Validates the {@link Device} for {@link DeviceRegistryService#update(KapuaUpdatableEntity)} operation. + * Validates the {@link Device} for {@link DeviceRegistryService#update(Object)} operation. * - * @param device The {@link Device} to validate. - * @throws org.eclipse.kapua.KapuaIllegalArgumentException if one of the {@link Device} fields is invalid. - * @throws org.eclipse.kapua.service.authorization.exception.SubjectUnauthorizedException if current {@link User} does not have sufficient {@link Permission}s - * @throws KapuaException if there are other errors. + * @param device + * The {@link Device} to validate. + * @throws org.eclipse.kapua.KapuaIllegalArgumentException + * if one of the {@link Device} fields is invalid. + * @throws org.eclipse.kapua.service.authorization.exception.SubjectUnauthorizedException + * if current {@link User} does not have sufficient {@link Permission}s + * @throws KapuaException + * if there are other errors. * @since 1.0.0 */ @Override @@ -286,7 +286,7 @@ public void validateUpdatePreconditions(TxContext txContext, Device device) thro // .groupId // Check that current User can manage the current Group of the Device KapuaId currentGroupId = findCurrentGroupId(txContext, device.getScopeId(), device.getId()); - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE, Actions.write, device.getScopeId(), currentGroupId)); + authorizationService.checkPermission(new Permission(Domains.DEVICE, Actions.write, device.getScopeId(), currentGroupId)); // Check that current User can manage the target Group of the Device if (device.getGroupId() != null) { @@ -295,7 +295,7 @@ public void validateUpdatePreconditions(TxContext txContext, Device device) thro () -> groupService.find(device.getScopeId(), device.getGroupId()) ), "device.groupId"); } - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE, Actions.write, device.getScopeId(), device.getGroupId())); + authorizationService.checkPermission(new Permission(Domains.DEVICE, Actions.write, device.getScopeId(), device.getGroupId())); // .status ArgumentValidator.notNull(device.getStatus(), "device.status"); @@ -455,11 +455,16 @@ public void validateUpdatePreconditions(TxContext txContext, Device device) thro /** * Validates the parameters for {@link DeviceRegistryService#find(KapuaId, KapuaId)} operation. * - * @param scopeId The {@link Device#getScopeId()} - * @param deviceId The {@link Device#getId()} - * @throws org.eclipse.kapua.KapuaIllegalArgumentException if one of the parameters is invalid. - * @throws org.eclipse.kapua.service.authorization.exception.SubjectUnauthorizedException if current {@link User} does not have sufficient {@link Permission}s - * @throws KapuaException if there are other errors. + * @param scopeId + * The {@link Device#getScopeId()} + * @param deviceId + * The {@link Device#getId()} + * @throws org.eclipse.kapua.KapuaIllegalArgumentException + * if one of the parameters is invalid. + * @throws org.eclipse.kapua.service.authorization.exception.SubjectUnauthorizedException + * if current {@link User} does not have sufficient {@link Permission}s + * @throws KapuaException + * if there are other errors. * @since 1.0.0 */ @Override @@ -469,16 +474,20 @@ public void validateFindPreconditions(TxContext txContext, KapuaId scopeId, Kapu ArgumentValidator.notNull(deviceId, "deviceId"); // Check access KapuaId groupId = findCurrentGroupId(txContext, scopeId, deviceId); - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE, Actions.read, scopeId, groupId)); + authorizationService.checkPermission(new Permission(Domains.DEVICE, Actions.read, scopeId, groupId)); } /** * Validates the {@link KapuaQuery} for {@link DeviceRegistryService#query(KapuaQuery)} operation. * - * @param query The {@link KapuaQuery} to validate. - * @throws org.eclipse.kapua.KapuaIllegalArgumentException if one of the {@link KapuaQuery} fields is invalid. - * @throws org.eclipse.kapua.service.authorization.exception.SubjectUnauthorizedException if current {@link User} does not have sufficient {@link Permission}s - * @throws KapuaException if there are other errors. + * @param query + * The {@link KapuaQuery} to validate. + * @throws org.eclipse.kapua.KapuaIllegalArgumentException + * if one of the {@link KapuaQuery} fields is invalid. + * @throws org.eclipse.kapua.service.authorization.exception.SubjectUnauthorizedException + * if current {@link User} does not have sufficient {@link Permission}s + * @throws KapuaException + * if there are other errors. * @since 1.0.0 */ @Override @@ -494,16 +503,20 @@ public void validateQueryPreconditions(KapuaQuery query) throws KapuaException { } } // Check access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE, Actions.read, query.getScopeId(), Group.ANY)); + authorizationService.checkPermission(new Permission(Domains.DEVICE, Actions.read, query.getScopeId(), Group.ANY)); } /** * Validates the {@link KapuaQuery} for {@link DeviceRegistryService#count(KapuaQuery)} operation. * - * @param query The {@link KapuaQuery} to validate. - * @throws org.eclipse.kapua.KapuaIllegalArgumentException if one of the {@link KapuaQuery} fields is invalid. - * @throws org.eclipse.kapua.service.authorization.exception.SubjectUnauthorizedException if current {@link User} does not have sufficient {@link Permission}s - * @throws KapuaException if there are other errors. + * @param query + * The {@link KapuaQuery} to validate. + * @throws org.eclipse.kapua.KapuaIllegalArgumentException + * if one of the {@link KapuaQuery} fields is invalid. + * @throws org.eclipse.kapua.service.authorization.exception.SubjectUnauthorizedException + * if current {@link User} does not have sufficient {@link Permission}s + * @throws KapuaException + * if there are other errors. * @since 1.0.0 */ @Override @@ -511,17 +524,22 @@ public void validateCountPreconditions(KapuaQuery query) throws KapuaException { // Argument validation ArgumentValidator.notNull(query, "query"); // Check access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE, Actions.read, query.getScopeId(), Group.ANY)); + authorizationService.checkPermission(new Permission(Domains.DEVICE, Actions.read, query.getScopeId(), Group.ANY)); } /** * Validates the parameters for {@link DeviceRegistryService#delete(KapuaId, KapuaId)} operation. * - * @param scopeId The {@link Device#getScopeId()} - * @param deviceId The {@link Device#getId()} - * @throws org.eclipse.kapua.KapuaIllegalArgumentException if one of the parameters is invalid. - * @throws org.eclipse.kapua.service.authorization.exception.SubjectUnauthorizedException if current {@link User} does not have sufficient {@link Permission}s - * @throws KapuaException if there are other errors. + * @param scopeId + * The {@link Device#getScopeId()} + * @param deviceId + * The {@link Device#getId()} + * @throws org.eclipse.kapua.KapuaIllegalArgumentException + * if one of the parameters is invalid. + * @throws org.eclipse.kapua.service.authorization.exception.SubjectUnauthorizedException + * if current {@link User} does not have sufficient {@link Permission}s + * @throws KapuaException + * if there are other errors. * @since 1.0.0 */ @Override @@ -531,17 +549,22 @@ public void validateDeletePreconditions(TxContext txContext, KapuaId scopeId, Ka ArgumentValidator.notNull(deviceId, "deviceId"); // Check access KapuaId groupId = findCurrentGroupId(txContext, scopeId, deviceId); - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE, Actions.delete, scopeId, groupId)); + authorizationService.checkPermission(new Permission(Domains.DEVICE, Actions.delete, scopeId, groupId)); } /** * Validates the parameters for {@link DeviceRegistryService#findByClientId(KapuaId, String)} operation. * - * @param scopeId The {@link Device#getScopeId()} - * @param clientId The {@link Device#getClientId()} - * @throws org.eclipse.kapua.KapuaIllegalArgumentException if one of the parameters is invalid. - * @throws org.eclipse.kapua.service.authorization.exception.SubjectUnauthorizedException if current {@link User} does not have sufficient {@link Permission}s - * @throws KapuaException if there are other errors. + * @param scopeId + * The {@link Device#getScopeId()} + * @param clientId + * The {@link Device#getClientId()} + * @throws org.eclipse.kapua.KapuaIllegalArgumentException + * if one of the parameters is invalid. + * @throws org.eclipse.kapua.service.authorization.exception.SubjectUnauthorizedException + * if current {@link User} does not have sufficient {@link Permission}s + * @throws KapuaException + * if there are other errors. * @since 1.0.0 */ @Override @@ -555,14 +578,17 @@ public void validateFindByClientIdPreconditions(KapuaId scopeId, String clientId /** * Finds the current {@link Group} id assigned to the given {@link Device#getId()}. * - * @param scopeId The {@link Device#getScopeId()} - * @param entityId The {@link Device#getId()} + * @param scopeId + * The {@link Device#getScopeId()} + * @param entityId + * The {@link Device#getId()} * @return The {@link Group} id found. - * @throws KapuaException if any error occurs while looking for the Group. + * @throws KapuaException + * if any error occurs while looking for the Group. * @since 1.0.0 */ private KapuaId findCurrentGroupId(TxContext tx, KapuaId scopeId, KapuaId entityId) throws KapuaException { - DeviceQuery query = deviceFactory.newQuery(scopeId); + DeviceQuery query = new DeviceQuery(scopeId); query.setPredicate(query.attributePredicate(KapuaEntityAttributes.ENTITY_ID, entityId)); DeviceListResult results; diff --git a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/connection/internal/DeviceConnectionCreatorImpl.java b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/connection/internal/DeviceConnectionCreatorImpl.java deleted file mode 100644 index 81d0e9406b6..00000000000 --- a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/connection/internal/DeviceConnectionCreatorImpl.java +++ /dev/null @@ -1,161 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.registry.connection.internal; - -import org.eclipse.kapua.commons.model.AbstractKapuaUpdatableEntityCreator; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.device.registry.ConnectionUserCouplingMode; -import org.eclipse.kapua.service.device.registry.connection.DeviceConnection; -import org.eclipse.kapua.service.device.registry.connection.DeviceConnectionCreator; -import org.eclipse.kapua.service.device.registry.connection.DeviceConnectionStatus; - -/** - * {@link DeviceConnectionCreator} implementation. - * - * @since 1.0.0 - */ -public class DeviceConnectionCreatorImpl extends AbstractKapuaUpdatableEntityCreator implements DeviceConnectionCreator { - - private static final long serialVersionUID = 2740394157765904615L; - - private DeviceConnectionStatus status; - private String clientId; - private KapuaId userId; - private ConnectionUserCouplingMode userCouplingMode; - private KapuaId reservedUserId; - private boolean allowUserChange; - private String authenticationType; - private String lastAuthenticationType; - private String protocol; - private String clientIp; - private String serverIp; - - /** - * Constructor - * - * @param scopeId - */ - public DeviceConnectionCreatorImpl(KapuaId scopeId) { - super(scopeId); - } - - @Override - public DeviceConnectionStatus getStatus() { - return status; - } - - @Override - public void setStatus(DeviceConnectionStatus status) { - this.status = status; - } - - @Override - public String getClientId() { - return clientId; - } - - @Override - public void setClientId(String clientId) { - this.clientId = clientId; - } - - @Override - public KapuaId getUserId() { - return userId; - } - - @Override - public void setUserId(KapuaId userId) { - this.userId = userId; - } - - @Override - public ConnectionUserCouplingMode getUserCouplingMode() { - return userCouplingMode; - } - - @Override - public void setUserCouplingMode(ConnectionUserCouplingMode userCouplingMode) { - this.userCouplingMode = userCouplingMode; - } - - @Override - public KapuaId getReservedUserId() { - return reservedUserId; - } - - @Override - public void setReservedUserId(KapuaId reservedUserId) { - this.reservedUserId = reservedUserId; - } - - @Override - public boolean getAllowUserChange() { - return allowUserChange; - } - - @Override - public void setAllowUserChange(boolean allowUserChange) { - this.allowUserChange = allowUserChange; - } - - @Override - public String getAuthenticationType() { - return authenticationType; - } - - @Override - public void setAuthenticationType(String authenticationType) { - this.authenticationType = authenticationType; - } - - @Override - public String getLastAuthenticationType() { - return lastAuthenticationType; - } - - @Override - public void setLastAuthenticationType(String lastAuthenticationType) { - this.lastAuthenticationType = lastAuthenticationType; - } - - @Override - public String getProtocol() { - return protocol; - } - - @Override - public void setProtocol(String protocol) { - this.protocol = protocol; - } - - @Override - public String getClientIp() { - return clientIp; - } - - @Override - public void setClientIp(String clientIp) { - this.clientIp = clientIp; - } - - @Override - public String getServerIp() { - return serverIp; - } - - @Override - public void setServerIp(String serverIp) { - this.serverIp = serverIp; - } -} diff --git a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/connection/internal/DeviceConnectionFactoryImpl.java b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/connection/internal/DeviceConnectionFactoryImpl.java index 2cfb367a158..8b6c9c85138 100644 --- a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/connection/internal/DeviceConnectionFactoryImpl.java +++ b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/connection/internal/DeviceConnectionFactoryImpl.java @@ -12,15 +12,12 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.registry.connection.internal; +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaEntityCloneException; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.device.registry.connection.DeviceConnection; -import org.eclipse.kapua.service.device.registry.connection.DeviceConnectionCreator; import org.eclipse.kapua.service.device.registry.connection.DeviceConnectionFactory; -import org.eclipse.kapua.service.device.registry.connection.DeviceConnectionListResult; -import org.eclipse.kapua.service.device.registry.connection.DeviceConnectionQuery; - -import javax.inject.Singleton; /** * {@link DeviceConnectionFactory} implementation. @@ -30,26 +27,11 @@ @Singleton public class DeviceConnectionFactoryImpl implements DeviceConnectionFactory { - @Override - public DeviceConnectionCreator newCreator(KapuaId scopeId) { - return new DeviceConnectionCreatorImpl(scopeId); - } - - @Override - public DeviceConnectionQuery newQuery(KapuaId scopeId) { - return new DeviceConnectionQueryImpl(scopeId); - } - @Override public DeviceConnection newEntity(KapuaId scopeId) { return new DeviceConnectionImpl(scopeId); } - @Override - public DeviceConnectionListResult newListResult() { - return new DeviceConnectionListResultImpl(); - } - @Override public DeviceConnection clone(DeviceConnection deviceConnection) { try { diff --git a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/connection/internal/DeviceConnectionImplJpaRepository.java b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/connection/internal/DeviceConnectionImplJpaRepository.java index 43a5329bcff..8af1a2ae703 100644 --- a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/connection/internal/DeviceConnectionImplJpaRepository.java +++ b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/connection/internal/DeviceConnectionImplJpaRepository.java @@ -16,6 +16,7 @@ import org.eclipse.kapua.commons.jpa.KapuaJpaRepositoryConfiguration; import org.eclipse.kapua.commons.jpa.KapuaUpdatableEntityJpaRepository; import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.service.device.registry.connection.DeviceConnection; import org.eclipse.kapua.service.device.registry.connection.DeviceConnectionAttributes; import org.eclipse.kapua.service.device.registry.connection.DeviceConnectionListResult; @@ -28,12 +29,12 @@ public class DeviceConnectionImplJpaRepository implements DeviceConnectionRepository { public DeviceConnectionImplJpaRepository(KapuaJpaRepositoryConfiguration jpaRepoConfig) { - super(DeviceConnectionImpl.class, DeviceConnection.TYPE, () -> new DeviceConnectionListResultImpl(), jpaRepoConfig); + super(DeviceConnectionImpl.class, DeviceConnection.TYPE, () -> new DeviceConnectionListResult(), jpaRepoConfig); } @Override public long countByClientId(TxContext tx, KapuaId scopeId, String clientId) throws KapuaException { - final DeviceConnectionQuery query = new DeviceConnectionQueryImpl(scopeId); + final KapuaQuery query = new DeviceConnectionQuery(scopeId); query.setPredicate(query.attributePredicate(DeviceConnectionAttributes.CLIENT_ID, clientId)); return this.count(tx, query); } diff --git a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/connection/internal/DeviceConnectionListResultImpl.java b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/connection/internal/DeviceConnectionListResultImpl.java deleted file mode 100644 index c8414fe0915..00000000000 --- a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/connection/internal/DeviceConnectionListResultImpl.java +++ /dev/null @@ -1,26 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.registry.connection.internal; - -import org.eclipse.kapua.commons.model.query.KapuaListResultImpl; -import org.eclipse.kapua.service.device.registry.connection.DeviceConnection; -import org.eclipse.kapua.service.device.registry.connection.DeviceConnectionListResult; - -/** - * Device connection list. - * - * @since 1.0 - */ -public class DeviceConnectionListResultImpl extends KapuaListResultImpl implements DeviceConnectionListResult { - private static final long serialVersionUID = -4450707993798807403L; -} diff --git a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/connection/internal/DeviceConnectionQueryImpl.java b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/connection/internal/DeviceConnectionQueryImpl.java deleted file mode 100644 index 2cbbd225ee1..00000000000 --- a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/connection/internal/DeviceConnectionQueryImpl.java +++ /dev/null @@ -1,53 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.registry.connection.internal; - -import org.eclipse.kapua.commons.model.query.AbstractKapuaQuery; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.model.query.KapuaSortCriteria; -import org.eclipse.kapua.model.query.SortOrder; -import org.eclipse.kapua.service.device.registry.DeviceAttributes; -import org.eclipse.kapua.service.device.registry.connection.DeviceConnectionQuery; - -/** - * {@link DeviceConnectionQuery} implementation. - * - * @since 1.0.0 - */ -public class DeviceConnectionQueryImpl extends AbstractKapuaQuery implements DeviceConnectionQuery { - - /** - * Constructor. - * - * @since 1.0.0 - */ - private DeviceConnectionQueryImpl() { - super(); - } - - /** - * Constructor. - * - * @param scopeId The {@link #getScopeId()}. - * @since 1.0.0 - */ - public DeviceConnectionQueryImpl(KapuaId scopeId) { - this(); - setScopeId(scopeId); - } - - @Override - public KapuaSortCriteria getDefaultSortCriteria() { - return fieldSortCriteria(DeviceAttributes.CLIENT_ID, SortOrder.ASCENDING); - } -} diff --git a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/connection/internal/DeviceConnectionServiceImpl.java b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/connection/internal/DeviceConnectionServiceImpl.java index b48ee3a9ce0..452adbf0dc9 100644 --- a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/connection/internal/DeviceConnectionServiceImpl.java +++ b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/connection/internal/DeviceConnectionServiceImpl.java @@ -35,7 +35,7 @@ import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; +import org.eclipse.kapua.service.authorization.permission.Permission; import org.eclipse.kapua.service.device.authentication.api.DeviceConnectionCredentialAdapter; import org.eclipse.kapua.service.device.registry.common.DeviceValidationRegex; import org.eclipse.kapua.service.device.registry.connection.DeviceConnection; @@ -74,13 +74,12 @@ public class DeviceConnectionServiceImpl extends KapuaConfigurableServiceBase im public DeviceConnectionServiceImpl( Map, ServiceConfigurationManager> serviceConfigurationManagersByServiceClass, AuthorizationService authorizationService, - PermissionFactory permissionFactory, DeviceConnectionFactory entityFactory, @Named("DeviceRegistryTransactionManager") TxManager txManager, DeviceConnectionRepository repository, Map availableDeviceConnectionAdapters, EventStorer eventStorer) { - super(txManager, serviceConfigurationManagersByServiceClass.get(DeviceConnectionService.class), Domains.DEVICE_CONNECTION, authorizationService, permissionFactory); + super(txManager, serviceConfigurationManagersByServiceClass.get(DeviceConnectionService.class), Domains.DEVICE_CONNECTION, authorizationService); this.entityFactory = entityFactory; this.repository = repository; this.availableDeviceConnectionAdapters = availableDeviceConnectionAdapters; @@ -104,7 +103,7 @@ public DeviceConnection create(DeviceConnectionCreator deviceConnectionCreator) throw new KapuaIllegalArgumentException("deviceConnectionCreator.authenticationType", deviceConnectionCreator.getAuthenticationType()); } // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE_CONNECTION, Actions.write, null)); + authorizationService.checkPermission(new Permission(Domains.DEVICE_CONNECTION, Actions.write, null)); return txManager.execute(tx -> { //TODO: check whether this is anywhere efficient // Check duplicate ClientId @@ -144,7 +143,7 @@ public DeviceConnection update(DeviceConnection deviceConnection) throw new KapuaIllegalArgumentException("deviceConnection.authenticationType", deviceConnection.getAuthenticationType()); } // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE_CONNECTION, Actions.write, null)); + authorizationService.checkPermission(new Permission(Domains.DEVICE_CONNECTION, Actions.write, null)); // Do Update return txManager.execute(tx -> repository.update(tx, deviceConnection)); } @@ -157,7 +156,7 @@ public DeviceConnection find(KapuaId scopeId, KapuaId entityId) ArgumentValidator.notNull(entityId, "entityId"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE_CONNECTION, Actions.read, scopeId)); + authorizationService.checkPermission(new Permission(Domains.DEVICE_CONNECTION, Actions.read, scopeId)); // Do find return txManager.execute(tx -> repository.find(tx, scopeId, entityId)) @@ -172,7 +171,7 @@ public DeviceConnection findByClientId(KapuaId scopeId, String clientId) ArgumentValidator.notEmptyOrNull(clientId, "clientId"); // Build query - DeviceConnectionQueryImpl query = new DeviceConnectionQueryImpl(scopeId); + DeviceConnectionQuery query = new DeviceConnectionQuery(scopeId); query.setPredicate(query.attributePredicate(DeviceConnectionAttributes.CLIENT_ID, clientId)); // Do find @@ -186,7 +185,7 @@ public DeviceConnectionListResult query(KapuaQuery query) ArgumentValidator.notNull(query, "query"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE_CONNECTION, Actions.read, query.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.DEVICE_CONNECTION, Actions.read, query.getScopeId())); // Do query return txManager.execute(tx -> repository.query(tx, query)); @@ -199,7 +198,7 @@ public long count(KapuaQuery query) ArgumentValidator.notNull(query, "query"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE_CONNECTION, Actions.read, query.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.DEVICE_CONNECTION, Actions.read, query.getScopeId())); // Do count return txManager.execute(tx -> repository.count(tx, query)); @@ -213,7 +212,7 @@ public void delete(KapuaId scopeId, KapuaId deviceConnectionId) ArgumentValidator.notNull(scopeId, "deviceConnection.scopeId"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE_CONNECTION, Actions.write, null)); + authorizationService.checkPermission(new Permission(Domains.DEVICE_CONNECTION, Actions.write, null)); txManager.execute(tx -> repository.delete(tx, scopeId, deviceConnectionId)); } @@ -238,7 +237,7 @@ public void disconnect(KapuaId scopeId, KapuaId deviceConnectionId) throws Kapua ArgumentValidator.notNull(scopeId, "deviceConnection.scopeId"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE_CONNECTION, Actions.write, null)); + authorizationService.checkPermission(new Permission(Domains.DEVICE_CONNECTION, Actions.write, null)); // Find the specified DeviceConnection DeviceConnection deviceConnection = txManager.execute( @@ -267,7 +266,7 @@ public void onKapuaEvent(ServiceEvent kapuaEvent) throws KapuaException { // Private methods private void deleteConnectionByAccountId(KapuaId scopeId, KapuaId accountId) throws KapuaException { - DeviceConnectionQuery query = entityFactory.newQuery(accountId); + DeviceConnectionQuery query = new DeviceConnectionQuery(accountId); txManager.execute(tx -> { final DeviceConnectionListResult deviceConnectionsToDelete = repository.query(tx, query); diff --git a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/connection/option/internal/DeviceConnectionOptionCreatorImpl.java b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/connection/option/internal/DeviceConnectionOptionCreatorImpl.java deleted file mode 100644 index 91fb23d48df..00000000000 --- a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/connection/option/internal/DeviceConnectionOptionCreatorImpl.java +++ /dev/null @@ -1,73 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.registry.connection.option.internal; - -import org.eclipse.kapua.commons.model.AbstractKapuaUpdatableEntityCreator; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.device.registry.ConnectionUserCouplingMode; -import org.eclipse.kapua.service.device.registry.connection.option.DeviceConnectionOption; -import org.eclipse.kapua.service.device.registry.connection.option.DeviceConnectionOptionCreator; - -/** - * Device connection creator service implementation. - * - * @since 1.0 - */ -public class DeviceConnectionOptionCreatorImpl extends AbstractKapuaUpdatableEntityCreator implements DeviceConnectionOptionCreator { - - private static final long serialVersionUID = 2740394157765904615L; - - private ConnectionUserCouplingMode userCouplingMode; - private KapuaId reservedUserId; - - private String authenticationType; - - /** - * Constructor - * - * @param scopeId - */ - public DeviceConnectionOptionCreatorImpl(KapuaId scopeId) { - super(scopeId); - } - - @Override - public ConnectionUserCouplingMode getUserCouplingMode() { - return userCouplingMode; - } - - @Override - public void setUserCouplingMode(ConnectionUserCouplingMode userCouplingMode) { - this.userCouplingMode = userCouplingMode; - } - - @Override - public KapuaId getReservedUserId() { - return reservedUserId; - } - - @Override - public void setReservedUserId(KapuaId reservedUserId) { - this.reservedUserId = reservedUserId; - } - - @Override - public String getAuthenticationType() { - return authenticationType; - } - - @Override - public void setAuthenticationType(String authenticationType) { - this.authenticationType = authenticationType; - } -} diff --git a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/connection/option/internal/DeviceConnectionOptionFactoryImpl.java b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/connection/option/internal/DeviceConnectionOptionFactoryImpl.java index cc6a3a70378..1228ea1d555 100644 --- a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/connection/option/internal/DeviceConnectionOptionFactoryImpl.java +++ b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/connection/option/internal/DeviceConnectionOptionFactoryImpl.java @@ -12,15 +12,12 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.registry.connection.option.internal; +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaEntityCloneException; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.device.registry.connection.option.DeviceConnectionOption; -import org.eclipse.kapua.service.device.registry.connection.option.DeviceConnectionOptionCreator; import org.eclipse.kapua.service.device.registry.connection.option.DeviceConnectionOptionFactory; -import org.eclipse.kapua.service.device.registry.connection.option.DeviceConnectionOptionListResult; -import org.eclipse.kapua.service.device.registry.connection.option.DeviceConnectionOptionQuery; - -import javax.inject.Singleton; /** * {@link DeviceConnectionOptionFactory} implementation. @@ -30,26 +27,11 @@ @Singleton public class DeviceConnectionOptionFactoryImpl implements DeviceConnectionOptionFactory { - @Override - public DeviceConnectionOptionCreator newCreator(KapuaId scopeId) { - return new DeviceConnectionOptionCreatorImpl(scopeId); - } - - @Override - public DeviceConnectionOptionQuery newQuery(KapuaId scopeId) { - return new DeviceConnectionOptionQueryImpl(scopeId); - } - @Override public DeviceConnectionOption newEntity(KapuaId scopeId) { return new DeviceConnectionOptionImpl(scopeId); } - @Override - public DeviceConnectionOptionListResult newListResult() { - return new DeviceConnectionOptionListResultImpl(); - } - @Override public DeviceConnectionOption clone(DeviceConnectionOption deviceConnectionOption) { try { diff --git a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/connection/option/internal/DeviceConnectionOptionImplJpaRepository.java b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/connection/option/internal/DeviceConnectionOptionImplJpaRepository.java index 63375409a5a..930c2344323 100644 --- a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/connection/option/internal/DeviceConnectionOptionImplJpaRepository.java +++ b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/connection/option/internal/DeviceConnectionOptionImplJpaRepository.java @@ -21,7 +21,8 @@ public class DeviceConnectionOptionImplJpaRepository extends KapuaUpdatableEntityJpaRepository implements DeviceConnectionOptionRepository { + public DeviceConnectionOptionImplJpaRepository(KapuaJpaRepositoryConfiguration jpaRepoConfig) { - super(DeviceConnectionOptionImpl.class, DeviceConnectionOption.TYPE, () -> new DeviceConnectionOptionListResultImpl(), jpaRepoConfig); + super(DeviceConnectionOptionImpl.class, DeviceConnectionOption.TYPE, () -> new DeviceConnectionOptionListResult(), jpaRepoConfig); } } diff --git a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/connection/option/internal/DeviceConnectionOptionListResultImpl.java b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/connection/option/internal/DeviceConnectionOptionListResultImpl.java deleted file mode 100644 index 002d804adcb..00000000000 --- a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/connection/option/internal/DeviceConnectionOptionListResultImpl.java +++ /dev/null @@ -1,27 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.registry.connection.option.internal; - -import org.eclipse.kapua.commons.model.query.KapuaListResultImpl; -import org.eclipse.kapua.service.device.registry.connection.option.DeviceConnectionOption; -import org.eclipse.kapua.service.device.registry.connection.option.DeviceConnectionOptionListResult; - -/** - * Device connection options list. - * - * @since 1.0.0 - */ -public class DeviceConnectionOptionListResultImpl extends KapuaListResultImpl implements DeviceConnectionOptionListResult { - - private static final long serialVersionUID = -4450707993798807403L; -} diff --git a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/connection/option/internal/DeviceConnectionOptionQueryImpl.java b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/connection/option/internal/DeviceConnectionOptionQueryImpl.java deleted file mode 100644 index fd4ca1102d1..00000000000 --- a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/connection/option/internal/DeviceConnectionOptionQueryImpl.java +++ /dev/null @@ -1,45 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.registry.connection.option.internal; - -import org.eclipse.kapua.commons.model.query.AbstractKapuaQuery; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.device.registry.connection.option.DeviceConnectionOptionQuery; - -/** - * {@link DeviceConnectionOptionQuery} implementation. - * - * @since 1.0.0 - */ -public class DeviceConnectionOptionQueryImpl extends AbstractKapuaQuery implements DeviceConnectionOptionQuery { - - /** - * Constructor. - * - * @since 1.0.0 - */ - private DeviceConnectionOptionQueryImpl() { - super(); - } - - /** - * Constructor. - * - * @param scopeId The {@link #getScopeId()}. - * @since 1.0.0 - */ - public DeviceConnectionOptionQueryImpl(KapuaId scopeId) { - this(); - setScopeId(scopeId); - } -} diff --git a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/connection/option/internal/DeviceConnectionOptionServiceImpl.java b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/connection/option/internal/DeviceConnectionOptionServiceImpl.java index b3a15a5c37e..0fdfe3ac4f1 100644 --- a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/connection/option/internal/DeviceConnectionOptionServiceImpl.java +++ b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/connection/option/internal/DeviceConnectionOptionServiceImpl.java @@ -12,6 +12,11 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.registry.connection.option.internal; +import java.util.Map; + +import javax.inject.Inject; +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaEntityNotFoundException; import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.KapuaIllegalArgumentException; @@ -25,11 +30,10 @@ import org.eclipse.kapua.model.query.predicate.AndPredicate; import org.eclipse.kapua.model.query.predicate.AttributePredicate.Operator; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; +import org.eclipse.kapua.service.authorization.permission.Permission; import org.eclipse.kapua.service.device.authentication.api.DeviceConnectionCredentialAdapter; import org.eclipse.kapua.service.device.registry.connection.DeviceConnectionAttributes; import org.eclipse.kapua.service.device.registry.connection.DeviceConnectionFactory; -import org.eclipse.kapua.service.device.registry.connection.DeviceConnectionQuery; import org.eclipse.kapua.service.device.registry.connection.DeviceConnectionRepository; import org.eclipse.kapua.service.device.registry.connection.option.DeviceConnectionOption; import org.eclipse.kapua.service.device.registry.connection.option.DeviceConnectionOptionCreator; @@ -39,13 +43,8 @@ import org.eclipse.kapua.service.device.registry.connection.option.UserAlreadyReservedException; import org.eclipse.kapua.storage.TxManager; -import javax.inject.Inject; -import javax.inject.Singleton; -import java.util.Map; - /** - * DeviceConnectionService exposes APIs to retrieve Device connections under a scope. - * It includes APIs to find, list, and update devices connections associated with a scope. + * DeviceConnectionService exposes APIs to retrieve Device connections under a scope. It includes APIs to find, list, and update devices connections associated with a scope. * * @since 1.0 */ @@ -53,7 +52,6 @@ public class DeviceConnectionOptionServiceImpl implements DeviceConnectionOptionService { private final AuthorizationService authorizationService; - private final PermissionFactory permissionFactory; private final TxManager txManager; private final DeviceConnectionRepository deviceConnectionRepository; private final DeviceConnectionFactory entityFactory; @@ -63,14 +61,12 @@ public class DeviceConnectionOptionServiceImpl implements DeviceConnectionOption @Inject public DeviceConnectionOptionServiceImpl( AuthorizationService authorizationService, - PermissionFactory permissionFactory, TxManager txManager, DeviceConnectionRepository deviceConnectionRepository, DeviceConnectionFactory entityFactory, DeviceConnectionOptionRepository repository, Map availableDeviceConnectionAdapters) { this.authorizationService = authorizationService; - this.permissionFactory = permissionFactory; this.txManager = txManager; this.deviceConnectionRepository = deviceConnectionRepository; this.entityFactory = entityFactory; @@ -95,10 +91,10 @@ public DeviceConnectionOption update(DeviceConnectionOption deviceConnectionOpti if (!availableDeviceConnectionAdapters.containsKey(deviceConnectionOptions.getAuthenticationType())) { throw new KapuaIllegalArgumentException("deviceConnection.authenticationType", deviceConnectionOptions.getAuthenticationType()); } - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE_CONNECTION, Actions.write, deviceConnectionOptions.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.DEVICE_CONNECTION, Actions.write, deviceConnectionOptions.getScopeId())); return txManager.execute(tx -> { if (deviceConnectionOptions.getReservedUserId() != null) { - DeviceConnectionQuery query = entityFactory.newQuery(deviceConnectionOptions.getScopeId()); + final KapuaQuery query = new KapuaQuery(deviceConnectionOptions.getScopeId()); AndPredicate deviceAndPredicate = query.andPredicate( query.attributePredicate(DeviceConnectionAttributes.RESERVED_USER_ID, deviceConnectionOptions.getReservedUserId()), @@ -126,7 +122,7 @@ public DeviceConnectionOption find(KapuaId scopeId, KapuaId entityId) ArgumentValidator.notNull(scopeId, "scopeId"); ArgumentValidator.notNull(entityId, "entityId"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE_CONNECTION, Actions.read, scopeId)); + authorizationService.checkPermission(new Permission(Domains.DEVICE_CONNECTION, Actions.read, scopeId)); return txManager.execute(tx -> repository.find(tx, scopeId, entityId)) .orElse(null); @@ -138,7 +134,7 @@ public DeviceConnectionOptionListResult query(KapuaQuery query) // Argument Validation ArgumentValidator.notNull(query, "query"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE_CONNECTION, Actions.read, query.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.DEVICE_CONNECTION, Actions.read, query.getScopeId())); return txManager.execute(tx -> repository.query(tx, query)); } @@ -149,7 +145,7 @@ public long count(KapuaQuery query) // Argument Validation ArgumentValidator.notNull(query, "query"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE_CONNECTION, Actions.read, query.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.DEVICE_CONNECTION, Actions.read, query.getScopeId())); return txManager.execute(tx -> repository.count(tx, query)); } diff --git a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/event/internal/DeviceEventCreatorImpl.java b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/event/internal/DeviceEventCreatorImpl.java deleted file mode 100644 index 4cafa287f29..00000000000 --- a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/event/internal/DeviceEventCreatorImpl.java +++ /dev/null @@ -1,148 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.registry.event.internal; - -import org.eclipse.kapua.commons.model.AbstractKapuaEntityCreator; -import org.eclipse.kapua.message.KapuaPosition; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.device.management.message.KapuaMethod; -import org.eclipse.kapua.service.device.management.message.response.KapuaResponseCode; -import org.eclipse.kapua.service.device.registry.event.DeviceEvent; -import org.eclipse.kapua.service.device.registry.event.DeviceEventCreator; - -import javax.xml.bind.annotation.XmlElement; -import java.util.Date; - -/** - * Device event creator service implementation. - * - * @since 1.0 - */ -public class DeviceEventCreatorImpl extends AbstractKapuaEntityCreator implements DeviceEventCreator { - - private static final long serialVersionUID = -3982569213440658172L; - - @XmlElement(name = "deviceId") - private KapuaId deviceId; - - @XmlElement(name = "receivedOn") - private Date receivedOn; - - @XmlElement(name = "sentOn") - private Date sentOn; - - @XmlElement(name = "position") - private KapuaPosition position; - - @XmlElement(name = "resource") - private String resource; - - @XmlElement(name = "action") - private KapuaMethod action; - - @XmlElement(name = "responseCode") - private KapuaResponseCode responseCode; - - @XmlElement(name = "eventMessage") - private String eventMessage; - - /** - * Constructor - * - * @param scopeId - */ - protected DeviceEventCreatorImpl(KapuaId scopeId) { - super(scopeId); - } - - @Override - public KapuaId getDeviceId() { - return deviceId; - } - - @Override - public void setDeviceId(KapuaId deviceId) { - this.deviceId = deviceId; - } - - @Override - public Date getSentOn() { - return sentOn != null ? new Date(sentOn.getTime()) : null; - } - - @Override - public void setSentOn(Date sentOn) { - this.sentOn = sentOn; - } - - @Override - public Date getReceivedOn() { - return receivedOn != null ? new Date(receivedOn.getTime()) : null; - } - - @Override - public void setReceivedOn(Date receivedOn) { - this.receivedOn = receivedOn; - } - - @Override - public KapuaPosition getPosition() { - return position; - } - - @Override - public void setPosition(KapuaPosition position) { - this.position = position; - } - - @Override - public String getResource() { - return resource; - } - - @Override - public void setResource(String resource) { - this.resource = resource; - } - - @Override - public KapuaMethod getAction() { - return action.normalizeAction(); - } - - @Override - public void setAction(KapuaMethod action) { - this.action = action.normalizeAction(); - } - - @Override - public KapuaResponseCode getResponseCode() { - return responseCode; - } - - @Override - public void setResponseCode(KapuaResponseCode responseCode) { - this.responseCode = responseCode; - } - - @Override - public String getEventMessage() { - return eventMessage; - } - - @Override - public void setEventMessage(String eventMessage) { - this.eventMessage = eventMessage; - } - -} diff --git a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/event/internal/DeviceEventFactoryImpl.java b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/event/internal/DeviceEventFactoryImpl.java index 223cc0e63d6..217276be88b 100644 --- a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/event/internal/DeviceEventFactoryImpl.java +++ b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/event/internal/DeviceEventFactoryImpl.java @@ -12,16 +12,11 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.registry.event.internal; +import javax.inject.Singleton; + import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.device.management.message.KapuaMethod; import org.eclipse.kapua.service.device.registry.event.DeviceEvent; -import org.eclipse.kapua.service.device.registry.event.DeviceEventCreator; import org.eclipse.kapua.service.device.registry.event.DeviceEventFactory; -import org.eclipse.kapua.service.device.registry.event.DeviceEventListResult; -import org.eclipse.kapua.service.device.registry.event.DeviceEventQuery; - -import javax.inject.Singleton; -import java.util.Date; /** * {@link DeviceEventFactory} implementation. @@ -31,38 +26,11 @@ @Singleton public class DeviceEventFactoryImpl implements DeviceEventFactory { - @Override - public DeviceEventCreator newCreator(KapuaId scopeId, KapuaId deviceId, Date receivedOn, String resource) { - DeviceEventCreator creator = newCreator(scopeId); - - creator.setDeviceId(deviceId); - creator.setAction(KapuaMethod.CREATE); - creator.setReceivedOn(new Date(receivedOn.getTime())); - creator.setResource(resource); - - return creator; - } - - @Override - public DeviceEventQuery newQuery(KapuaId scopeId) { - return new DeviceEventQueryImpl(scopeId); - } - @Override public DeviceEvent newEntity(KapuaId scopeId) { return new DeviceEventImpl(scopeId); } - @Override - public DeviceEventCreator newCreator(KapuaId scopeId) { - return new DeviceEventCreatorImpl(scopeId); - } - - @Override - public DeviceEventListResult newListResult() { - return new DeviceEventListResultImpl(); - } - @Override public DeviceEvent clone(DeviceEvent deviceEvent) { return new DeviceEventImpl(deviceEvent); diff --git a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/event/internal/DeviceEventImplJpaRepository.java b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/event/internal/DeviceEventImplJpaRepository.java index f77f26fadd7..4ff3d01f411 100644 --- a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/event/internal/DeviceEventImplJpaRepository.java +++ b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/event/internal/DeviceEventImplJpaRepository.java @@ -21,7 +21,8 @@ public class DeviceEventImplJpaRepository extends KapuaEntityJpaRepository implements DeviceEventRepository { + public DeviceEventImplJpaRepository(KapuaJpaRepositoryConfiguration configuration) { - super(DeviceEventImpl.class, DeviceEvent.TYPE, () -> new DeviceEventListResultImpl(), configuration); + super(DeviceEventImpl.class, DeviceEvent.TYPE, () -> new DeviceEventListResult(), configuration); } } diff --git a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/event/internal/DeviceEventListResultImpl.java b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/event/internal/DeviceEventListResultImpl.java deleted file mode 100644 index aba3659c2d0..00000000000 --- a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/event/internal/DeviceEventListResultImpl.java +++ /dev/null @@ -1,27 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.registry.event.internal; - -import org.eclipse.kapua.commons.model.query.KapuaListResultImpl; -import org.eclipse.kapua.service.device.registry.event.DeviceEvent; -import org.eclipse.kapua.service.device.registry.event.DeviceEventListResult; - -/** - * Device event list. - * - * @since 1.0 - */ -public class DeviceEventListResultImpl extends KapuaListResultImpl implements DeviceEventListResult { - - private static final long serialVersionUID = 6537888946643944463L; -} diff --git a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/event/internal/DeviceEventQueryImpl.java b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/event/internal/DeviceEventQueryImpl.java deleted file mode 100644 index a4b95d55674..00000000000 --- a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/event/internal/DeviceEventQueryImpl.java +++ /dev/null @@ -1,53 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.registry.event.internal; - -import org.eclipse.kapua.commons.model.query.AbstractKapuaQuery; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.model.query.KapuaSortCriteria; -import org.eclipse.kapua.model.query.SortOrder; -import org.eclipse.kapua.service.device.registry.event.DeviceEventAttributes; -import org.eclipse.kapua.service.device.registry.event.DeviceEventQuery; - -/** - * {@link DeviceEventQuery} implementation. - * - * @since 1.0.0 - */ -public class DeviceEventQueryImpl extends AbstractKapuaQuery implements DeviceEventQuery { - - /** - * Constructor. - * - * @since 1.0.0 - */ - private DeviceEventQueryImpl() { - super(); - } - - /** - * Constructor. - * - * @param scopeId The {@link #getScopeId()}. - * @since 1.0.0 - */ - public DeviceEventQueryImpl(KapuaId scopeId) { - this(); - setScopeId(scopeId); - } - - @Override - public KapuaSortCriteria getDefaultSortCriteria() { - return fieldSortCriteria(DeviceEventAttributes.RECEIVED_ON, SortOrder.DESCENDING); - } -} diff --git a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/event/internal/DeviceEventServiceImpl.java b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/event/internal/DeviceEventServiceImpl.java index a33666bf575..fbe847c3383 100644 --- a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/event/internal/DeviceEventServiceImpl.java +++ b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/event/internal/DeviceEventServiceImpl.java @@ -12,6 +12,9 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.registry.event.internal; +import javax.inject.Inject; +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaEntityNotFoundException; import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.commons.model.domains.Domains; @@ -20,7 +23,7 @@ import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; +import org.eclipse.kapua.service.authorization.permission.Permission; import org.eclipse.kapua.service.device.registry.Device; import org.eclipse.kapua.service.device.registry.DeviceRepository; import org.eclipse.kapua.service.device.registry.event.DeviceEvent; @@ -33,9 +36,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.inject.Inject; -import javax.inject.Singleton; - /** * {@link DeviceEventService} implementation. * @@ -51,7 +51,6 @@ public class DeviceEventServiceImpl private static final double MAX_WAIT = 200d; private final AuthorizationService authorizationService; - private final PermissionFactory permissionFactory; private final TxManager txManager; private final DeviceRepository deviceRepository; private final DeviceEventFactory entityFactory; @@ -60,13 +59,11 @@ public class DeviceEventServiceImpl @Inject public DeviceEventServiceImpl( AuthorizationService authorizationService, - PermissionFactory permissionFactory, TxManager txManager, DeviceRepository deviceRepository, DeviceEventFactory entityFactory, DeviceEventRepository deviceEventRepository) { this.authorizationService = authorizationService; - this.permissionFactory = permissionFactory; this.txManager = txManager; this.deviceRepository = deviceRepository; this.entityFactory = entityFactory; @@ -84,7 +81,7 @@ public DeviceEvent create(DeviceEventCreator deviceEventCreator) throws KapuaExc ArgumentValidator.notNull(deviceEventCreator.getReceivedOn(), "deviceEventCreator.receivedOn"); ArgumentValidator.notEmptyOrNull(deviceEventCreator.getResource(), "deviceEventCreator.eventType"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE_EVENT, Actions.write, deviceEventCreator.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.DEVICE_EVENT, Actions.write, deviceEventCreator.getScopeId())); return txManager.execute(tx -> { // Check that device exists final Device device = deviceRepository.findForUpdate(tx, deviceEventCreator.getScopeId(), deviceEventCreator.getDeviceId()) @@ -104,7 +101,7 @@ public DeviceEvent create(DeviceEventCreator deviceEventCreator) throws KapuaExc final DeviceEvent created = repository.create(tx, newEvent); device.setLastEventId(created.getId()); //Do not call update explicitly, the transaction ending will automatically update the entity -// deviceRepository.update(tx, device, device); + // deviceRepository.update(tx, device, device); return newEvent; }); @@ -117,7 +114,7 @@ public DeviceEvent find(KapuaId scopeId, KapuaId entityId) ArgumentValidator.notNull(scopeId, "scopeId"); ArgumentValidator.notNull(entityId, "entityId"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE_EVENT, Actions.read, scopeId)); + authorizationService.checkPermission(new Permission(Domains.DEVICE_EVENT, Actions.read, scopeId)); return txManager.execute(tx -> repository.find(tx, scopeId, entityId)) .orElse(null); @@ -129,7 +126,7 @@ public DeviceEventListResult query(KapuaQuery query) // Argument Validation ArgumentValidator.notNull(query, "query"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE_EVENT, Actions.read, query.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.DEVICE_EVENT, Actions.read, query.getScopeId())); return txManager.execute(tx -> repository.query(tx, query)); } @@ -140,7 +137,7 @@ public long count(KapuaQuery query) // Argument Validation ArgumentValidator.notNull(query, "query"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE_EVENT, Actions.read, query.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.DEVICE_EVENT, Actions.read, query.getScopeId())); return txManager.execute(tx -> repository.count(tx, query)); } @@ -152,7 +149,7 @@ public void delete(KapuaId scopeId, KapuaId deviceEventId) throws KapuaException ArgumentValidator.notNull(scopeId, "deviceEvent.scopeId"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DEVICE_EVENT, Actions.delete, scopeId)); + authorizationService.checkPermission(new Permission(Domains.DEVICE_EVENT, Actions.delete, scopeId)); txManager.execute(tx -> repository.delete(tx, scopeId, deviceEventId)); } diff --git a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/internal/DeviceCreatorImpl.java b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/internal/DeviceCreatorImpl.java deleted file mode 100644 index 746f7e2f0df..00000000000 --- a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/internal/DeviceCreatorImpl.java +++ /dev/null @@ -1,385 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.registry.internal; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import javax.validation.constraints.NotNull; - -import org.eclipse.kapua.commons.model.AbstractKapuaUpdatableEntityCreator; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.device.registry.Device; -import org.eclipse.kapua.service.device.registry.DeviceCreator; -import org.eclipse.kapua.service.device.registry.DeviceExtendedProperty; -import org.eclipse.kapua.service.device.registry.DeviceStatus; - -/** - * {@link DeviceCreator} implementation. - * - * @since 1.0.0 - */ -public class DeviceCreatorImpl extends AbstractKapuaUpdatableEntityCreator implements DeviceCreator { - - private static final long serialVersionUID = 8497299443773395462L; - private KapuaId groupId; - private String clientId; - private DeviceStatus status = DeviceStatus.ENABLED; - private KapuaId connectionId; - private KapuaId lastEventId; - private String displayName; - private String serialNumber; - private String modelId; - private String modelName; - private String imei; - private String imsi; - private String iccid; - private String biosVersion; - private String firmwareVersion; - private String osVersion; - private String jvmVersion; - private String osgiFrameworkVersion; - private String applicationFrameworkVersion; - private String connectionInterface; - private String connectionIp; - private String applicationIdentifiers; - private String acceptEncoding; - private String customAttribute1; - private String customAttribute2; - private String customAttribute3; - private String customAttribute4; - private String customAttribute5; - private List extendedProperties; - private String tamperStatus; - private Set tagIds; - - /** - * Constructor. - * - * @param scopeId The scope {@link KapuaId}. - * @since 1.0.0 - */ - protected DeviceCreatorImpl(KapuaId scopeId) { - super(scopeId); - } - - @Override - public KapuaId getGroupId() { - return groupId; - } - - @Override - public void setGroupId(KapuaId groupId) { - this.groupId = groupId; - } - - @Override - public String getClientId() { - return clientId; - } - - @Override - public void setClientId(String clientId) { - this.clientId = clientId; - } - - @Override - public DeviceStatus getStatus() { - return status; - } - - @Override - public void setStatus(DeviceStatus status) { - this.status = status; - } - - @Override - public KapuaId getConnectionId() { - return connectionId; - } - - @Override - public void setConnectionId(KapuaId connectionId) { - this.connectionId = connectionId; - } - - @Override - public KapuaId getLastEventId() { - return lastEventId; - } - - @Override - public void setLastEventId(KapuaId lastEventId) { - this.lastEventId = lastEventId; - } - - @Override - public String getDisplayName() { - return displayName; - } - - @Override - public void setDisplayName(String displayName) { - this.displayName = displayName; - } - - @Override - public String getSerialNumber() { - return serialNumber; - } - - @Override - public void setSerialNumber(String serialNumber) { - this.serialNumber = serialNumber; - } - - @Override - public String getModelId() { - return modelId; - } - - @Override - public void setModelId(String modelId) { - this.modelId = modelId; - } - - @Override - public String getModelName() { - return modelName; - } - - @Override - public void setModelName(String modelName) { - this.modelName = modelName; - } - - @Override - public String getImei() { - return imei; - } - - @Override - public void setImei(String imei) { - this.imei = imei; - } - - @Override - public String getImsi() { - return imsi; - } - - @Override - public void setImsi(String imsi) { - this.imsi = imsi; - } - - @Override - public String getIccid() { - return iccid; - } - - @Override - public void setIccid(String iccid) { - this.iccid = iccid; - } - - @Override - public String getBiosVersion() { - return biosVersion; - } - - @Override - public void setBiosVersion(String biosVersion) { - this.biosVersion = biosVersion; - } - - @Override - public String getFirmwareVersion() { - return firmwareVersion; - } - - @Override - public void setFirmwareVersion(String firmwareVersion) { - this.firmwareVersion = firmwareVersion; - } - - @Override - public String getOsVersion() { - return osVersion; - } - - @Override - public void setOsVersion(String osVersion) { - this.osVersion = osVersion; - } - - @Override - public String getJvmVersion() { - return jvmVersion; - } - - @Override - public void setJvmVersion(String jvmVersion) { - this.jvmVersion = jvmVersion; - } - - @Override - public String getOsgiFrameworkVersion() { - return osgiFrameworkVersion; - } - - @Override - public void setOsgiFrameworkVersion(String osgiFrameworkVersion) { - this.osgiFrameworkVersion = osgiFrameworkVersion; - } - - @Override - public String getApplicationFrameworkVersion() { - return applicationFrameworkVersion; - } - - @Override - public void setApplicationFrameworkVersion(String applicationFrameworkVersion) { - this.applicationFrameworkVersion = applicationFrameworkVersion; - } - - @Override - public String getConnectionInterface() { - return connectionInterface; - } - - @Override - public void setConnectionInterface(String connectionInterface) { - this.connectionInterface = connectionInterface; - } - - @Override - public String getConnectionIp() { - return connectionIp; - } - - @Override - public void setConnectionIp(String connectionIp) { - this.connectionIp = connectionIp; - } - - @Override - public String getApplicationIdentifiers() { - return applicationIdentifiers; - } - - @Override - public void setApplicationIdentifiers(String applicationIdentifiers) { - this.applicationIdentifiers = applicationIdentifiers; - } - - @Override - public String getAcceptEncoding() { - return acceptEncoding; - } - - @Override - public void setAcceptEncoding(String acceptEncoding) { - this.acceptEncoding = acceptEncoding; - } - - @Override - public String getCustomAttribute1() { - return customAttribute1; - } - - @Override - public void setCustomAttribute1(String customAttribute1) { - this.customAttribute1 = customAttribute1; - } - - @Override - public String getCustomAttribute2() { - return customAttribute2; - } - - @Override - public void setCustomAttribute2(String customAttribute2) { - this.customAttribute2 = customAttribute2; - } - - @Override - public String getCustomAttribute3() { - return customAttribute3; - } - - @Override - public void setCustomAttribute3(String customAttribute3) { - this.customAttribute3 = customAttribute3; - } - - @Override - public String getCustomAttribute4() { - return customAttribute4; - } - - @Override - public void setCustomAttribute4(String customAttribute4) { - this.customAttribute4 = customAttribute4; - } - - @Override - public String getCustomAttribute5() { - return customAttribute5; - } - - @Override - public void setCustomAttribute5(String customAttribute5) { - this.customAttribute5 = customAttribute5; - } - - @Override - public List getExtendedProperties() { - if (extendedProperties == null) { - extendedProperties = new ArrayList<>(); - } - - return extendedProperties; - } - - @Override - public void addExtendedProperty(@NotNull DeviceExtendedProperty extendedProperty) { - getExtendedProperties().add(extendedProperty); - } - - @Override - public void setExtendedProperties(List extendedProperties) { - this.extendedProperties = extendedProperties; - } - - @Override - public String getTamperStatus() { - return tamperStatus; - } - - @Override - public void setTamperStatus(String tamperStatus) { - this.tamperStatus = tamperStatus; - } - - @Override - public Set getTagIds() { - return tagIds == null ? new HashSet<>() : tagIds; - } - - @Override - public void setTagIds(Set tagIds) { - this.tagIds = tagIds; - } -} diff --git a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/internal/DeviceFactoryImpl.java b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/internal/DeviceFactoryImpl.java index 70524bf2ba0..a24127554c4 100644 --- a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/internal/DeviceFactoryImpl.java +++ b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/internal/DeviceFactoryImpl.java @@ -12,16 +12,13 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.registry.internal; +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaEntityCloneException; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.device.registry.Device; -import org.eclipse.kapua.service.device.registry.DeviceCreator; import org.eclipse.kapua.service.device.registry.DeviceExtendedProperty; import org.eclipse.kapua.service.device.registry.DeviceFactory; -import org.eclipse.kapua.service.device.registry.DeviceListResult; -import org.eclipse.kapua.service.device.registry.DeviceQuery; - -import javax.inject.Singleton; /** * {@link DeviceFactory} implementation. @@ -31,33 +28,11 @@ @Singleton public class DeviceFactoryImpl implements DeviceFactory { - @Override - public DeviceCreator newCreator(KapuaId scopeId, String clientId) { - DeviceCreator deviceCreator = newCreator(scopeId); - deviceCreator.setClientId(clientId); - return deviceCreator; - } - - @Override - public DeviceQuery newQuery(KapuaId scopeId) { - return new DeviceQueryImpl(scopeId); - } - - @Override - public DeviceListResult newListResult() { - return new DeviceListResultImpl(); - } - @Override public Device newEntity(KapuaId scopeId) { return new DeviceImpl(scopeId); } - @Override - public DeviceCreator newCreator(KapuaId scopeId) { - return new DeviceCreatorImpl(scopeId); - } - @Override public DeviceExtendedProperty newExtendedProperty(String groupName, String name, String value) { return new DeviceExtendedPropertyImpl(groupName, name, value); diff --git a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/internal/DeviceImplJpaRepository.java b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/internal/DeviceImplJpaRepository.java index 2be2228b60a..ef67ed8483b 100644 --- a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/internal/DeviceImplJpaRepository.java +++ b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/internal/DeviceImplJpaRepository.java @@ -12,7 +12,11 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.registry.internal; -import com.google.common.collect.Lists; +import java.util.Optional; + +import javax.persistence.EntityManager; +import javax.persistence.LockModeType; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.commons.jpa.JpaAwareTxContext; import org.eclipse.kapua.commons.jpa.KapuaJpaRepositoryConfiguration; @@ -21,23 +25,23 @@ import org.eclipse.kapua.service.device.registry.Device; import org.eclipse.kapua.service.device.registry.DeviceAttributes; import org.eclipse.kapua.service.device.registry.DeviceListResult; +import org.eclipse.kapua.service.device.registry.DeviceQuery; import org.eclipse.kapua.service.device.registry.DeviceRepository; import org.eclipse.kapua.storage.TxContext; -import javax.persistence.EntityManager; -import javax.persistence.LockModeType; -import java.util.Optional; +import com.google.common.collect.Lists; public class DeviceImplJpaRepository extends KapuaUpdatableEntityJpaRepository implements DeviceRepository { + public DeviceImplJpaRepository(KapuaJpaRepositoryConfiguration jpaRepoConfig) { - super(DeviceImpl.class, Device.TYPE, () -> new DeviceListResultImpl(), jpaRepoConfig); + super(DeviceImpl.class, Device.TYPE, () -> new DeviceListResult(), jpaRepoConfig); } @Override public Optional findByClientId(TxContext tx, KapuaId scopeId, String clientId) throws KapuaException { - DeviceQueryImpl query = new DeviceQueryImpl(scopeId); + DeviceQuery query = new DeviceQuery(scopeId); query.setPredicate(query.attributePredicate(DeviceAttributes.CLIENT_ID, clientId)); query.setFetchAttributes(Lists.newArrayList(DeviceAttributes.CONNECTION, DeviceAttributes.LAST_EVENT)); return Optional.ofNullable(this.query(tx, query).getFirstItem()); diff --git a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/internal/DeviceListResultImpl.java b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/internal/DeviceListResultImpl.java deleted file mode 100644 index 4f3543482cb..00000000000 --- a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/internal/DeviceListResultImpl.java +++ /dev/null @@ -1,27 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.registry.internal; - -import org.eclipse.kapua.commons.model.query.KapuaListResultImpl; -import org.eclipse.kapua.service.device.registry.Device; -import org.eclipse.kapua.service.device.registry.DeviceListResult; - -/** - * Device list result implementation. - * - * @since 1.0 - */ -public class DeviceListResultImpl extends KapuaListResultImpl implements DeviceListResult { - - private static final long serialVersionUID = -3870951363076544938L; -} diff --git a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/internal/DeviceMatchPredicateImpl.java b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/internal/DeviceMatchPredicateImpl.java deleted file mode 100644 index 6d3d69ee361..00000000000 --- a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/internal/DeviceMatchPredicateImpl.java +++ /dev/null @@ -1,48 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2020, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.registry.internal; - -import java.util.Arrays; - -import org.eclipse.kapua.commons.model.query.predicate.AbstractMatchPredicate; -import org.eclipse.kapua.service.device.registry.DeviceAttributes; -import org.eclipse.kapua.service.device.registry.DeviceMatchPredicate; - -public class DeviceMatchPredicateImpl extends AbstractMatchPredicate implements DeviceMatchPredicate { - - /** - * Constructor. - * - * @param matchTerm - * @since 1.3.0 - */ - public DeviceMatchPredicateImpl(T matchTerm) { - this.attributeNames = Arrays.asList( - DeviceAttributes.CLIENT_ID, - DeviceAttributes.DISPLAY_NAME, - DeviceAttributes.SERIAL_NUMBER, - DeviceAttributes.MODEL_ID, - DeviceAttributes.MODEL_NAME, - DeviceAttributes.BIOS_VERSION, - DeviceAttributes.FIRMWARE_VERSION, - DeviceAttributes.OS_VERSION, - DeviceAttributes.JVM_VERSION, - DeviceAttributes.OSGI_FRAMEWORK_VERSION, - DeviceAttributes.APPLICATION_FRAMEWORK_VERSION, - DeviceAttributes.CONNECTION_INTERFACE, - DeviceAttributes.CONNECTION_IP - ); - this.matchTerm = matchTerm; - } - -} diff --git a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/internal/DeviceQueryImpl.java b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/internal/DeviceQueryImpl.java deleted file mode 100644 index d1695ccb916..00000000000 --- a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/internal/DeviceQueryImpl.java +++ /dev/null @@ -1,59 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.device.registry.internal; - -import org.eclipse.kapua.commons.model.query.AbstractKapuaQuery; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.model.query.KapuaSortCriteria; -import org.eclipse.kapua.model.query.SortOrder; -import org.eclipse.kapua.service.device.registry.DeviceAttributes; -import org.eclipse.kapua.service.device.registry.DeviceQuery; - -/** - * {@link DeviceQuery} implementation. - * - * @since 1.0.0 - */ -public class DeviceQueryImpl extends AbstractKapuaQuery implements DeviceQuery { - - /** - * Constructor. - * - * @since 1.0.0 - */ - private DeviceQueryImpl() { - super(); - } - - /** - * Constructor. - * - * @param scopeId The {@link #getScopeId()}. - * @since 1.0.0 - */ - public DeviceQueryImpl(KapuaId scopeId) { - this(); - setScopeId(scopeId); - } - - @Override - public KapuaSortCriteria getDefaultSortCriteria() { - return fieldSortCriteria(DeviceAttributes.CLIENT_ID, SortOrder.ASCENDING); - } - - @Override - public DeviceMatchPredicateImpl matchPredicate(T matchTerm) { - return new DeviceMatchPredicateImpl<>(matchTerm); - } - -} diff --git a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/internal/DeviceRegistryServiceImpl.java b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/internal/DeviceRegistryServiceImpl.java index 2bd64f03026..a91ccab2678 100644 --- a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/internal/DeviceRegistryServiceImpl.java +++ b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/internal/DeviceRegistryServiceImpl.java @@ -23,7 +23,6 @@ import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.service.authorization.AuthorizationService; import org.eclipse.kapua.service.authorization.access.GroupQueryHelper; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; import org.eclipse.kapua.service.device.registry.Device; import org.eclipse.kapua.service.device.registry.DeviceAttributes; import org.eclipse.kapua.service.device.registry.DeviceCreator; @@ -56,13 +55,12 @@ public class DeviceRegistryServiceImpl public DeviceRegistryServiceImpl( ServiceConfigurationManager serviceConfigurationManager, AuthorizationService authorizationService, - PermissionFactory permissionFactory, TxManager txManager, DeviceRepository deviceRepository, DeviceFactory entityFactory, GroupQueryHelper groupQueryHelper, EventStorer eventStorer, DeviceValidation deviceValidation) { - super(txManager, serviceConfigurationManager, Domains.DEVICE, authorizationService, permissionFactory); + super(txManager, serviceConfigurationManager, Domains.DEVICE, authorizationService); this.deviceRepository = deviceRepository; this.entityFactory = entityFactory; this.groupQueryHelper = groupQueryHelper; @@ -79,7 +77,7 @@ public Device create(DeviceCreator deviceCreator) // Check entity limit serviceConfigurationManager.checkAllowedEntities(tx, deviceCreator.getScopeId(), "Devices"); // Check duplicate clientId - DeviceQuery query = entityFactory.newQuery(deviceCreator.getScopeId()); + DeviceQuery query = new DeviceQuery(deviceCreator.getScopeId()); query.setPredicate(query.attributePredicate(DeviceAttributes.CLIENT_ID, deviceCreator.getClientId())); //TODO: check whether this is anywhere efficient if (deviceRepository.count(tx, query) > 0) { @@ -204,7 +202,7 @@ public void onKapuaEvent(ServiceEvent kapuaEvent) throws KapuaException { // Private methods private void deleteDeviceByGroupId(KapuaId scopeId, KapuaId groupId) throws KapuaException { - DeviceQuery query = entityFactory.newQuery(scopeId); + DeviceQuery query = new DeviceQuery(scopeId); query.setPredicate(query.attributePredicate(DeviceAttributes.GROUP_ID, groupId)); txManager.execute(tx -> { @@ -219,7 +217,7 @@ private void deleteDeviceByGroupId(KapuaId scopeId, KapuaId groupId) throws Kapu } private void deleteDeviceByAccountId(KapuaId scopeId, KapuaId accountId) throws KapuaException { - DeviceQuery query = entityFactory.newQuery(accountId); + DeviceQuery query = new DeviceQuery(accountId); txManager.execute(tx -> { DeviceListResult devicesToDelete = deviceRepository.query(tx, query); diff --git a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/lifecycle/internal/DeviceLifeCycleServiceImpl.java b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/lifecycle/internal/DeviceLifeCycleServiceImpl.java index f9ce2fdc30e..9cac8c21cf5 100644 --- a/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/lifecycle/internal/DeviceLifeCycleServiceImpl.java +++ b/service/device/registry/internal/src/main/java/org/eclipse/kapua/service/device/registry/lifecycle/internal/DeviceLifeCycleServiceImpl.java @@ -17,13 +17,11 @@ import java.util.Date; import java.util.List; import java.util.Map; + import javax.inject.Inject; import javax.inject.Singleton; import javax.validation.constraints.NotNull; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.common.base.Strings; import org.checkerframework.checker.nullness.qual.Nullable; import org.eclipse.kapua.KapuaEntityNotFoundException; import org.eclipse.kapua.KapuaException; @@ -58,6 +56,10 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.base.Strings; + /** * {@link DeviceLifeCycleService} implementation. * @@ -103,7 +105,7 @@ public void birth(KapuaId connectionId, KapuaBirthMessage birthMessage) throws K // Device update Device device; if (deviceId == null) { - DeviceCreator deviceCreator = deviceFactory.newCreator(scopeId); + DeviceCreator deviceCreator = new DeviceCreator(scopeId); deviceCreator.setClientId(birthChannel.getClientId()); deviceCreator.setDisplayName(birthPayload.getDisplayName()); @@ -168,12 +170,17 @@ public void death(KapuaId connectionId, KapuaDisconnectMessage message) throws K *

        * Tries to update the {@link Device} a number of times to allow close device updates to be stored properly. * - * @param scopeId The {@link Device#getScopeId()} to update. - * @param deviceId The {@link Device#getId()} to update. - * @param birthPayload The {@link KapuaBirthPayload} from which extract data. - * @param connectionId The {@link DeviceConnection#getId()} + * @param scopeId + * The {@link Device#getScopeId()} to update. + * @param deviceId + * The {@link Device#getId()} to update. + * @param birthPayload + * The {@link KapuaBirthPayload} from which extract data. + * @param connectionId + * The {@link DeviceConnection#getId()} * @return The updated {@link Device}. - * @throws KapuaException If {@link Device} does not exists or {@link DeviceRegistryService#update(KapuaUpdatableEntity)} causes an error. + * @throws KapuaException + * If {@link Device} does not exists or {@link DeviceRegistryService#update(KapuaUpdatableEntity)} causes an error. * @since 1.2.0 */ private Device updateDeviceInfoFromMessage(KapuaId scopeId, KapuaId deviceId, KapuaBirthPayload birthPayload, KapuaId connectionId) throws KapuaException { @@ -241,18 +248,21 @@ private Device updateDeviceInfoFromMessage(KapuaId scopeId, KapuaId deviceId, Ka return device; } - /** * Creates a {@link DeviceEvent} from the {@link KapuaLifecycleMessage}. *

        - * Internally invokes {@link DeviceRegistryService#find(KapuaId, KapuaId)} with the given parameters and - * then uses {@link #createLifecycleEvent(Device, String, KapuaLifecycleMessage)} + * Internally invokes {@link DeviceRegistryService#find(KapuaId, KapuaId)} with the given parameters and then uses {@link #createLifecycleEvent(Device, String, KapuaLifecycleMessage)} * - * @param scopeId The {@link Device#getScopeId()} of the {@link Device} that generated the {@link KapuaLifecycleMessage}. - * @param deviceId The {@link Device#getId()} of the {@link Device} that generated the {@link KapuaLifecycleMessage}. - * @param resource The resource used to publish the {@link KapuaLifecycleMessage} - * @param message The {@link KapuaLifecycleMessage} from which to extract data. - * @throws KapuaException if storing the {@link DeviceEvent} throws a {@link KapuaException} + * @param scopeId + * The {@link Device#getScopeId()} of the {@link Device} that generated the {@link KapuaLifecycleMessage}. + * @param deviceId + * The {@link Device#getId()} of the {@link Device} that generated the {@link KapuaLifecycleMessage}. + * @param resource + * The resource used to publish the {@link KapuaLifecycleMessage} + * @param message + * The {@link KapuaLifecycleMessage} from which to extract data. + * @throws KapuaException + * if storing the {@link DeviceEvent} throws a {@link KapuaException} * @since 1.2.0 */ private DeviceEvent createLifecycleEvent(@NotNull KapuaId scopeId, KapuaId deviceId, @NotNull String resource, @NotNull KapuaLifecycleMessage message) throws KapuaException { @@ -265,15 +275,19 @@ private DeviceEvent createLifecycleEvent(@NotNull KapuaId scopeId, KapuaId devic /** * Creates a {@link DeviceEvent} from the {@link KapuaLifecycleMessage}. * - * @param device The {@link Device} that generated the {@link KapuaLifecycleMessage}. - * @param resource The resource used to publish the {@link KapuaLifecycleMessage} - * @param message The {@link KapuaLifecycleMessage} from which to extract data. - * @throws KapuaException if storing the {@link DeviceEvent} throws a {@link KapuaException} + * @param device + * The {@link Device} that generated the {@link KapuaLifecycleMessage}. + * @param resource + * The resource used to publish the {@link KapuaLifecycleMessage} + * @param message + * The {@link KapuaLifecycleMessage} from which to extract data. + * @throws KapuaException + * if storing the {@link DeviceEvent} throws a {@link KapuaException} * @since 1.2.0 */ private DeviceEvent createLifecycleEvent(@NotNull Device device, @NotNull String resource, @NotNull KapuaLifecycleMessage message) throws KapuaException { - DeviceEventCreator deviceEventCreator = deviceEventFactory.newCreator(device.getScopeId(), device.getId(), message.getReceivedOn(), resource); + DeviceEventCreator deviceEventCreator = new DeviceEventCreator(device.getScopeId(), device.getId(), message.getReceivedOn(), resource); deviceEventCreator.setResponseCode(KapuaResponseCode.ACCEPTED); deviceEventCreator.setSentOn(message.getSentOn()); deviceEventCreator.setReceivedOn(Date.from(KapuaDateUtils.getKapuaSysDate())); @@ -293,9 +307,11 @@ private DeviceEvent createLifecycleEvent(@NotNull Device device, @NotNull String /** * Builds the {@link List} of {@link DeviceExtendedProperty}es from the {@link KapuaBirthPayload#getExtendedProperties()} property. * - * @param extendedPropertiesString The {@link KapuaBirthPayload#getExtendedProperties()} to parse. + * @param extendedPropertiesString + * The {@link KapuaBirthPayload#getExtendedProperties()} to parse. * @return The {@link List} of {@link DeviceExtendedProperty}es parsed. - * @throws KapuaException If there are exception while parsing the JSON-formatted metric. + * @throws KapuaException + * If there are exception while parsing the JSON-formatted metric. * @since 1.5.0 */ private List buildDeviceExtendedPropertyFromBirth(@Nullable String extendedPropertiesString) throws KapuaException { diff --git a/service/device/registry/pom.xml b/service/device/registry/pom.xml index 1bef64494e8..bbcd92acd0a 100644 --- a/service/device/registry/pom.xml +++ b/service/device/registry/pom.xml @@ -19,7 +19,7 @@ org.eclipse.kapua kapua-device - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT pom diff --git a/service/device/registry/test-steps/pom.xml b/service/device/registry/test-steps/pom.xml index 5a03ada40b2..30c53824df9 100644 --- a/service/device/registry/test-steps/pom.xml +++ b/service/device/registry/test-steps/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-device-registry - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-device-registry-test-steps diff --git a/service/device/registry/test-steps/src/main/java/org/eclipse/kapua/service/device/registry/steps/AclCreator.java b/service/device/registry/test-steps/src/main/java/org/eclipse/kapua/service/device/registry/steps/AclCreator.java index 8eb6e5313ce..c1263ca1ef0 100644 --- a/service/device/registry/test-steps/src/main/java/org/eclipse/kapua/service/device/registry/steps/AclCreator.java +++ b/service/device/registry/test-steps/src/main/java/org/eclipse/kapua/service/device/registry/steps/AclCreator.java @@ -13,6 +13,14 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.registry.steps; +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.commons.model.domains.Domains; import org.eclipse.kapua.commons.model.id.KapuaEid; @@ -22,32 +30,19 @@ import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.account.Account; import org.eclipse.kapua.service.account.AccountCreator; -import org.eclipse.kapua.service.account.AccountFactory; import org.eclipse.kapua.service.account.AccountService; import org.eclipse.kapua.service.authentication.credential.CredentialCreator; -import org.eclipse.kapua.service.authentication.credential.CredentialFactory; import org.eclipse.kapua.service.authentication.credential.CredentialService; import org.eclipse.kapua.service.authentication.credential.CredentialStatus; import org.eclipse.kapua.service.authorization.access.AccessInfoCreator; -import org.eclipse.kapua.service.authorization.access.AccessInfoFactory; import org.eclipse.kapua.service.authorization.access.AccessInfoService; import org.eclipse.kapua.service.authorization.permission.Permission; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; import org.eclipse.kapua.service.user.User; import org.eclipse.kapua.service.user.UserCreator; -import org.eclipse.kapua.service.user.UserFactory; import org.eclipse.kapua.service.user.UserService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - /** * Creator of Accounts, Users, Permissions that are used in ACL tests */ @@ -63,32 +58,22 @@ public class AclCreator { * Credential service. */ private CredentialService credentialService; - private CredentialFactory credentialFactory; - private PermissionFactory permissionFactory; /** * User service. */ private UserService userService; - private UserFactory userFactory; /** * Accessinfo service. */ private AccessInfoService accessInfoService; - private AccessInfoFactory accessInfoFactory; /** * Account service. */ private AccountService accountService; - /** - * Account factory. - */ - private AccountFactory accountFactory; - - /** * Constructor with all support services. */ @@ -96,24 +81,21 @@ public AclCreator() { KapuaLocator locator = KapuaLocator.getInstance(); accountService = locator.getService(AccountService.class); - accountFactory = locator.getFactory(AccountFactory.class); userService = locator.getService(UserService.class); - userFactory = locator.getFactory(UserFactory.class); accessInfoService = locator.getService(AccessInfoService.class); - accessInfoFactory = locator.getFactory(AccessInfoFactory.class); credentialService = locator.getService(CredentialService.class); - credentialFactory = locator.getFactory(CredentialFactory.class); - permissionFactory = locator.getFactory(PermissionFactory.class); } /** * Configure user service with reasonable default values. * - * @param accId account id - * @param scopeId scope id + * @param accId + * account id + * @param scopeId + * scope id */ private void configureUserService(KapuaId accId, KapuaId scopeId) { @@ -135,8 +117,10 @@ private void configureUserService(KapuaId accId, KapuaId scopeId) { /** * Configure account service with reasonable default values. * - * @param accId account id - * @param scopeId scope id + * @param accId + * account id + * @param scopeId + * scope id */ private void configureAccountService(KapuaId accId, KapuaId scopeId) { @@ -154,10 +138,12 @@ private void configureAccountService(KapuaId accId, KapuaId scopeId) { /** * Creates permissions for user with specified account. Permissions are created in privileged mode. * - * @param permissionList list of permissions for user, if targetScopeId is not set user scope that is - * specified as account - * @param user user for whom permissions are set - * @param account account in which user is defined + * @param permissionList + * list of permissions for user, if targetScopeId is not set user scope that is specified as account + * @param user + * user for whom permissions are set + * @param account + * account in which user is defined * @throws Exception */ private void createPermissions(List permissionList, User user, Account account) @@ -175,18 +161,20 @@ private void createPermissions(List permissionList, User user, Ac } /** - * Create accessInfoCreator instance with data about user permissions. - * If target scope is not defined in permission list use account scope. + * Create accessInfoCreator instance with data about user permissions. If target scope is not defined in permission list use account scope. * - * @param permissionList list of all permissions - * @param user user for which permissions are set - * @param account that user belongs to + * @param permissionList + * list of all permissions + * @param user + * user for which permissions are set + * @param account + * that user belongs to * @return AccessInfoCreator instance for creating user permissions */ private AccessInfoCreator accessInfoCreatorCreator(List permissionList, - User user, Account account) { + User user, Account account) { - AccessInfoCreator accessInfoCreator = accessInfoFactory.newCreator(account.getId()); + AccessInfoCreator accessInfoCreator = new AccessInfoCreator(account.getId()); accessInfoCreator.setUserId(user.getId()); accessInfoCreator.setScopeId(user.getScopeId()); Set permissions = new HashSet<>(); @@ -197,7 +185,7 @@ private AccessInfoCreator accessInfoCreatorCreator(List permissio targetScopeId = (KapuaEid) account.getId(); } String domain = permissionData.getDomain(); - Permission permission = permissionFactory.newPermission(domain, action, targetScopeId); + Permission permission = new Permission(domain, action, targetScopeId); permissions.add(permission); } accessInfoCreator.setPermissions(permissions); @@ -208,7 +196,7 @@ private AccessInfoCreator accessInfoCreatorCreator(List permissio public void attachUserCredentials(Account account, User user) throws KapuaException { KapuaSecurityUtils.doPrivileged(() -> { CredentialCreator credentialCreator; - credentialCreator = credentialFactory.newCreator(account.getId(), user.getId(), "PASSWORD", "KeepCalm123.", CredentialStatus.ENABLED, null); + credentialCreator = new CredentialCreator(account.getId(), user.getId(), "PASSWORD", "KeepCalm123.", CredentialStatus.ENABLED, null); try { credentialService.create(credentialCreator); } catch (KapuaException ke) { @@ -222,7 +210,7 @@ public void attachUserCredentials(Account account, User user) throws KapuaExcept public void attachUserCredentials(Account account, User user, String password) throws KapuaException { KapuaSecurityUtils.doPrivileged(() -> { CredentialCreator credentialCreator; - credentialCreator = credentialFactory.newCreator(account.getId(), user.getId(), "PASSWORD", password, CredentialStatus.ENABLED, null); + credentialCreator = new CredentialCreator(account.getId(), user.getId(), "PASSWORD", password, CredentialStatus.ENABLED, null); try { credentialService.create(credentialCreator); } catch (KapuaException ke) { @@ -235,14 +223,14 @@ public void attachUserCredentials(Account account, User user, String password) t public User createUser(Account account, String name) throws KapuaException { configureUserService(account.getId(), SYS_ID); - UserCreator userCreator = userFactory.newCreator(account.getId(), name); + UserCreator userCreator = new UserCreator(account.getId(), name); return userService.create(userCreator); } Account createAccount(String name, String orgName, String orgEmail) throws KapuaException { configureAccountService(ROOT_SCOPE_ID, SYS_ID); - AccountCreator accountCreator = accountFactory.newCreator(ROOT_SCOPE_ID); + AccountCreator accountCreator = new AccountCreator(ROOT_SCOPE_ID); accountCreator.setName(name); accountCreator.setOrganizationName(orgName); accountCreator.setOrganizationEmail(orgEmail); diff --git a/service/device/registry/test-steps/src/main/java/org/eclipse/kapua/service/device/registry/steps/AclSteps.java b/service/device/registry/test-steps/src/main/java/org/eclipse/kapua/service/device/registry/steps/AclSteps.java index bbd2237eebb..0d90a4245ea 100644 --- a/service/device/registry/test-steps/src/main/java/org/eclipse/kapua/service/device/registry/steps/AclSteps.java +++ b/service/device/registry/test-steps/src/main/java/org/eclipse/kapua/service/device/registry/steps/AclSteps.java @@ -13,14 +13,21 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.registry.steps; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.inject.Inject; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.locator.KapuaLocator; -import org.eclipse.kapua.qa.common.TestBase; import org.eclipse.kapua.qa.common.StepData; +import org.eclipse.kapua.qa.common.TestBase; import org.eclipse.kapua.service.account.Account; import org.eclipse.kapua.service.authentication.AuthenticationService; -import org.eclipse.kapua.service.authentication.CredentialsFactory; import org.eclipse.kapua.service.authentication.LoginCredentials; +import org.eclipse.kapua.service.authentication.UsernamePasswordCredentials; import org.eclipse.kapua.service.user.User; import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken; import org.eclipse.paho.client.mqttv3.MqttCallback; @@ -43,13 +50,6 @@ import io.cucumber.java.en.Then; import io.cucumber.java.en.When; -import javax.inject.Inject; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - /** * Steps for testing Access Control List functionality on Broker service. */ @@ -87,7 +87,6 @@ public class AclSteps extends TestBase { private static Map listenerMqttMessage; private static AuthenticationService authenticationService; - private static CredentialsFactory credentialsFactory; /** * Helper for creating Accoutn, User and other artifacts needed in tests. */ @@ -98,11 +97,10 @@ public AclSteps(StepData stepData) { super(stepData); } - @After(value="@setup") + @After(value = "@setup") public void setServices() { locator = KapuaLocator.getInstance(); authenticationService = locator.getService(AuthenticationService.class); - credentialsFactory = locator.getFactory(CredentialsFactory.class); mqttDevice = new MqttDevice(); clientMqttMessage = new HashMap<>(); @@ -111,7 +109,7 @@ public void setServices() { aclCreator = new AclCreator(); } - @Before(value="@env_docker or @env_docker_base or @env_none", order=10) + @Before(value = "@env_docker or @env_docker_base or @env_none", order = 10) public void beforeScenarioNone(Scenario scenario) { updateScenario(scenario); } @@ -128,7 +126,7 @@ public void startMqttDevice() throws KapuaException { waitInMillis(BROKER_START_WAIT_MILLIS); // Login with system user String passwd = SYS_PASSWORD; - LoginCredentials credentials = credentialsFactory.newUsernamePasswordCredentials(SYS_USERNAME, passwd); + LoginCredentials credentials = new UsernamePasswordCredentials(SYS_USERNAME, passwd); authenticationService.login(credentials); } @@ -173,8 +171,8 @@ public void connectionLost(Throwable cause) { logger.info("Connection lost!", cause); } }); - List mqttClientList = (List)stepData.get("Paho_" + deviceGroup); - if (mqttClientList==null) { + List mqttClientList = (List) stepData.get("Paho_" + deviceGroup); + if (mqttClientList == null) { mqttClientList = new ArrayList<>(); stepData.put("Paho_" + deviceGroup, mqttClientList); } @@ -184,8 +182,8 @@ public void connectionLost(Throwable cause) { @Then("Clients from group {string} are connected") public void checkClientConnected(String deviceGroup) throws Exception { - List mqttDeviceList = (List)stepData.get("Paho_" + deviceGroup); - if (mqttDeviceList!=null) { + List mqttDeviceList = (List) stepData.get("Paho_" + deviceGroup); + if (mqttDeviceList != null) { mqttDeviceList.forEach(mqttDevice -> Assert.assertTrue("Client " + mqttDevice.getClientId() + " should be connected!", mqttDevice.isConnected())); } } @@ -213,8 +211,7 @@ private boolean brokerReceivesStringOnTopicInternal(String payload, String topic String message = listenerMqttMessage.get(topic); if (timeout) { Assert.assertEquals(payload, message); - } - else { + } else { result = payload.equals(message); } } else { @@ -252,8 +249,7 @@ private boolean iReceiveStringOnTopicInternal(String clientId, String payload, S String message = messages.get(topic); if (timeout) { Assert.assertEquals(payload, message); - } - else { + } else { result = payload.equals(message); } } else { @@ -313,7 +309,7 @@ public void createDataManageAccountAndUser() throws Exception { @And("other broker account and user are created") public void createOtherBrokerAccountAndUser() throws Exception { - Account account = aclCreator.createAccount("domino","Domino Corp.", "lisa@domino.org"); + Account account = aclCreator.createAccount("domino", "Domino Corp.", "lisa@domino.org"); User user = aclCreator.createUser(account, "domina"); aclCreator.attachUserCredentials(account, user); aclCreator.attachBrokerPermissions(account, user); @@ -334,7 +330,8 @@ public void exceptionIsNotThrown() { /** * Simple wait implementation. * - * @param millis milli seconds + * @param millis + * milli seconds */ private void waitInMillis(long millis) { try { diff --git a/service/device/registry/test-steps/src/main/java/org/eclipse/kapua/service/device/registry/steps/BrokerSteps.java b/service/device/registry/test-steps/src/main/java/org/eclipse/kapua/service/device/registry/steps/BrokerSteps.java index c0e71b9b03b..dddfc566a6f 100644 --- a/service/device/registry/test-steps/src/main/java/org/eclipse/kapua/service/device/registry/steps/BrokerSteps.java +++ b/service/device/registry/test-steps/src/main/java/org/eclipse/kapua/service/device/registry/steps/BrokerSteps.java @@ -32,11 +32,9 @@ import org.eclipse.kapua.service.device.management.asset.DeviceAssetChannel; import org.eclipse.kapua.service.device.management.asset.DeviceAssetManagementService; import org.eclipse.kapua.service.device.management.asset.DeviceAssets; -import org.eclipse.kapua.service.device.management.asset.internal.DeviceAssetsImpl; import org.eclipse.kapua.service.device.management.bundle.DeviceBundle; import org.eclipse.kapua.service.device.management.bundle.DeviceBundleManagementService; import org.eclipse.kapua.service.device.management.bundle.DeviceBundles; -import org.eclipse.kapua.service.device.management.command.DeviceCommandFactory; import org.eclipse.kapua.service.device.management.command.DeviceCommandInput; import org.eclipse.kapua.service.device.management.command.DeviceCommandManagementService; import org.eclipse.kapua.service.device.management.command.DeviceCommandOutput; @@ -72,9 +70,7 @@ import io.cucumber.java.en.When; /** - * Steps used in integration scenarios with running MQTT broker and process of - * registering mocked Kura device registering with Kapua and issuing basic administrative - * commands on Mocked Kura. + * Steps used in integration scenarios with running MQTT broker and process of registering mocked Kura device registering with Kapua and issuing basic administrative commands on Mocked Kura. */ @Singleton public class BrokerSteps extends TestBase { @@ -135,11 +131,6 @@ public class BrokerSteps extends TestBase { */ private DeviceCommandManagementService deviceCommandManagementService; - /** - * Factory for creating commands sent to Kura. - */ - private DeviceCommandFactory deviceCommandFactory; - /** * Service for connecting devices. */ @@ -165,7 +156,6 @@ public void setServices() throws Exception { deviceConfiguratiomManagementService = locator.getService(DeviceConfigurationManagementService.class); deviceBundleManagementService = locator.getService(DeviceBundleManagementService.class); deviceCommandManagementService = locator.getService(DeviceCommandManagementService.class); - deviceCommandFactory = locator.getFactory(DeviceCommandFactory.class); deviceConnectionService = locator.getService(DeviceConnectionService.class); deviceAssetManagementService = locator.getService(DeviceAssetManagementService.class); } @@ -252,8 +242,10 @@ public void deviceBirthMessage() throws Exception { /** * Checks that the {@link Device} with the given {@link Device#getClientId()} has {@link DeviceConnection#getStatus()} {@link DeviceConnectionStatus#CONNECTED} within the given time. * - * @param clientId The {@link Device#getClientId()} to check - * @param waitSeconds The max time of wait in seconds + * @param clientId + * The {@link Device#getClientId()} to check + * @param waitSeconds + * The max time of wait in seconds * @throws Exception * @since 1.2.0 */ @@ -261,7 +253,7 @@ public void deviceBirthMessage() throws Exception { public void deviceConnected(String clientId, int waitSeconds) throws Exception { long now = System.currentTimeMillis(); - while ((System.currentTimeMillis() - now) < (waitSeconds * 1000L)){ + while ((System.currentTimeMillis() - now) < (waitSeconds * 1000L)) { Device kuraDevice = deviceRegistryService.findByClientId(getCurrentScopeId(), clientId); if (kuraDevice != null && @@ -461,7 +453,7 @@ public void configurationReceived() { public void executeCommand(String command) throws Exception { for (KuraDevice kuraDevice : kuraDevices) { Device device = deviceRegistryService.findByClientId(SYS_SCOPE_ID, kuraDevice.getClientId()); - DeviceCommandInput commandInput = deviceCommandFactory.newCommandInput(); + DeviceCommandInput commandInput = new DeviceCommandInput(); commandInput.setCommand(command); commandInput.setRunAsynch(false); commandInput.setTimeout(0); @@ -493,7 +485,6 @@ public void deviceWithServerIp(String serverIp) { Assert.assertEquals(serverIp, deviceConn.getServerIp()); } - @When("Client with name {string} with client id {string} user {string} password {string} is connected") public void clientConnect(String clientName, String clientId, String user, String password) throws Exception { MqttClient mqttClient = null; @@ -570,7 +561,7 @@ public void disconnectConnectionWithClientId(String clientId) throws Exception { @Then("Device(s) status is {string} within {int} second(s) for client id {string}") public void deviceStatusIs(String expectedStatus, int timeout, String clientId) throws Exception { String currentStatus = null; - while(!expectedStatus.equals(currentStatus) && timeout-->0) { + while (!expectedStatus.equals(currentStatus) && timeout-- > 0) { Thread.sleep(1000); logger.info("Device(s) status countdown check: {}", timeout); @@ -619,7 +610,7 @@ public void iAddDeviceToKuraMock(int numberOfDevices) { @And("Device assets are requested") public void deviceAssetsAreRequested() throws Exception { - DeviceAssets deviceAssets = new DeviceAssetsImpl(); + DeviceAssets deviceAssets = new DeviceAssets(); for (KuraDevice kuraDevice : kuraDevices) { Device device = deviceRegistryService.findByClientId(SYS_SCOPE_ID, kuraDevice.getClientId()); Assert.assertNotNull(device); diff --git a/service/device/registry/test-steps/src/main/java/org/eclipse/kapua/service/device/registry/steps/DeviceManagementKeystoreSteps.java b/service/device/registry/test-steps/src/main/java/org/eclipse/kapua/service/device/registry/steps/DeviceManagementKeystoreSteps.java index 10991d200ce..26e4ddbc313 100644 --- a/service/device/registry/test-steps/src/main/java/org/eclipse/kapua/service/device/registry/steps/DeviceManagementKeystoreSteps.java +++ b/service/device/registry/test-steps/src/main/java/org/eclipse/kapua/service/device/registry/steps/DeviceManagementKeystoreSteps.java @@ -12,17 +12,14 @@ *******************************************************************************/ package org.eclipse.kapua.service.device.registry.steps; -import com.google.inject.Singleton; -import io.cucumber.java.After; -import io.cucumber.java.Before; -import io.cucumber.java.Scenario; -import io.cucumber.java.en.Then; -import io.cucumber.java.en.When; +import java.util.List; + +import javax.inject.Inject; + import org.eclipse.kapua.broker.artemis.plugin.security.setting.BrokerSetting; import org.eclipse.kapua.locator.KapuaLocator; import org.eclipse.kapua.qa.common.StepData; import org.eclipse.kapua.qa.common.TestBase; -import org.eclipse.kapua.service.device.management.keystore.DeviceKeystoreManagementFactory; import org.eclipse.kapua.service.device.management.keystore.DeviceKeystoreManagementService; import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystore; import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystoreCSR; @@ -37,8 +34,13 @@ import org.eclipse.kapua.service.device.registry.DeviceRegistryService; import org.junit.Assert; -import javax.inject.Inject; -import java.util.List; +import com.google.inject.Singleton; + +import io.cucumber.java.After; +import io.cucumber.java.Before; +import io.cucumber.java.Scenario; +import io.cucumber.java.en.Then; +import io.cucumber.java.en.When; @Singleton public class DeviceManagementKeystoreSteps extends TestBase { @@ -52,7 +54,6 @@ public class DeviceManagementKeystoreSteps extends TestBase { private DeviceRegistryService deviceRegistryService; private DeviceKeystoreManagementService deviceKeystoreManagementService; - private DeviceKeystoreManagementFactory deviceKeystoreManagementFactory; private BrokerSetting brokerSettings = KapuaLocator.getInstance().getComponent(BrokerSetting.class); /** @@ -75,7 +76,6 @@ public void setServices() { KapuaLocator locator = KapuaLocator.getInstance(); deviceRegistryService = locator.getService(DeviceRegistryService.class); deviceKeystoreManagementService = locator.getService(DeviceKeystoreManagementService.class); - deviceKeystoreManagementFactory = locator.getFactory(DeviceKeystoreManagementFactory.class); } @When("Keystores are requested") @@ -145,7 +145,7 @@ public void requestKeystoreItemsByAlias(String alias) throws Exception { for (KuraDevice kuraDevice : kuraDevices) { Device device = deviceRegistryService.findByClientId(SYS_SCOPE_ID, kuraDevice.getClientId()); if (device != null) { - DeviceKeystoreItemQuery query = deviceKeystoreManagementFactory.newDeviceKeystoreItemQuery(); + DeviceKeystoreItemQuery query = new DeviceKeystoreItemQuery(); query.setAlias(alias); DeviceKeystoreItems keystoreItems = deviceKeystoreManagementService.getKeystoreItems(device.getScopeId(), device.getId(), query, null); List keystoreItemList = keystoreItems.getKeystoreItems(); @@ -160,7 +160,7 @@ public void requestKeystoreItemsByKeystoreId(String keystoreId) throws Exception for (KuraDevice kuraDevice : kuraDevices) { Device device = deviceRegistryService.findByClientId(SYS_SCOPE_ID, kuraDevice.getClientId()); if (device != null) { - DeviceKeystoreItemQuery query = deviceKeystoreManagementFactory.newDeviceKeystoreItemQuery(); + DeviceKeystoreItemQuery query = new DeviceKeystoreItemQuery(); query.setKeystoreId(keystoreId); DeviceKeystoreItems keystoreItems = deviceKeystoreManagementService.getKeystoreItems(device.getScopeId(), device.getId(), query, null); List keystoreItemList = keystoreItems.getKeystoreItems(); @@ -238,7 +238,7 @@ public void installKeystoreCertificateWithAlias(String alias) throws Exception { for (KuraDevice kuraDevice : kuraDevices) { Device device = deviceRegistryService.findByClientId(SYS_SCOPE_ID, kuraDevice.getClientId()); if (device != null) { - DeviceKeystoreCertificate deviceKeystoreCertificate = deviceKeystoreManagementFactory.newDeviceKeystoreCertificate(); + DeviceKeystoreCertificate deviceKeystoreCertificate = new DeviceKeystoreCertificate(); deviceKeystoreCertificate.setAlias(alias); deviceKeystoreCertificate.setKeystoreId("SSLKeystore"); deviceKeystoreCertificate.setCertificate("-----BEGIN CERTIFICATE-----\n" + @@ -282,7 +282,7 @@ public void installKeystoreKeypairWithAlias(String alias) throws Exception { for (KuraDevice kuraDevice : (List) stepData.get(KURA_DEVICES)) { Device device = deviceRegistryService.findByClientId(SYS_SCOPE_ID, kuraDevice.getClientId()); if (device != null) { - DeviceKeystoreKeypair deviceKeystoreKeypair = deviceKeystoreManagementFactory.newDeviceKeystoreKeypair(); + DeviceKeystoreKeypair deviceKeystoreKeypair = new DeviceKeystoreKeypair(); deviceKeystoreKeypair.setAlias(alias); deviceKeystoreKeypair.setKeystoreId("SSLKeystore"); deviceKeystoreKeypair.setAlgorithm("RSA"); @@ -343,7 +343,7 @@ public void sendCertificateSigningRequestFor(String keystoreId, String alias) th for (KuraDevice kuraDevice : kuraDevices) { Device device = deviceRegistryService.findByClientId(SYS_SCOPE_ID, kuraDevice.getClientId()); if (device != null) { - DeviceKeystoreCSRInfo deviceKeystoreCSRInfo = deviceKeystoreManagementFactory.newDeviceKeystoreCSRInfo(); + DeviceKeystoreCSRInfo deviceKeystoreCSRInfo = new DeviceKeystoreCSRInfo(); deviceKeystoreCSRInfo.setKeystoreId(keystoreId); deviceKeystoreCSRInfo.setAlias(alias); deviceKeystoreCSRInfo.setSignatureAlgorithm("SHA256withRSA"); diff --git a/service/device/registry/test-steps/src/main/java/org/eclipse/kapua/service/device/registry/steps/DeviceRegistrySteps.java b/service/device/registry/test-steps/src/main/java/org/eclipse/kapua/service/device/registry/steps/DeviceRegistrySteps.java index a970d78eeff..16c76d1e5ef 100644 --- a/service/device/registry/test-steps/src/main/java/org/eclipse/kapua/service/device/registry/steps/DeviceRegistrySteps.java +++ b/service/device/registry/test-steps/src/main/java/org/eclipse/kapua/service/device/registry/steps/DeviceRegistrySteps.java @@ -23,18 +23,9 @@ import java.util.Set; import java.util.UUID; import java.util.Vector; + import javax.inject.Inject; -import com.google.common.base.Strings; -import com.google.common.collect.Lists; -import com.google.inject.Singleton; -import io.cucumber.java.After; -import io.cucumber.java.Before; -import io.cucumber.java.Scenario; -import io.cucumber.java.en.And; -import io.cucumber.java.en.Given; -import io.cucumber.java.en.Then; -import io.cucumber.java.en.When; import org.apache.commons.lang3.StringUtils; import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.commons.model.id.KapuaEid; @@ -72,7 +63,6 @@ import org.eclipse.kapua.service.authorization.domain.Domain; import org.eclipse.kapua.service.authorization.group.Group; import org.eclipse.kapua.service.authorization.group.GroupAttributes; -import org.eclipse.kapua.service.authorization.group.GroupFactory; import org.eclipse.kapua.service.authorization.group.GroupQuery; import org.eclipse.kapua.service.authorization.group.GroupService; import org.eclipse.kapua.service.device.management.message.KapuaMethod; @@ -89,7 +79,6 @@ import org.eclipse.kapua.service.device.registry.DeviceStatus; import org.eclipse.kapua.service.device.registry.connection.DeviceConnection; import org.eclipse.kapua.service.device.registry.connection.DeviceConnectionCreator; -import org.eclipse.kapua.service.device.registry.connection.DeviceConnectionFactory; import org.eclipse.kapua.service.device.registry.connection.DeviceConnectionListResult; import org.eclipse.kapua.service.device.registry.connection.DeviceConnectionQuery; import org.eclipse.kapua.service.device.registry.connection.DeviceConnectionService; @@ -105,7 +94,6 @@ import org.eclipse.kapua.service.tag.Tag; import org.eclipse.kapua.service.tag.TagAttributes; import org.eclipse.kapua.service.tag.TagCreator; -import org.eclipse.kapua.service.tag.TagFactory; import org.eclipse.kapua.service.tag.TagListResult; import org.eclipse.kapua.service.tag.TagQuery; import org.eclipse.kapua.service.tag.TagService; @@ -115,12 +103,22 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import com.google.common.base.Strings; +import com.google.common.collect.Lists; +import com.google.inject.Singleton; + +import io.cucumber.java.After; +import io.cucumber.java.Before; +import io.cucumber.java.Scenario; +import io.cucumber.java.en.And; +import io.cucumber.java.en.Given; +import io.cucumber.java.en.Then; +import io.cucumber.java.en.When; + /** * Implementation of Gherkin steps used in DeviceRegistry.feature scenarios. *

        - * MockedLocator is used for Location Service. Mockito is used to mock other - * services that the Device Registry services dependent on. Dependent services are: - - * Authorization Service - + * MockedLocator is used for Location Service. Mockito is used to mock other services that the Device Registry services dependent on. Dependent services are: - Authorization Service - */ @Singleton public class DeviceRegistrySteps extends TestBase { @@ -172,23 +170,19 @@ public class DeviceRegistrySteps extends TestBase { // Various device connection service related references private DeviceConnectionService deviceConnectionService; - private DeviceConnectionFactory deviceConnectionFactory; // Various device event service related references private DeviceEventService eventService; private DeviceEventFactory eventFactory; - // Additional service references for integration testing private DeviceLifeCycleService deviceLifeCycleService; private AccountService accountService; private UserService userService; private TagService tagService; - private TagFactory tagFactory; private KapuaMessageFactory messageFactory; private KapuaLifecycleMessageFactory lifecycleMessageFactory; private GroupService groupService; - private GroupFactory groupFactory; private AclCreator aclCreator; @@ -220,7 +214,6 @@ public void setServices() { deviceFactory = locator.getFactory(DeviceFactory.class); deviceConnectionService = locator.getService(DeviceConnectionService.class); - deviceConnectionFactory = locator.getFactory(DeviceConnectionFactory.class); eventService = locator.getService(DeviceEventService.class); eventFactory = locator.getFactory(DeviceEventFactory.class); @@ -232,10 +225,7 @@ public void setServices() { accountService = locator.getService(AccountService.class); userService = locator.getService(UserService.class); tagService = locator.getService(TagService.class); - tagFactory = locator.getFactory(TagFactory.class); groupService = locator.getService(GroupService.class); - groupFactory = locator.getFactory(GroupFactory.class); - aclCreator = new AclCreator(); } @@ -391,7 +381,6 @@ public void createDevicesWithParametersAndConnection(List devLst) thr createDevicesAsSpecifiedInternal(devLst, deviceConnection); } - private void createDevicesAsSpecifiedInternal(List cucDevices, DeviceConnection deviceConnection) throws Exception { primeException(); try { @@ -420,7 +409,7 @@ private void createDevicesAsSpecifiedInternal(List cucDevices, Device public void createDeviceWithName(String clientId) throws KapuaException { Account lastAccount = (Account) stepData.get(LAST_ACCOUNT); - DeviceCreator deviceCreator = deviceFactory.newCreator(lastAccount.getId()); + DeviceCreator deviceCreator = new DeviceCreator(lastAccount.getId()); deviceCreator.setClientId(clientId); Device device = deviceRegistryService.create(deviceCreator); @@ -439,7 +428,7 @@ public void createDeviceWithInvalidSymbolsInName() throws Exception { for (int i = 0; i < invalidSymbols.length(); i++) { String clientId = DEVICE + invalidSymbols.charAt(i); try { - DeviceCreator tmpDevCr = deviceFactory.newCreator(tmpAcc.getId(), clientId); + DeviceCreator tmpDevCr = new DeviceCreator(tmpAcc.getId(), clientId); Device tmpDev = deviceRegistryService.create(tmpDevCr); } catch (KapuaException e) { verifyException(e); @@ -468,13 +457,13 @@ public void setDeviceIdToNull() { @Given("A regular query") public void createRegularQuery() { - DeviceQuery query = deviceFactory.newQuery(getCurrentScopeId()); + DeviceQuery query = new DeviceQuery(getCurrentScopeId()); stepData.put(DEVICE_QUERY, query); } @Given("A query with a null Scope ID") public void createQueryWithNullScopeId() { - DeviceQuery query = deviceFactory.newQuery(null); + DeviceQuery query = new DeviceQuery(null); stepData.put(DEVICE_QUERY, query); } @@ -522,7 +511,7 @@ public void generateABunchOfTestDevices(int number, String version) throws Excep primeException(); try { for (int i = 0; i < number; i++) { - tmpDevCr = deviceFactory.newCreator(getCurrentScopeId(), "test_" + String.valueOf(random.nextInt())); + tmpDevCr = new DeviceCreator(getCurrentScopeId(), "test_" + String.valueOf(random.nextInt())); tmpDevCr.setBiosVersion(version); deviceRegistryService.create(tmpDevCr); } @@ -541,7 +530,7 @@ public void generateABunchOfTestDevicesInScope(int number, int scope) throws Exc for (int i = 0; i < number; i++) { tmpId = new KapuaEid(BigInteger.valueOf(scope)); tmpClient = "test_" + String.valueOf(random.nextInt()); - tmpDevCr = deviceFactory.newCreator(tmpId, tmpClient); + tmpDevCr = new DeviceCreator(tmpId, tmpClient); deviceRegistryService.create(tmpDevCr); } } catch (KapuaException ex) { @@ -639,7 +628,7 @@ public void queryForDevices() throws Exception { @When("I query for devices with BIOS version {string}") public void queryForDevicesBasedOnBiosVersion(String version) throws Exception { - DeviceQuery tmpQuery = deviceFactory.newQuery(getCurrentScopeId()); + DeviceQuery tmpQuery = new DeviceQuery(getCurrentScopeId()); // Search for the known bios version string tmpQuery.setPredicate(tmpQuery.attributePredicate(DeviceAttributes.BIOS_VERSION, version, AttributePredicate.Operator.EQUAL)); primeException(); @@ -654,7 +643,7 @@ public void queryForDevicesBasedOnBiosVersion(String version) throws Exception { @When("I query for devices with BIOS different from {string}") public void queryForDevicesWithDifferentBiosVersion(String version) throws Exception { - DeviceQuery tmpQuery = deviceFactory.newQuery(getCurrentScopeId()); + DeviceQuery tmpQuery = new DeviceQuery(getCurrentScopeId()); // Search for the known bios version string tmpQuery.setPredicate(tmpQuery.attributePredicate(DeviceAttributes.BIOS_VERSION, version, AttributePredicate.Operator.EQUAL)); primeException(); @@ -669,7 +658,7 @@ public void queryForDevicesWithDifferentBiosVersion(String version) throws Excep @When("I query for devices with Client Id {string}") public void queryForDevicesBasedOnClientId(String id) throws Exception { - DeviceQuery tmpQuery = deviceFactory.newQuery(getCurrentScopeId()); + DeviceQuery tmpQuery = new DeviceQuery(getCurrentScopeId()); // Search for the known bios version string tmpQuery.setPredicate(tmpQuery.attributePredicate(DeviceAttributes.CLIENT_ID, id, AttributePredicate.Operator.EQUAL)); primeException(); @@ -697,12 +686,12 @@ public void countForDevices() throws Exception { @When("I count the devices in scope {int}") public void countDevicesInScope(int scope) throws Exception { - updateCount(() -> (int) deviceRegistryService.count(deviceFactory.newQuery(getKapuaId(scope)))); + updateCount(() -> (int) deviceRegistryService.count(new DeviceQuery(getKapuaId(scope)))); } @When("I count devices with BIOS version {string}") public void countDevicesWithBIOSVersion(String version) throws Exception { - DeviceQuery tmpQuery = deviceFactory.newQuery(getCurrentScopeId()); + DeviceQuery tmpQuery = new DeviceQuery(getCurrentScopeId()); tmpQuery.setPredicate(tmpQuery.attributePredicate(DeviceAttributes.BIOS_VERSION, version, AttributePredicate.Operator.EQUAL)); updateCount(() -> (int) deviceRegistryService.count(tmpQuery)); } @@ -762,7 +751,7 @@ public void deleteDeviceWithRememberedId() throws Exception { public void deleteDeviceWithClientId(String clientId) throws Exception { try { primeException(); - DeviceQuery tmpQuery = deviceFactory.newQuery(getCurrentScopeId()); + DeviceQuery tmpQuery = new DeviceQuery(getCurrentScopeId()); tmpQuery.setPredicate(tmpQuery.attributePredicate(DeviceAttributes.CLIENT_ID, clientId, AttributePredicate.Operator.EQUAL)); DeviceListResult deviceList = deviceRegistryService.query(tmpQuery); Device device = deviceList.getFirstItem(); @@ -1002,9 +991,9 @@ public void exerciseAllDeviceFactoryFunctions() { DeviceQuery tmpQuery; DeviceListResult tmpListRes; tmpDevice = deviceFactory.newEntity(SYS_SCOPE_ID); - tmpCreator = deviceFactory.newCreator(SYS_SCOPE_ID); - tmpQuery = deviceFactory.newQuery(SYS_SCOPE_ID); - tmpListRes = deviceFactory.newListResult(); + tmpCreator = new DeviceCreator(SYS_SCOPE_ID); + tmpQuery = new DeviceQuery(SYS_SCOPE_ID); + tmpListRes = new DeviceListResult(); Assert.assertNotNull(tmpDevice); Assert.assertNotNull(tmpCreator); Assert.assertNotNull(tmpQuery); @@ -1071,10 +1060,10 @@ public void createConnections(List cucConnections) throws Excepti DeviceConnectionCreator connectionCreator = null; DeviceConnection deviceConnection = null; - DeviceConnectionListResult deviceConnections = deviceConnectionFactory.newListResult(); + DeviceConnectionListResult deviceConnections = new DeviceConnectionListResult(); for (CucConnection cucConnection : cucConnections) { - connectionCreator = deviceConnectionFactory.newCreator(scopeId); + connectionCreator = new DeviceConnectionCreator(scopeId); connectionCreator.setStatus(DeviceConnectionStatus.CONNECTED); connectionCreator.setUserId(userId); connectionCreator.setUserCouplingMode(ConnectionUserCouplingMode.LOOSE); @@ -1083,7 +1072,8 @@ public void createConnections(List cucConnections) throws Excepti connectionCreator.setServerIp(cucConnection.getServerIp()); connectionCreator.setProtocol(cucConnection.getProtocol()); connectionCreator.setAllowUserChange(false); - connectionCreator.setAuthenticationType(deviceConnectionService.getAvailableAuthTypes().stream().findFirst().orElseThrow(() -> new IllegalStateException("No DeviceConnection authenticationTypes are available for testing"))); + connectionCreator.setAuthenticationType(deviceConnectionService.getAvailableAuthTypes().stream().findFirst() + .orElseThrow(() -> new IllegalStateException("No DeviceConnection authenticationTypes are available for testing"))); deviceConnection = deviceConnectionService.create(connectionCreator); deviceConnections.addItem(deviceConnection); } @@ -1216,7 +1206,7 @@ public void checkDeviceConnectionStatus(String status) { @Then("I count {int} connections in scope {int}") public void countConnectioncInScope(int target, int scope) throws Exception { - updateCountAndCheck(() -> (int) deviceConnectionService.count(deviceConnectionFactory.newQuery(getKapuaId(scope))), target); + updateCountAndCheck(() -> (int) deviceConnectionService.count(new DeviceConnectionQuery(getKapuaId(scope))), target); } @When("I search for a connection by scope and connection IDs") @@ -1282,7 +1272,7 @@ public void deleteRandomConnection() throws Exception { @When("I query for all connections with the parameter {string} set to {string}") public void queryForConnections(String parameter, String value) throws Exception { - DeviceConnectionQuery query = deviceConnectionFactory.newQuery(getCurrentScopeId()); + DeviceConnectionQuery query = new DeviceConnectionQuery(getCurrentScopeId()); query.setPredicate(query.attributePredicate(parameter, value, AttributePredicate.Operator.EQUAL)); primeException(); try { @@ -1340,8 +1330,8 @@ public void checkThatConnectionIsNull() { public void exerciseAllConnectionFactoryFunctions() { DeviceConnectionCreator tmpCreator = null; DeviceConnectionQuery tmpQuery = null; - tmpCreator = deviceConnectionFactory.newCreator(SYS_SCOPE_ID); - tmpQuery = deviceConnectionFactory.newQuery(SYS_SCOPE_ID); + tmpCreator = new DeviceConnectionCreator(SYS_SCOPE_ID); + tmpQuery = new DeviceConnectionQuery(SYS_SCOPE_ID); Assert.assertNotNull(tmpCreator); Assert.assertNotNull(tmpQuery); } @@ -1463,12 +1453,12 @@ public void deleteEventWithRandomId() throws Exception { @When("I count events for scope {int}") public void countEventsInScope(int scpId) throws Exception { - updateCount(() -> (int) eventService.count(eventFactory.newQuery(getKapuaId(scpId)))); + updateCount(() -> (int) eventService.count(new DeviceEventQuery(getKapuaId(scpId)))); } @When("I query for {string} events") public void queryForSpecificEvents(String eventType) throws Exception { - DeviceEventQuery tmpQuery = eventFactory.newQuery(getCurrentScopeId()); + DeviceEventQuery tmpQuery = new DeviceEventQuery(getCurrentScopeId()); Assert.assertNotNull(tmpQuery); KapuaMethod tmpMeth = getMethodFromString(eventType); Assert.assertNotNull(tmpMeth); @@ -1510,7 +1500,7 @@ public void searchForEventsGreaterFromDeviceWithClientID(String clientId, String Assert.assertNotNull(account); Device device = deviceRegistryService.findByClientId(account.getId(), clientId); Assert.assertNotNull(device); - DeviceEventQuery eventQuery = eventFactory.newQuery(account.getId()); + DeviceEventQuery eventQuery = new DeviceEventQuery(account.getId()); eventQuery.setPredicate(eventQuery.attributePredicate(DeviceEventAttributes.DEVICE_ID, device.getId(), AttributePredicate.Operator.EQUAL)); eventQuery.setSortCriteria(eventQuery.fieldSortCriteria(DeviceEventAttributes.RECEIVED_ON, SortOrder.ASCENDING)); DeviceEventListResult deviceEventList = eventService.query(eventQuery); @@ -1550,7 +1540,7 @@ private void searchForEventsFromDeviceWithClientIDInternal(String clientId, Stri private boolean searchForEventsFromDeviceWithClientID(Account account, Device device, int events, boolean timeoutOccurred, boolean greater) throws Exception { DeviceEventListResult deviceEventList = null; try { - DeviceEventQuery eventQuery = eventFactory.newQuery(account.getId()); + DeviceEventQuery eventQuery = new DeviceEventQuery(account.getId()); eventQuery.setPredicate(eventQuery.attributePredicate(DeviceEventAttributes.DEVICE_ID, device.getId(), AttributePredicate.Operator.EQUAL)); eventQuery.setSortCriteria(eventQuery.fieldSortCriteria(DeviceEventAttributes.RECEIVED_ON, SortOrder.ASCENDING)); deviceEventList = eventService.query(eventQuery); @@ -1613,14 +1603,14 @@ public void checkEventList(int number) throws Exception { private void printEvents(DeviceEventListResult eventList, int count) throws Exception { logger.info("Events size: {}", eventList.getSize()); eventList.getItems().forEach((event) -> logger.info("\ttype: {} - id: {} - date: {} - {}", event.getType(), event.getDeviceId(), event.getCreatedOn(), event.getEventMessage())); -// if (count > eventList.getSize()) { -// logger.info("++++++++++++++++++++++++++++++++++++++++++++++++\n===========================================================\n\n"); -// Thread.sleep(30000); -// searchForEventsFromDeviceWithClientID("rpione3", "kapua-sys" ); -// eventList = (DeviceEventListResult) stepData.get(DEVICE_EVENT_LIST); -// eventList.getItems().forEach((event) -> logger.info("\ttype: {} - id: {} - date: {} - {}", event.getType(), event.getDeviceId(), event.getCreatedOn(), event.getEventMessage())); -// logger.info("++++++++++++++++++++++++++++++++++++++++++++++++\n===========================================================\n\n"); -// } + // if (count > eventList.getSize()) { + // logger.info("++++++++++++++++++++++++++++++++++++++++++++++++\n===========================================================\n\n"); + // Thread.sleep(30000); + // searchForEventsFromDeviceWithClientID("rpione3", "kapua-sys" ); + // eventList = (DeviceEventListResult) stepData.get(DEVICE_EVENT_LIST); + // eventList.getItems().forEach((event) -> logger.info("\ttype: {} - id: {} - date: {} - {}", event.getType(), event.getDeviceId(), event.getCreatedOn(), event.getEventMessage())); + // logger.info("++++++++++++++++++++++++++++++++++++++++++++++++\n===========================================================\n\n"); + // } } @Then("There is no such event") @@ -1635,9 +1625,9 @@ public void exerciseAllEventFactoryFunctions() { DeviceEventQuery tmpQuery = null; DeviceEventListResult tmpList = null; tmpEvent = eventFactory.newEntity(SYS_SCOPE_ID); - tmpCreator = eventFactory.newCreator(SYS_SCOPE_ID, getKapuaId(), new Date(), ""); - tmpQuery = eventFactory.newQuery(SYS_SCOPE_ID); - tmpList = eventFactory.newListResult(); + tmpCreator = new DeviceEventCreator(SYS_SCOPE_ID, getKapuaId(), new Date(), ""); + tmpQuery = new DeviceEventQuery(SYS_SCOPE_ID); + tmpList = new DeviceEventListResult(); Assert.assertNotNull(tmpEvent); Assert.assertNotNull(tmpCreator); Assert.assertNotNull(tmpQuery); @@ -1661,7 +1651,7 @@ public void checkDeviceEventDomainUpdate() { @When("I search for the device {string} in account {string}") public void searchForDeviceWithClientID(String clientId, String account) throws Exception { - DeviceListResult tmpList = deviceFactory.newListResult(); + DeviceListResult tmpList = new DeviceListResult(); primeException(); try { stepData.remove(DEVICE); @@ -1686,7 +1676,7 @@ public void iTagDeviceWithTag(String deviceTagName) throws Exception { Device device = (Device) stepData.get(DEVICE); primeException(); try { - TagCreator tagCreator = tagFactory.newCreator(account.getId()); + TagCreator tagCreator = new TagCreator(account.getId()); tagCreator.setName(deviceTagName); Tag tag = tagService.create(tagCreator); Set tags = new HashSet<>(); @@ -1704,8 +1694,8 @@ public void iTagDeviceWithTag(String deviceTagName) throws Exception { @When("I search for device with tag {string}") public void iSearchForDeviceWithTag(String deviceTagName) throws Exception { Account lastAcc = (Account) stepData.get(LAST_ACCOUNT); - DeviceQuery deviceQuery = deviceFactory.newQuery(lastAcc.getId()); - TagQuery tagQuery = tagFactory.newQuery(lastAcc.getId()); + DeviceQuery deviceQuery = new DeviceQuery(lastAcc.getId()); + TagQuery tagQuery = new TagQuery(lastAcc.getId()); tagQuery.setPredicate(tagQuery.attributePredicate(TagAttributes.NAME, deviceTagName, AttributePredicate.Operator.EQUAL)); primeException(); try { @@ -1886,7 +1876,6 @@ public void createAnApplicationMessage(String clientId) throws Exception { } } - @Given("Such a set of privileged users for account {string}") public void createPrivilegedUsers(String accName, List users) throws Throwable { KapuaSecurityUtils.doPrivileged(() -> { @@ -1928,14 +1917,15 @@ public void setDeviceConnectionCouplingMode(String name, String mode) throws Kap public void createConnectionForDevice(List connections) throws KapuaException { KapuaSecurityUtils.doPrivileged(() -> { for (CucConnection tmpConn : connections) { - DeviceConnectionCreator tmpCreator = deviceConnectionFactory.newCreator(tmpConn.getScopeId()); + DeviceConnectionCreator tmpCreator = new DeviceConnectionCreator(tmpConn.getScopeId()); tmpCreator.setStatus(DeviceConnectionStatus.CONNECTED); tmpCreator.setClientId(tmpConn.getClientId()); tmpCreator.setUserId(tmpConn.getUserId()); tmpCreator.setReservedUserId(tmpConn.getReservedUserId()); tmpCreator.setAllowUserChange(tmpConn.getAllowUserChange()); tmpCreator.setUserCouplingMode(tmpConn.getUserCouplingMode()); - tmpCreator.setAuthenticationType(deviceConnectionService.getAvailableAuthTypes().stream().findFirst().orElseThrow(() -> new IllegalStateException("No DeviceConnection authenticationTypes are available for testing"))); + tmpCreator.setAuthenticationType(deviceConnectionService.getAvailableAuthTypes().stream().findFirst() + .orElseThrow(() -> new IllegalStateException("No DeviceConnection authenticationTypes are available for testing"))); DeviceConnection tmpDevConn = deviceConnectionService.create(tmpCreator); tmpDevConn.setStatus(DeviceConnectionStatus.DISCONNECTED); deviceConnectionService.update(tmpDevConn); @@ -1953,7 +1943,7 @@ public void searchForConnectionFromDeviceWithClientID(String clientId, String ac KapuaSecurityUtils.doPrivileged(() -> { Account tmpAcc; DeviceConnection tmpConn; - DeviceConnectionListResult tmpConnLst = deviceConnectionFactory.newListResult(); + DeviceConnectionListResult tmpConnLst = new DeviceConnectionListResult(); tmpAcc = accountService.findByName(account); Assert.assertNotNull(tmpAcc); Assert.assertNotNull(tmpAcc.getId()); @@ -1999,7 +1989,8 @@ public void searchForConnectionFromDeviceWithClientIDStatusAndUser(String client searchForConnectionFromDeviceWithClientIDStatusAndUser(clientId, account.getId(), status, connectionUserId.getId(), true); } - private boolean searchForConnectionFromDeviceWithClientIDStatusAndUser(String clientId, KapuaId accountId, String connectionStatus, KapuaId connectionUserId, boolean timeoutOccurred) throws Exception { + private boolean searchForConnectionFromDeviceWithClientIDStatusAndUser(String clientId, KapuaId accountId, String connectionStatus, KapuaId connectionUserId, boolean timeoutOccurred) + throws Exception { try { Device device = deviceRegistryService.findByClientId(accountId, clientId); if (timeoutOccurred) { @@ -2022,7 +2013,7 @@ private boolean searchForConnectionFromDeviceWithClientIDStatusAndUser(String cl } } stepData.put(DEVICE_CONNECTION, deviceConnection); - DeviceConnectionListResult tmpConnLst = deviceConnectionFactory.newListResult(); + DeviceConnectionListResult tmpConnLst = new DeviceConnectionListResult(); Vector dcv = new Vector<>(); dcv.add(deviceConnection); tmpConnLst.addItems(dcv); @@ -2125,7 +2116,7 @@ public void checkUserForExistingConnection(String device, String scope, String n // Create a device creator object. The creator is pre-filled with default data. private DeviceCreator prepareRegularDeviceCreator(KapuaId scopeId, String clientId) { - DeviceCreator deviceCreator = deviceFactory.newCreator(scopeId); + DeviceCreator deviceCreator = new DeviceCreator(scopeId); deviceCreator.setClientId(clientId); deviceCreator.setStatus(DeviceStatus.ENABLED); @@ -2184,7 +2175,7 @@ private Device prepareRegularDevice(KapuaId accountId, KapuaId deviceId) { // Create a connection creator object. The creator is pre-filled with default data. private DeviceConnectionCreator prepareRegularConnectionCreator(KapuaId scopeId, KapuaId userId) { - DeviceConnectionCreator creator = deviceConnectionFactory.newCreator(scopeId); + DeviceConnectionCreator creator = new DeviceConnectionCreator(scopeId); creator.setUserId(userId); creator.setUserCouplingMode(ConnectionUserCouplingMode.LOOSE); creator.setReservedUserId(userId); @@ -2193,13 +2184,14 @@ private DeviceConnectionCreator prepareRegularConnectionCreator(KapuaId scopeId, creator.setServerIp(SERVER_IP); creator.setProtocol("tcp"); creator.setAllowUserChange(false); - creator.setAuthenticationType(deviceConnectionService.getAvailableAuthTypes().stream().findFirst().orElseThrow(() -> new IllegalStateException("No DeviceConnection authenticationTypes are available for testing"))); + creator.setAuthenticationType( + deviceConnectionService.getAvailableAuthTypes().stream().findFirst().orElseThrow(() -> new IllegalStateException("No DeviceConnection authenticationTypes are available for testing"))); return creator; } // Create a event creator object. The creator is pre-filled with default data. private DeviceEventCreator prepareRegularDeviceEventCreator(KapuaId accountId, KapuaId deviceId) { - DeviceEventCreator tmpCreator = eventFactory.newCreator(accountId); + DeviceEventCreator tmpCreator = new DeviceEventCreator(accountId); KapuaPosition tmpPosition = messageFactory.newPosition(); Date timeReceived = new Date(); Date timeSent = new Date(System.currentTimeMillis() - 5 * 60 * 1000); @@ -2226,31 +2218,31 @@ private DeviceEventCreator prepareRegularDeviceEventCreator(KapuaId accountId, K private KapuaMethod getMethodFromString(String name) { KapuaMethod tmpMeth = null; switch (name.trim().toUpperCase()) { - case "READ": - tmpMeth = KapuaMethod.READ; - break; - case "CREATE": - tmpMeth = KapuaMethod.CREATE; - break; - case "WRITE": - tmpMeth = KapuaMethod.WRITE; - break; - case "DELETE": - tmpMeth = KapuaMethod.DELETE; - break; - case "OPTIONS": - tmpMeth = KapuaMethod.OPTIONS; - break; - case "EXECUTE": - tmpMeth = KapuaMethod.EXECUTE; - break; + case "READ": + tmpMeth = KapuaMethod.READ; + break; + case "CREATE": + tmpMeth = KapuaMethod.CREATE; + break; + case "WRITE": + tmpMeth = KapuaMethod.WRITE; + break; + case "DELETE": + tmpMeth = KapuaMethod.DELETE; + break; + case "OPTIONS": + tmpMeth = KapuaMethod.OPTIONS; + break; + case "EXECUTE": + tmpMeth = KapuaMethod.EXECUTE; + break; } Assert.assertNotNull(tmpMeth); return tmpMeth; } private Device getDeviceWithClientId(String clientId) throws KapuaException { - DeviceQuery tmpQuery = deviceFactory.newQuery(getCurrentScopeId()); + DeviceQuery tmpQuery = new DeviceQuery(getCurrentScopeId()); tmpQuery.setPredicate(tmpQuery.attributePredicate(DeviceAttributes.CLIENT_ID, clientId)); DeviceListResult deviceList = deviceRegistryService.query(tmpQuery); @@ -2454,41 +2446,41 @@ private DeviceCreator prepareDeviceCreatorFromCucDevice(CucDevice cucDevice) { DeviceConnectionStatus parseConnectionStatusString(String stat) { switch (stat.trim().toUpperCase()) { - case "CONNECTED": - return DeviceConnectionStatus.CONNECTED; - case "DISCONNECTED": - return DeviceConnectionStatus.DISCONNECTED; - case "MISSING": - return DeviceConnectionStatus.MISSING; + case "CONNECTED": + return DeviceConnectionStatus.CONNECTED; + case "DISCONNECTED": + return DeviceConnectionStatus.DISCONNECTED; + case "MISSING": + return DeviceConnectionStatus.MISSING; } return null; } ConnectionUserCouplingMode parseConnectionCouplingString(String mode) { switch (mode.trim().toUpperCase()) { - case "INHERITED": - return ConnectionUserCouplingMode.INHERITED; - case "LOOSE": - return ConnectionUserCouplingMode.LOOSE; - case "STRICT": - return ConnectionUserCouplingMode.STRICT; + case "INHERITED": + return ConnectionUserCouplingMode.INHERITED; + case "LOOSE": + return ConnectionUserCouplingMode.LOOSE; + case "STRICT": + return ConnectionUserCouplingMode.STRICT; } return null; } boolean parseBooleanFromString(String value) { switch (value.trim().toLowerCase()) { - case "true": - return true; - case "false": - return false; + case "true": + return true; + case "false": + return false; } return false; } @Then("I create a device with name {string}") public void iCreateADeviceWithName(String clientId) throws Exception { - DeviceCreator deviceCreator = deviceFactory.newCreator(getCurrentScopeId()); + DeviceCreator deviceCreator = new DeviceCreator(getCurrentScopeId()); deviceCreator.setClientId(clientId); stepData.put(DEVICE_CREATOR, deviceCreator); try { @@ -2501,17 +2493,16 @@ public void iCreateADeviceWithName(String clientId) throws Exception { } } - @Then("I create a device with name {string} and tags") public void iCreateADeviceWithName(String clientId, List tags) throws Exception { final HashSet tagIds = new HashSet<>(); - final TagCreator tagCreator = tagFactory.newCreator(getCurrentScopeId()); + final TagCreator tagCreator = new TagCreator(getCurrentScopeId()); for (String tagName : tags) { tagCreator.setName(tagName); final Tag tag = tagService.create(tagCreator); tagIds.add(tag.getId()); } - final DeviceCreator deviceCreator = deviceFactory.newCreator(getCurrentScopeId()); + final DeviceCreator deviceCreator = new DeviceCreator(getCurrentScopeId()); deviceCreator.setClientId(clientId); deviceCreator.setTagIds(tagIds); stepData.put(DEVICE_CREATOR, deviceCreator); @@ -2561,7 +2552,7 @@ public void iSearchForEventsFromDevicesInAccount(String account, int eventsNum) tmpDev = deviceRegistryService.findByClientId(tmpAcc.getId(), device.getClientId()); Assert.assertNotNull(tmpDev); Assert.assertNotNull(tmpDev.getId()); - tmpQuery = eventFactory.newQuery(tmpAcc.getId()); + tmpQuery = new DeviceEventQuery(tmpAcc.getId()); tmpQuery.setPredicate(tmpQuery.attributePredicate(DeviceEventAttributes.DEVICE_ID, tmpDev.getId(), AttributePredicate.Operator.EQUAL)); tmpQuery.setSortCriteria(tmpQuery.fieldSortCriteria(DeviceEventAttributes.RECEIVED_ON, SortOrder.ASCENDING)); tmpList = eventService.query(tmpQuery); @@ -2593,11 +2584,11 @@ public void iAssignTagToDevice() throws Exception { @And("I assign tag {string} to device {string}") public void iAssignTagNamedToDevice(String tagName, String deviceName) throws Exception { try { - DeviceQuery tmpQuery = deviceFactory.newQuery(getCurrentScopeId()); + DeviceQuery tmpQuery = new DeviceQuery(getCurrentScopeId()); tmpQuery.setPredicate(tmpQuery.attributePredicate(DeviceAttributes.CLIENT_ID, deviceName, AttributePredicate.Operator.EQUAL)); DeviceListResult deviceList = deviceRegistryService.query(tmpQuery); Device device = deviceList.getFirstItem(); - TagQuery tagQuery = tagFactory.newQuery(getCurrentScopeId()); + TagQuery tagQuery = new TagQuery(getCurrentScopeId()); tagQuery.setPredicate(tagQuery.attributePredicate(TagAttributes.NAME, tagName, AttributePredicate.Operator.EQUAL)); TagListResult tagList = tagService.query(tagQuery); Tag tag = tagList.getFirstItem(); @@ -2614,10 +2605,10 @@ public void iAssignTagNamedToDevice(String tagName, String deviceName) throws Ex @And("I add device {string} to group {string}") public void iAddDeviceToGroup(String deviceName, String groupName) throws Exception { try { - GroupQuery query = groupFactory.newQuery(getCurrentScopeId()); + GroupQuery query = new GroupQuery(getCurrentScopeId()); query.setPredicate(query.attributePredicate(GroupAttributes.NAME, groupName, AttributePredicate.Operator.EQUAL)); Group foundGroup = groupService.query(query).getFirstItem(); - DeviceQuery tmpQuery = deviceFactory.newQuery(getCurrentScopeId()); + DeviceQuery tmpQuery = new DeviceQuery(getCurrentScopeId()); tmpQuery.setPredicate(tmpQuery.attributePredicate(DeviceAttributes.CLIENT_ID, deviceName, AttributePredicate.Operator.EQUAL)); Device device = deviceRegistryService.query(tmpQuery).getFirstItem(); KapuaId groupId = foundGroup.getId(); @@ -2644,11 +2635,11 @@ public void iTryToEditDevicesDisplayNameTo(String displayName) throws Exception @Given("Tag {string} is assigned to device {string}") public void tagIsAssignedToDevice(String tagName, String deviceName) throws Throwable { try { - DeviceQuery tmpQuery = deviceFactory.newQuery(getCurrentScopeId()); + DeviceQuery tmpQuery = new DeviceQuery(getCurrentScopeId()); tmpQuery.setPredicate(tmpQuery.attributePredicate(DeviceAttributes.CLIENT_ID, deviceName, AttributePredicate.Operator.EQUAL)); DeviceListResult deviceList = deviceRegistryService.query(tmpQuery); Device device = deviceList.getFirstItem(); - TagQuery tagQuery = tagFactory.newQuery(getCurrentScopeId()); + TagQuery tagQuery = new TagQuery(getCurrentScopeId()); tagQuery.setPredicate(tagQuery.attributePredicate(TagAttributes.NAME, tagName, AttributePredicate.Operator.EQUAL)); TagListResult tagList = tagService.query(tagQuery); Tag tag = tagList.getFirstItem(); @@ -2662,7 +2653,7 @@ public void tagIsAssignedToDevice(String tagName, String deviceName) throws Thro @When("I remove device {string} from all groups") public void iChangeDevicesGroupToNoGroup(String deviceName) throws Exception { try { - DeviceQuery tmpQuery = deviceFactory.newQuery(getCurrentScopeId()); + DeviceQuery tmpQuery = new DeviceQuery(getCurrentScopeId()); tmpQuery.setPredicate(tmpQuery.attributePredicate(DeviceAttributes.CLIENT_ID, deviceName, AttributePredicate.Operator.EQUAL)); Device device = deviceRegistryService.query(tmpQuery).getFirstItem(); device.setGroupId(null); @@ -2705,11 +2696,11 @@ public void iCreateDevicesAndAddThemToGroup(int numberOfDevices, String groupNam @Given("I unassign tag {string} from device {string}") public void iUnassignTagNamedFromDevice(String tagName, String deviceName) throws Exception { try { - DeviceQuery tmpQuery = deviceFactory.newQuery(getCurrentScopeId()); + DeviceQuery tmpQuery = new DeviceQuery(getCurrentScopeId()); tmpQuery.setPredicate(tmpQuery.attributePredicate(DeviceAttributes.CLIENT_ID, deviceName, AttributePredicate.Operator.EQUAL)); DeviceListResult deviceList = deviceRegistryService.query(tmpQuery); Device device = deviceList.getFirstItem(); - TagQuery tagQuery = tagFactory.newQuery(getCurrentScopeId()); + TagQuery tagQuery = new TagQuery(getCurrentScopeId()); tagQuery.setPredicate(tagQuery.attributePredicate(TagAttributes.NAME, tagName, AttributePredicate.Operator.EQUAL)); TagListResult tagList = tagService.query(tagQuery); Tag tag = tagList.getFirstItem(); @@ -2726,10 +2717,10 @@ public void iUnassignTagNamedFromDevice(String tagName, String deviceName) throw @Then("Device {string} is in Assigned Devices of group {string}") public void deviceIsInGroupsAssignedDevices(String deviceName, String groupName) throws Exception { try { - GroupQuery query = groupFactory.newQuery(getCurrentScopeId()); + GroupQuery query = new GroupQuery(getCurrentScopeId()); query.setPredicate(query.attributePredicate(GroupAttributes.NAME, groupName, AttributePredicate.Operator.EQUAL)); Group foundGroup = groupService.query(query).getFirstItem(); - DeviceQuery tmpQuery = deviceFactory.newQuery(getCurrentScopeId()); + DeviceQuery tmpQuery = new DeviceQuery(getCurrentScopeId()); tmpQuery.setPredicate(tmpQuery.attributePredicate(DeviceAttributes.CLIENT_ID, deviceName, AttributePredicate.Operator.EQUAL)); Device device = deviceRegistryService.query(tmpQuery).getFirstItem(); KapuaId expectedGroupId = foundGroup.getId(); @@ -2813,7 +2804,6 @@ private void iChangeDeviceLastEventIdTo(String lastEventId) throws Throwable { } } - @And("The devices display name is {string}") public void theDevicesDisplayNameIs(String displayName) throws Throwable { Device device = (Device) stepData.get(DEVICE); @@ -3181,11 +3171,11 @@ public void iChangeDeviceExtendedPropertiesTo(List cu @Given("Tag {string} is not assigned to device {string}") public void tagWithNameIsNotAssignedToDevice(String tagName, String deviceName) throws Throwable { try { - DeviceQuery tmpQuery = deviceFactory.newQuery(getCurrentScopeId()); + DeviceQuery tmpQuery = new DeviceQuery(getCurrentScopeId()); tmpQuery.setPredicate(tmpQuery.attributePredicate(DeviceAttributes.CLIENT_ID, deviceName, AttributePredicate.Operator.EQUAL)); DeviceListResult deviceList = deviceRegistryService.query(tmpQuery); Device device = deviceList.getFirstItem(); - TagQuery tagQuery = tagFactory.newQuery(getCurrentScopeId()); + TagQuery tagQuery = new TagQuery(getCurrentScopeId()); tagQuery.setPredicate(tagQuery.attributePredicate(TagAttributes.NAME, tagName, AttributePredicate.Operator.EQUAL)); TagListResult tagList = tagService.query(tagQuery); Tag tag = tagList.getFirstItem(); @@ -3199,10 +3189,10 @@ public void tagWithNameIsNotAssignedToDevice(String tagName, String deviceName) @Then("Device {string} is not in Assigned Devices of group {string}") public void deviceIsNotInGroupsAssignedDevices(String deviceName, String groupName) throws Exception { try { - GroupQuery query = groupFactory.newQuery(getCurrentScopeId()); + GroupQuery query = new GroupQuery(getCurrentScopeId()); query.setPredicate(query.attributePredicate(GroupAttributes.NAME, groupName, AttributePredicate.Operator.EQUAL)); Group foundGroup = groupService.query(query).getFirstItem(); - DeviceQuery tmpQuery = deviceFactory.newQuery(getCurrentScopeId()); + DeviceQuery tmpQuery = new DeviceQuery(getCurrentScopeId()); tmpQuery.setPredicate(tmpQuery.attributePredicate(DeviceAttributes.CLIENT_ID, deviceName, AttributePredicate.Operator.EQUAL)); Device device = deviceRegistryService.query(tmpQuery).getFirstItem(); KapuaId expectedGroupId = foundGroup.getId(); @@ -3218,91 +3208,91 @@ public void iFilterDevices(List parameters) throws Exception { DeviceListResult devices; stepData.remove("DeviceList"); if (deviceParams.getClientId() != null && deviceParams.getDisplayName() == null && deviceParams.getSerialNumber() == null && deviceParams.getStatus() == null) { - DeviceQuery tmpQuery = deviceFactory.newQuery(getCurrentScopeId()); + DeviceQuery tmpQuery = new DeviceQuery(getCurrentScopeId()); tmpQuery.setPredicate(tmpQuery.attributePredicate(DeviceAttributes.CLIENT_ID, deviceParams.getClientId(), AttributePredicate.Operator.LIKE)); devices = deviceRegistryService.query(tmpQuery); stepData.put("DeviceList", devices); } else if (deviceParams.getClientId() == null && deviceParams.getDisplayName() != null && deviceParams.getSerialNumber() == null && deviceParams.getStatus() == null) { - DeviceQuery tmpQuery = deviceFactory.newQuery(getCurrentScopeId()); + DeviceQuery tmpQuery = new DeviceQuery(getCurrentScopeId()); tmpQuery.setPredicate(tmpQuery.attributePredicate(DeviceAttributes.DISPLAY_NAME, deviceParams.getDisplayName(), AttributePredicate.Operator.LIKE)); devices = deviceRegistryService.query(tmpQuery); stepData.put("DeviceList", devices); } else if (deviceParams.getClientId() == null && deviceParams.getDisplayName() == null && deviceParams.getSerialNumber() != null && deviceParams.getStatus() == null) { - DeviceQuery tmpQuery = deviceFactory.newQuery(getCurrentScopeId()); + DeviceQuery tmpQuery = new DeviceQuery(getCurrentScopeId()); tmpQuery.setPredicate(tmpQuery.attributePredicate(DeviceAttributes.SERIAL_NUMBER, deviceParams.getSerialNumber(), AttributePredicate.Operator.LIKE)); devices = deviceRegistryService.query(tmpQuery); stepData.put("DeviceList", devices); } else if (deviceParams.getClientId() == null && deviceParams.getDisplayName() == null && deviceParams.getSerialNumber() == null && deviceParams.getStatus() != null) { - DeviceQuery tmpQuery = deviceFactory.newQuery(getCurrentScopeId()); + DeviceQuery tmpQuery = new DeviceQuery(getCurrentScopeId()); tmpQuery.setPredicate(tmpQuery.attributePredicate(DeviceAttributes.STATUS, deviceParams.getStatus(), AttributePredicate.Operator.LIKE)); devices = deviceRegistryService.query(tmpQuery); stepData.put("DeviceList", devices); } else if (deviceParams.getClientId() != null && deviceParams.getDisplayName() != null && deviceParams.getSerialNumber() == null && deviceParams.getStatus() == null) { - DeviceQuery tmpQuery = deviceFactory.newQuery(getCurrentScopeId()); + DeviceQuery tmpQuery = new DeviceQuery(getCurrentScopeId()); tmpQuery.setPredicate(tmpQuery.andPredicate(tmpQuery.attributePredicate(DeviceAttributes.CLIENT_ID, deviceParams.getClientId(), AttributePredicate.Operator.LIKE), tmpQuery.attributePredicate(DeviceAttributes.DISPLAY_NAME, deviceParams.getDisplayName(), AttributePredicate.Operator.LIKE))); devices = deviceRegistryService.query(tmpQuery); stepData.put("DeviceList", devices); } else if (deviceParams.getClientId() != null && deviceParams.getDisplayName() == null && deviceParams.getSerialNumber() != null && deviceParams.getStatus() == null) { - DeviceQuery tmpQuery = deviceFactory.newQuery(getCurrentScopeId()); + DeviceQuery tmpQuery = new DeviceQuery(getCurrentScopeId()); tmpQuery.setPredicate(tmpQuery.andPredicate(tmpQuery.attributePredicate(DeviceAttributes.CLIENT_ID, deviceParams.getClientId(), AttributePredicate.Operator.LIKE), tmpQuery.attributePredicate(DeviceAttributes.SERIAL_NUMBER, deviceParams.getSerialNumber(), AttributePredicate.Operator.LIKE))); devices = deviceRegistryService.query(tmpQuery); stepData.put("DeviceList", devices); } else if (deviceParams.getClientId() != null && deviceParams.getDisplayName() == null && deviceParams.getSerialNumber() == null && deviceParams.getStatus() != null) { - DeviceQuery tmpQuery = deviceFactory.newQuery(getCurrentScopeId()); + DeviceQuery tmpQuery = new DeviceQuery(getCurrentScopeId()); tmpQuery.setPredicate(tmpQuery.andPredicate(tmpQuery.attributePredicate(DeviceAttributes.CLIENT_ID, deviceParams.getClientId(), AttributePredicate.Operator.LIKE), tmpQuery.attributePredicate(DeviceAttributes.STATUS, deviceParams.getStatus(), AttributePredicate.Operator.LIKE))); devices = deviceRegistryService.query(tmpQuery); stepData.put("DeviceList", devices); } else if (deviceParams.getClientId() == null && deviceParams.getDisplayName() != null && deviceParams.getSerialNumber() != null && deviceParams.getStatus() == null) { - DeviceQuery tmpQuery = deviceFactory.newQuery(getCurrentScopeId()); + DeviceQuery tmpQuery = new DeviceQuery(getCurrentScopeId()); tmpQuery.setPredicate(tmpQuery.andPredicate(tmpQuery.attributePredicate(DeviceAttributes.SERIAL_NUMBER, deviceParams.getSerialNumber(), AttributePredicate.Operator.LIKE), tmpQuery.attributePredicate(DeviceAttributes.DISPLAY_NAME, deviceParams.getDisplayName(), AttributePredicate.Operator.LIKE))); devices = deviceRegistryService.query(tmpQuery); stepData.put("DeviceList", devices); } else if (deviceParams.getClientId() == null && deviceParams.getDisplayName() != null && deviceParams.getSerialNumber() == null && deviceParams.getStatus() != null) { - DeviceQuery tmpQuery = deviceFactory.newQuery(getCurrentScopeId()); + DeviceQuery tmpQuery = new DeviceQuery(getCurrentScopeId()); tmpQuery.setPredicate(tmpQuery.andPredicate(tmpQuery.attributePredicate(DeviceAttributes.STATUS, deviceParams.getStatus(), AttributePredicate.Operator.LIKE), tmpQuery.attributePredicate(DeviceAttributes.DISPLAY_NAME, deviceParams.getDisplayName(), AttributePredicate.Operator.LIKE))); devices = deviceRegistryService.query(tmpQuery); stepData.put("DeviceList", devices); } else if (deviceParams.getClientId() == null && deviceParams.getDisplayName() == null && deviceParams.getSerialNumber() != null && deviceParams.getStatus() != null) { - DeviceQuery tmpQuery = deviceFactory.newQuery(getCurrentScopeId()); + DeviceQuery tmpQuery = new DeviceQuery(getCurrentScopeId()); tmpQuery.setPredicate(tmpQuery.andPredicate(tmpQuery.attributePredicate(DeviceAttributes.SERIAL_NUMBER, deviceParams.getSerialNumber(), AttributePredicate.Operator.LIKE), tmpQuery.attributePredicate(DeviceAttributes.STATUS, deviceParams.getStatus(), AttributePredicate.Operator.LIKE))); devices = deviceRegistryService.query(tmpQuery); stepData.put("DeviceList", devices); } else if (deviceParams.getClientId() != null && deviceParams.getDisplayName() != null && deviceParams.getSerialNumber() != null && deviceParams.getStatus() == null) { - DeviceQuery tmpQuery = deviceFactory.newQuery(getCurrentScopeId()); + DeviceQuery tmpQuery = new DeviceQuery(getCurrentScopeId()); tmpQuery.setPredicate(tmpQuery.andPredicate(tmpQuery.attributePredicate(DeviceAttributes.CLIENT_ID, deviceParams.getClientId(), AttributePredicate.Operator.LIKE), tmpQuery.attributePredicate(DeviceAttributes.DISPLAY_NAME, deviceParams.getDisplayName(), AttributePredicate.Operator.LIKE), tmpQuery.attributePredicate(DeviceAttributes.SERIAL_NUMBER, deviceParams.getSerialNumber(), AttributePredicate.Operator.LIKE))); devices = deviceRegistryService.query(tmpQuery); stepData.put("DeviceList", devices); } else if (deviceParams.getClientId() != null && deviceParams.getDisplayName() != null && deviceParams.getSerialNumber() == null && deviceParams.getStatus() != null) { - DeviceQuery tmpQuery = deviceFactory.newQuery(getCurrentScopeId()); + DeviceQuery tmpQuery = new DeviceQuery(getCurrentScopeId()); tmpQuery.setPredicate(tmpQuery.andPredicate(tmpQuery.attributePredicate(DeviceAttributes.CLIENT_ID, deviceParams.getClientId(), AttributePredicate.Operator.LIKE), tmpQuery.attributePredicate(DeviceAttributes.DISPLAY_NAME, deviceParams.getDisplayName(), AttributePredicate.Operator.LIKE), tmpQuery.attributePredicate(DeviceAttributes.STATUS, deviceParams.getStatus(), AttributePredicate.Operator.LIKE))); devices = deviceRegistryService.query(tmpQuery); stepData.put("DeviceList", devices); } else if (deviceParams.getClientId() != null && deviceParams.getDisplayName() == null && deviceParams.getSerialNumber() != null && deviceParams.getStatus() != null) { - DeviceQuery tmpQuery = deviceFactory.newQuery(getCurrentScopeId()); + DeviceQuery tmpQuery = new DeviceQuery(getCurrentScopeId()); tmpQuery.setPredicate(tmpQuery.andPredicate(tmpQuery.attributePredicate(DeviceAttributes.CLIENT_ID, deviceParams.getClientId(), AttributePredicate.Operator.LIKE), tmpQuery.attributePredicate(DeviceAttributes.SERIAL_NUMBER, deviceParams.getSerialNumber(), AttributePredicate.Operator.LIKE), tmpQuery.attributePredicate(DeviceAttributes.STATUS, deviceParams.getStatus(), AttributePredicate.Operator.LIKE))); devices = deviceRegistryService.query(tmpQuery); stepData.put("DeviceList", devices); } else if (deviceParams.getClientId() == null && deviceParams.getDisplayName() != null && deviceParams.getSerialNumber() != null && deviceParams.getStatus() != null) { - DeviceQuery tmpQuery = deviceFactory.newQuery(getCurrentScopeId()); + DeviceQuery tmpQuery = new DeviceQuery(getCurrentScopeId()); tmpQuery.setPredicate(tmpQuery.andPredicate(tmpQuery.attributePredicate(DeviceAttributes.SERIAL_NUMBER, deviceParams.getSerialNumber(), AttributePredicate.Operator.LIKE), tmpQuery.attributePredicate(DeviceAttributes.DISPLAY_NAME, deviceParams.getDisplayName(), AttributePredicate.Operator.LIKE), tmpQuery.attributePredicate(DeviceAttributes.STATUS, deviceParams.getStatus(), AttributePredicate.Operator.LIKE))); devices = deviceRegistryService.query(tmpQuery); stepData.put("DeviceList", devices); } else if (deviceParams.getClientId() != null && deviceParams.getDisplayName() != null && deviceParams.getSerialNumber() != null && deviceParams.getStatus() != null) { - DeviceQuery tmpQuery = deviceFactory.newQuery(getCurrentScopeId()); + DeviceQuery tmpQuery = new DeviceQuery(getCurrentScopeId()); tmpQuery.setPredicate(tmpQuery.andPredicate(tmpQuery.attributePredicate(DeviceAttributes.SERIAL_NUMBER, deviceParams.getSerialNumber(), AttributePredicate.Operator.LIKE), tmpQuery.attributePredicate(DeviceAttributes.DISPLAY_NAME, deviceParams.getDisplayName(), AttributePredicate.Operator.LIKE), tmpQuery.attributePredicate(DeviceAttributes.CLIENT_ID, deviceParams.getClientId(), AttributePredicate.Operator.LIKE), @@ -3317,7 +3307,7 @@ public void iSearchForADeviceWithName(String clientID) throws Throwable { try { stepData.remove(DEVICE); primeException(); - DeviceQuery query = deviceFactory.newQuery(SYS_SCOPE_ID); + DeviceQuery query = new DeviceQuery(SYS_SCOPE_ID); query.setPredicate(query.attributePredicate(DeviceAttributes.CLIENT_ID, clientID, AttributePredicate.Operator.EQUAL)); DeviceListResult queryResult = deviceRegistryService.query(query); Device foundDevice = queryResult.getFirstItem(); @@ -3330,7 +3320,7 @@ public void iSearchForADeviceWithName(String clientID) throws Throwable { @Given("I create a device with null clientID") public void iCreateADeviceWithNullClientID() throws Throwable { - DeviceCreator deviceCreator = deviceFactory.newCreator(getCurrentScopeId()); + DeviceCreator deviceCreator = new DeviceCreator(getCurrentScopeId()); deviceCreator.setClientId(null); stepData.put("DeviceCreator", deviceCreator); try { @@ -3345,7 +3335,7 @@ public void iCreateADeviceWithNullClientID() throws Throwable { @Given("I try to create devices with invalid symbols {string} in name") public void iTryToCreateDevicesWithInvalidSymbolsInName(String invalidCharacters) throws Exception { - DeviceCreator deviceCreator = deviceFactory.newCreator(getCurrentScopeId()); + DeviceCreator deviceCreator = new DeviceCreator(getCurrentScopeId()); for (int i = 0; i < invalidCharacters.length(); i++) { String deviceName = "deviceName" + invalidCharacters.charAt(i); deviceCreator.setClientId(deviceName); diff --git a/service/device/registry/test/pom.xml b/service/device/registry/test/pom.xml index f387cc6ac3c..21fd22bffd6 100644 --- a/service/device/registry/test/pom.xml +++ b/service/device/registry/test/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-device-registry - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-device-registry-test diff --git a/service/device/registry/test/src/test/java/org/eclipse/kapua/service/device/registry/test/DeviceRegistryLocatorConfiguration.java b/service/device/registry/test/src/test/java/org/eclipse/kapua/service/device/registry/test/DeviceRegistryLocatorConfiguration.java index b22f83a39f9..f7d3298f6c2 100644 --- a/service/device/registry/test/src/test/java/org/eclipse/kapua/service/device/registry/test/DeviceRegistryLocatorConfiguration.java +++ b/service/device/registry/test/src/test/java/org/eclipse/kapua/service/device/registry/test/DeviceRegistryLocatorConfiguration.java @@ -29,6 +29,7 @@ import org.eclipse.kapua.commons.metric.CommonsMetric; import org.eclipse.kapua.commons.metric.MetricsService; import org.eclipse.kapua.commons.metric.MetricsServiceImpl; +import org.eclipse.kapua.commons.model.mappers.KapuaBaseMapperImpl; import org.eclipse.kapua.commons.service.event.store.internal.EventStoreRecordImplJpaRepository; import org.eclipse.kapua.commons.service.internal.cache.CacheManagerProvider; import org.eclipse.kapua.commons.service.internal.cache.KapuaCacheManager; @@ -39,7 +40,6 @@ import org.eclipse.kapua.qa.common.MockedLocator; import org.eclipse.kapua.service.account.AccountFactory; import org.eclipse.kapua.service.account.AccountService; -import org.eclipse.kapua.service.authentication.CredentialsFactory; import org.eclipse.kapua.service.authentication.mfa.MfaAuthenticator; import org.eclipse.kapua.service.authentication.shiro.mfa.MfaAuthenticatorImpl; import org.eclipse.kapua.service.authentication.shiro.setting.KapuaAuthenticationSetting; @@ -48,7 +48,6 @@ import org.eclipse.kapua.service.authorization.domain.DomainRegistryService; import org.eclipse.kapua.service.authorization.group.GroupService; import org.eclipse.kapua.service.authorization.permission.Permission; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; import org.eclipse.kapua.service.device.authentication.UserPassDeviceConnectionCredentialAdapter; import org.eclipse.kapua.service.device.authentication.api.DeviceConnectionCredentialAdapter; import org.eclipse.kapua.service.device.registry.DeviceFactory; @@ -74,8 +73,8 @@ import org.eclipse.kapua.service.device.registry.internal.DeviceImplJpaRepository; import org.eclipse.kapua.service.device.registry.internal.DeviceRegistryCacheFactory; import org.eclipse.kapua.service.device.registry.internal.DeviceRegistryServiceImpl; -import org.eclipse.kapua.service.tag.internal.TagFactoryImpl; import org.eclipse.kapua.service.tag.internal.TagImplJpaRepository; +import org.eclipse.kapua.service.tag.internal.TagMapperImpl; import org.eclipse.kapua.service.tag.internal.TagServiceImpl; import org.eclipse.kapua.storage.TxManager; import org.mockito.Matchers; @@ -117,17 +116,12 @@ protected void configure() { // Inject mocked Authorization Service method checkPermission AuthorizationService mockedAuthorization = Mockito.mock(AuthorizationService.class); - // Inject mocked Permission Factory - final PermissionFactory permissionFactory = Mockito.mock(PermissionFactory.class); - bind(PermissionFactory.class).toInstance(permissionFactory); try { Mockito.doNothing().when(mockedAuthorization).checkPermission(Matchers.any(Permission.class)); } catch (KapuaException e) { // skip } - final CredentialsFactory credentialsFactory = Mockito.mock(CredentialsFactory.class); bind(AuthorizationService.class).toInstance(mockedAuthorization); - bind(CredentialsFactory.class).toInstance(credentialsFactory); bind(KapuaJpaRepositoryConfiguration.class).toInstance(new KapuaJpaRepositoryConfiguration()); bind(AccountRelativeFinder.class).toInstance(Mockito.mock(AccountRelativeFinder.class)); bind(AccountFactory.class).toInstance(Mockito.mock(AccountFactory.class)); @@ -144,7 +138,7 @@ protected void configure() { bind(DeviceRegistryCacheFactory.class).toInstance(deviceRegistryCacheFactory); final Map availableDeviceConnectionAdapters = new HashMap<>(); - availableDeviceConnectionAdapters.put("USER_PASS", new UserPassDeviceConnectionCredentialAdapter(credentialsFactory)); + availableDeviceConnectionAdapters.put("USER_PASS", new UserPassDeviceConnectionCredentialAdapter()); final MapBinder serviceConfigurationManagerMapBinder = MapBinder.newMapBinder(binder(), Class.class, ServiceConfigurationManager.class); @@ -161,7 +155,6 @@ protected void configure() { final DeviceConnectionService deviceConnectionService = new DeviceConnectionServiceImpl( classServiceConfigurationManagerMap, mockedAuthorization, - permissionFactory, new DeviceConnectionFactoryImpl(), txManager, new DeviceConnectionImplJpaRepository(jpaRepoConfig), @@ -175,7 +168,6 @@ protected void configure() { bind(DeviceEventRepository.class).toInstance(new DeviceEventImplJpaRepository(jpaRepoConfig)); final DeviceEventService deviceEventService = new DeviceEventServiceImpl( mockedAuthorization, - permissionFactory, txManager, new DeviceImplJpaRepository(jpaRepoConfig), new DeviceEventFactoryImpl(), @@ -189,26 +181,23 @@ protected void configure() { new KapuaDeviceRegistrySettings().getInt(KapuaDeviceRegistrySettingKeys.DEVICE_LIFECYCLE_BIRTH_VAR_FIELDS_LENGTH_MAX), new KapuaDeviceRegistrySettings().getInt(KapuaDeviceRegistrySettingKeys.DEVICE_LIFECYCLE_BIRTH_EXTENDED_PROPERTIES_LENGTH_MAX), mockedAuthorization, - permissionFactory, Mockito.mock(GroupService.class), deviceConnectionService, deviceEventService, new DeviceImplJpaRepository(jpaRepoConfig), - new DeviceFactoryImpl(), new TagServiceImpl( - permissionFactory, mockedAuthorization, Mockito.mock(ServiceConfigurationManager.class), new KapuaJpaTxManagerFactory(maxInsertAttempts).create("kapua-tag"), new TagImplJpaRepository(jpaRepoConfig), - new TagFactoryImpl()) + new TagMapperImpl(new KapuaBaseMapperImpl()) + ) ); bind(DeviceValidation.class).toInstance(deviceValidation); bind(DeviceRegistryService.class).toInstance(new DeviceRegistryServiceImpl( Mockito.mock(ServiceConfigurationManager.class), mockedAuthorization, - permissionFactory, txManager, new DeviceImplJpaRepository(jpaRepoConfig), new DeviceFactoryImpl(), diff --git a/service/endpoint/api/pom.xml b/service/endpoint/api/pom.xml index eaf41a67eda..3cafd8933fb 100644 --- a/service/endpoint/api/pom.xml +++ b/service/endpoint/api/pom.xml @@ -17,7 +17,7 @@ kapua-endpoint org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT 4.0.0 diff --git a/service/endpoint/api/src/main/java/org/eclipse/kapua/service/endpoint/EndpointInfoCreator.java b/service/endpoint/api/src/main/java/org/eclipse/kapua/service/endpoint/EndpointInfoCreator.java index 127db99299b..9c6849fd060 100644 --- a/service/endpoint/api/src/main/java/org/eclipse/kapua/service/endpoint/EndpointInfoCreator.java +++ b/service/endpoint/api/src/main/java/org/eclipse/kapua/service/endpoint/EndpointInfoCreator.java @@ -12,47 +12,100 @@ *******************************************************************************/ package org.eclipse.kapua.service.endpoint; -import org.eclipse.kapua.model.KapuaEntityCreator; +import java.util.HashSet; +import java.util.Set; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; -import java.util.Set; + +import org.eclipse.kapua.model.KapuaEntityCreator; +import org.eclipse.kapua.model.id.KapuaId; /** - * {@link EndpointInfo} creator definition.
        - * It is used to create a new {@link EndpointInfo}. + * {@link EndpointInfo} creator definition.
        It is used to create a new {@link EndpointInfo}. * * @since 1.0.0 */ @XmlRootElement(name = "endpointInfoCreator") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = EndpointInfoXmlRegistry.class, factoryMethod = "newCreator") -public interface EndpointInfoCreator extends KapuaEntityCreator { - - String getSchema(); - - void setSchema(String schema); - - String getDns(); - - void setDns(String dns); - - int getPort(); - - void setPort(int port); - - boolean getSecure(); - - void setSecure(boolean secure); - - Set getUsages(); - - void setUsages(Set usages); - - String getEndpointType(); - - void setEndpointType(String endpointType); - +@XmlType +public class EndpointInfoCreator extends KapuaEntityCreator { + + private String schema; + private String dns; + private int port; + private boolean secure; + private Set usages; + private String endpointType; + + public EndpointInfoCreator() { + } + + public EndpointInfoCreator(KapuaId scopeId) { + super(scopeId); + } + + public EndpointInfoCreator(KapuaEntityCreator entityCreator) { + super(entityCreator); + } + + public String getSchema() { + return schema; + } + + public EndpointInfoCreator setSchema(String schema) { + this.schema = schema; + return this; + } + + public String getDns() { + return dns; + } + + public EndpointInfoCreator setDns(String dns) { + this.dns = dns; + return this; + } + + public int getPort() { + return port; + } + + public EndpointInfoCreator setPort(int port) { + this.port = port; + return this; + } + + public boolean getSecure() { + return secure; + } + + public EndpointInfoCreator setSecure(boolean secure) { + this.secure = secure; + return this; + } + + public Set getUsages() { + if (usages == null) { + usages = new HashSet<>(); + } + + return usages; + } + + public EndpointInfoCreator setUsages(Set usages) { + this.usages = usages; + return this; + } + + public String getEndpointType() { + return endpointType; + } + + public EndpointInfoCreator setEndpointType(String endpointType) { + this.endpointType = endpointType; + return this; + } } diff --git a/service/endpoint/api/src/main/java/org/eclipse/kapua/service/endpoint/EndpointInfoFactory.java b/service/endpoint/api/src/main/java/org/eclipse/kapua/service/endpoint/EndpointInfoFactory.java index ace01e1d96f..b649458801c 100644 --- a/service/endpoint/api/src/main/java/org/eclipse/kapua/service/endpoint/EndpointInfoFactory.java +++ b/service/endpoint/api/src/main/java/org/eclipse/kapua/service/endpoint/EndpointInfoFactory.java @@ -19,14 +19,16 @@ * * @since 1.0.0 */ -public interface EndpointInfoFactory extends KapuaEntityFactory { +public interface EndpointInfoFactory extends KapuaEntityFactory { /** * Instantiates a new {@link EndpointUsage}. * - * @param name The name to set into the {@link EndpointUsage}. + * @param name + * The name to set into the {@link EndpointUsage}. * @return The newly instantiated {@link EndpointUsage}. * @since 1.0.0 */ EndpointUsage newEndpointUsage(String name); + } diff --git a/service/endpoint/api/src/main/java/org/eclipse/kapua/service/endpoint/EndpointInfoListResult.java b/service/endpoint/api/src/main/java/org/eclipse/kapua/service/endpoint/EndpointInfoListResult.java index 642f0944762..df3f7d48953 100644 --- a/service/endpoint/api/src/main/java/org/eclipse/kapua/service/endpoint/EndpointInfoListResult.java +++ b/service/endpoint/api/src/main/java/org/eclipse/kapua/service/endpoint/EndpointInfoListResult.java @@ -12,18 +12,18 @@ *******************************************************************************/ package org.eclipse.kapua.service.endpoint; -import org.eclipse.kapua.model.query.KapuaListResult; - import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; +import org.eclipse.kapua.model.query.KapuaListResult; + /** * {@link EndpointInfo} list result definition. * * @since 1.0.0 */ @XmlRootElement(name = "endpointInfos") -@XmlType(factoryClass = EndpointInfoXmlRegistry.class, factoryMethod = "newListResult") -public interface EndpointInfoListResult extends KapuaListResult { +@XmlType +public class EndpointInfoListResult extends KapuaListResult { } diff --git a/service/endpoint/api/src/main/java/org/eclipse/kapua/service/endpoint/EndpointInfoMatchPredicate.java b/service/endpoint/api/src/main/java/org/eclipse/kapua/service/endpoint/EndpointInfoMatchPredicate.java index 1f7a40b870e..dd656701d7e 100644 --- a/service/endpoint/api/src/main/java/org/eclipse/kapua/service/endpoint/EndpointInfoMatchPredicate.java +++ b/service/endpoint/api/src/main/java/org/eclipse/kapua/service/endpoint/EndpointInfoMatchPredicate.java @@ -12,8 +12,23 @@ *******************************************************************************/ package org.eclipse.kapua.service.endpoint; -import org.eclipse.kapua.model.query.predicate.MatchPredicate; +import java.util.Arrays; -public interface EndpointInfoMatchPredicate extends MatchPredicate { +import org.eclipse.kapua.model.query.predicate.AbstractMatchPredicate; +public class EndpointInfoMatchPredicate extends AbstractMatchPredicate { + + /** + * Constructor. + * + * @param matchTerm + * @since 2.1.0 + */ + public EndpointInfoMatchPredicate(T matchTerm) { + this.attributeNames = Arrays.asList( + EndpointInfoAttributes.SCHEMA, + EndpointInfoAttributes.DNS + ); + this.matchTerm = matchTerm; + } } diff --git a/service/endpoint/api/src/main/java/org/eclipse/kapua/service/endpoint/EndpointInfoQuery.java b/service/endpoint/api/src/main/java/org/eclipse/kapua/service/endpoint/EndpointInfoQuery.java index 8e0fcf05e6d..f73e40c292d 100644 --- a/service/endpoint/api/src/main/java/org/eclipse/kapua/service/endpoint/EndpointInfoQuery.java +++ b/service/endpoint/api/src/main/java/org/eclipse/kapua/service/endpoint/EndpointInfoQuery.java @@ -12,13 +12,14 @@ *******************************************************************************/ package org.eclipse.kapua.service.endpoint; -import org.eclipse.kapua.model.query.KapuaQuery; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; +import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.query.KapuaQuery; + /** * {@link EndpointInfo} {@link KapuaQuery} definition. * @@ -27,15 +28,34 @@ */ @XmlRootElement(name = "query") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = EndpointInfoXmlRegistry.class, factoryMethod = "newQuery") -public interface EndpointInfoQuery extends KapuaQuery { +@XmlType +public class EndpointInfoQuery extends KapuaQuery { + + public EndpointInfoQuery() { + } + + /** + * Constructor. + * + * @param scopeId + * The {@link #getScopeId()}. + * @since 1.0.0 + */ + public EndpointInfoQuery(KapuaId scopeId) { + super(scopeId); + } + /** * Instantiates a new {@link EndpointInfoMatchPredicate}. * - * @param matchTerm The term to use to match. - * @param The type of the term + * @param matchTerm + * The term to use to match. + * @param + * The type of the term * @return The newly instantiated {@link EndpointInfoMatchPredicate}. * @since 2.1.0 */ - EndpointInfoMatchPredicate matchPredicate(T matchTerm); + public EndpointInfoMatchPredicate matchPredicate(T matchTerm) { + return new EndpointInfoMatchPredicate<>(matchTerm); + } } diff --git a/service/endpoint/api/src/main/java/org/eclipse/kapua/service/endpoint/EndpointInfoXmlRegistry.java b/service/endpoint/api/src/main/java/org/eclipse/kapua/service/endpoint/EndpointInfoXmlRegistry.java index 334e2f8380f..6a862d1fad3 100644 --- a/service/endpoint/api/src/main/java/org/eclipse/kapua/service/endpoint/EndpointInfoXmlRegistry.java +++ b/service/endpoint/api/src/main/java/org/eclipse/kapua/service/endpoint/EndpointInfoXmlRegistry.java @@ -12,10 +12,10 @@ *******************************************************************************/ package org.eclipse.kapua.service.endpoint; -import org.eclipse.kapua.locator.KapuaLocator; - import javax.xml.bind.annotation.XmlRegistry; +import org.eclipse.kapua.locator.KapuaLocator; + @XmlRegistry public class EndpointInfoXmlRegistry { @@ -30,33 +30,6 @@ public EndpointInfo newEntity() { return endpointInfoFactory.newEntity(null); } - /** - * Creates a new {@link EndpointInfoCreator} instance - * - * @return - */ - public EndpointInfoCreator newCreator() { - return endpointInfoFactory.newCreator(null); - } - - /** - * Creates a new {@link EndpointInfoListResult} - * - * @return - */ - public EndpointInfoListResult newListResult() { - return endpointInfoFactory.newListResult(); - } - - /** - * Creates a new {@link EndpointInfoQuery} - * - * @return - */ - public EndpointInfoQuery newQuery() { - return endpointInfoFactory.newQuery(null); - } - public EndpointUsage newEndpointUsage() { return endpointInfoFactory.newEndpointUsage(null); } diff --git a/service/endpoint/internal/pom.xml b/service/endpoint/internal/pom.xml index 4e8ec80cb14..61ee508e6ea 100644 --- a/service/endpoint/internal/pom.xml +++ b/service/endpoint/internal/pom.xml @@ -19,7 +19,7 @@ kapua-endpoint org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-endpoint-internal diff --git a/service/endpoint/internal/src/main/java/org/eclipse/kapua/service/endpoint/internal/EndpointInfoCreatorImpl.java b/service/endpoint/internal/src/main/java/org/eclipse/kapua/service/endpoint/internal/EndpointInfoCreatorImpl.java deleted file mode 100644 index 6d52e0ca1c8..00000000000 --- a/service/endpoint/internal/src/main/java/org/eclipse/kapua/service/endpoint/internal/EndpointInfoCreatorImpl.java +++ /dev/null @@ -1,106 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2017, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.endpoint.internal; - -import org.eclipse.kapua.commons.model.AbstractKapuaEntityCreator; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.endpoint.EndpointInfo; -import org.eclipse.kapua.service.endpoint.EndpointInfoCreator; -import org.eclipse.kapua.service.endpoint.EndpointUsage; - -import java.util.HashSet; -import java.util.Set; - -/** - * {@link EndpointInfoCreator} implementation. - * - * @since 1.0.0 - */ -public class EndpointInfoCreatorImpl extends AbstractKapuaEntityCreator implements EndpointInfoCreator { - - private String schema; - private String dns; - private int port; - private boolean secure; - private Set usages; - private String endpointType; - - protected EndpointInfoCreatorImpl(KapuaId scopeId) { - super(scopeId); - } - - @Override - public String getSchema() { - return schema; - } - - @Override - public void setSchema(String schema) { - this.schema = schema; - } - - @Override - public String getDns() { - return dns; - } - - @Override - public void setDns(String dns) { - this.dns = dns; - } - - @Override - public int getPort() { - return port; - } - - @Override - public void setPort(int port) { - this.port = port; - } - - @Override - public boolean getSecure() { - return secure; - } - - @Override - public void setSecure(boolean secure) { - this.secure = secure; - } - - @Override - public Set getUsages() { - if (usages == null) { - usages = new HashSet<>(); - } - - return usages; - } - - @Override - public void setUsages(Set usages) { - this.usages = usages; - } - - @Override - public String getEndpointType() { - return endpointType; - } - - @Override - public void setEndpointType(String endpointType) { - this.endpointType = endpointType; - } - -} diff --git a/service/endpoint/internal/src/main/java/org/eclipse/kapua/service/endpoint/internal/EndpointInfoFactoryImpl.java b/service/endpoint/internal/src/main/java/org/eclipse/kapua/service/endpoint/internal/EndpointInfoFactoryImpl.java index 0bfdb553646..a3c32097005 100644 --- a/service/endpoint/internal/src/main/java/org/eclipse/kapua/service/endpoint/internal/EndpointInfoFactoryImpl.java +++ b/service/endpoint/internal/src/main/java/org/eclipse/kapua/service/endpoint/internal/EndpointInfoFactoryImpl.java @@ -12,17 +12,14 @@ *******************************************************************************/ package org.eclipse.kapua.service.endpoint.internal; +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaEntityCloneException; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.endpoint.EndpointInfo; -import org.eclipse.kapua.service.endpoint.EndpointInfoCreator; import org.eclipse.kapua.service.endpoint.EndpointInfoFactory; -import org.eclipse.kapua.service.endpoint.EndpointInfoListResult; -import org.eclipse.kapua.service.endpoint.EndpointInfoQuery; import org.eclipse.kapua.service.endpoint.EndpointUsage; -import javax.inject.Singleton; - /** * {@link EndpointInfoFactory} implementation. * @@ -36,21 +33,6 @@ public EndpointInfo newEntity(KapuaId scopeId) { return new EndpointInfoImpl(scopeId); } - @Override - public EndpointInfoListResult newListResult() { - return new EndpointInfoListResultImpl(); - } - - @Override - public EndpointInfoQuery newQuery(KapuaId scopeId) { - return new EndpointInfoQueryImpl(scopeId); - } - - @Override - public EndpointInfoCreator newCreator(KapuaId scopeId) { - return new EndpointInfoCreatorImpl(scopeId); - } - @Override public EndpointUsage newEndpointUsage(String name) { return new EndpointUsageImpl(name); diff --git a/service/endpoint/internal/src/main/java/org/eclipse/kapua/service/endpoint/internal/EndpointInfoImplJpaRepository.java b/service/endpoint/internal/src/main/java/org/eclipse/kapua/service/endpoint/internal/EndpointInfoImplJpaRepository.java index 3f9034dd861..2d83e376a1e 100644 --- a/service/endpoint/internal/src/main/java/org/eclipse/kapua/service/endpoint/internal/EndpointInfoImplJpaRepository.java +++ b/service/endpoint/internal/src/main/java/org/eclipse/kapua/service/endpoint/internal/EndpointInfoImplJpaRepository.java @@ -21,7 +21,8 @@ public class EndpointInfoImplJpaRepository extends KapuaUpdatableEntityJpaRepository implements EndpointInfoRepository { + public EndpointInfoImplJpaRepository(KapuaJpaRepositoryConfiguration jpaRepoConfig) { - super(EndpointInfoImpl.class, EndpointInfo.TYPE, () -> new EndpointInfoListResultImpl(), jpaRepoConfig); + super(EndpointInfoImpl.class, EndpointInfo.TYPE, () -> new EndpointInfoListResult(), jpaRepoConfig); } } diff --git a/service/endpoint/internal/src/main/java/org/eclipse/kapua/service/endpoint/internal/EndpointInfoListResultImpl.java b/service/endpoint/internal/src/main/java/org/eclipse/kapua/service/endpoint/internal/EndpointInfoListResultImpl.java deleted file mode 100644 index 36b624f5730..00000000000 --- a/service/endpoint/internal/src/main/java/org/eclipse/kapua/service/endpoint/internal/EndpointInfoListResultImpl.java +++ /dev/null @@ -1,26 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2017, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.endpoint.internal; - -import org.eclipse.kapua.commons.model.query.KapuaListResultImpl; -import org.eclipse.kapua.service.endpoint.EndpointInfo; -import org.eclipse.kapua.service.endpoint.EndpointInfoListResult; - -/** - * {@link EndpointInfoListResult} implementation. - * - * @since 1.0.0 - */ -public class EndpointInfoListResultImpl extends KapuaListResultImpl implements EndpointInfoListResult { - -} diff --git a/service/endpoint/internal/src/main/java/org/eclipse/kapua/service/endpoint/internal/EndpointInfoMatchPredicateImpl.java b/service/endpoint/internal/src/main/java/org/eclipse/kapua/service/endpoint/internal/EndpointInfoMatchPredicateImpl.java deleted file mode 100644 index f239431346f..00000000000 --- a/service/endpoint/internal/src/main/java/org/eclipse/kapua/service/endpoint/internal/EndpointInfoMatchPredicateImpl.java +++ /dev/null @@ -1,37 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2017, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.endpoint.internal; - -import org.eclipse.kapua.commons.model.query.predicate.AbstractMatchPredicate; -import org.eclipse.kapua.service.endpoint.EndpointInfoAttributes; -import org.eclipse.kapua.service.endpoint.EndpointInfoMatchPredicate; - -import java.util.Arrays; - -public class EndpointInfoMatchPredicateImpl extends AbstractMatchPredicate implements EndpointInfoMatchPredicate { - - /** - * Constructor. - * - * @param matchTerm - * @since 2.1.0 - */ - public EndpointInfoMatchPredicateImpl(T matchTerm) { - this.attributeNames = Arrays.asList( - EndpointInfoAttributes.SCHEMA, - EndpointInfoAttributes.DNS - ); - this.matchTerm = matchTerm; - } - -} diff --git a/service/endpoint/internal/src/main/java/org/eclipse/kapua/service/endpoint/internal/EndpointInfoQueryImpl.java b/service/endpoint/internal/src/main/java/org/eclipse/kapua/service/endpoint/internal/EndpointInfoQueryImpl.java deleted file mode 100644 index 7ceed548388..00000000000 --- a/service/endpoint/internal/src/main/java/org/eclipse/kapua/service/endpoint/internal/EndpointInfoQueryImpl.java +++ /dev/null @@ -1,41 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2017, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.endpoint.internal; - -import org.eclipse.kapua.commons.model.query.AbstractKapuaQuery; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.endpoint.EndpointInfoMatchPredicate; -import org.eclipse.kapua.service.endpoint.EndpointInfoQuery; - -/** - * {@link EndpointInfoQuery} implementation. - * - * @since 1.0.0 - */ -public class EndpointInfoQueryImpl extends AbstractKapuaQuery implements EndpointInfoQuery { - - /** - * Constructor. - * - * @param scopeId The {@link #getScopeId()}. - * @since 1.0.0 - */ - public EndpointInfoQueryImpl(KapuaId scopeId) { - super(scopeId); - } - - @Override - public EndpointInfoMatchPredicate matchPredicate(T matchTerm) { - return new EndpointInfoMatchPredicateImpl<>(matchTerm); - } -} diff --git a/service/endpoint/internal/src/main/java/org/eclipse/kapua/service/endpoint/internal/EndpointInfoServiceImpl.java b/service/endpoint/internal/src/main/java/org/eclipse/kapua/service/endpoint/internal/EndpointInfoServiceImpl.java index 11a4a8bc75a..fa1b086525d 100644 --- a/service/endpoint/internal/src/main/java/org/eclipse/kapua/service/endpoint/internal/EndpointInfoServiceImpl.java +++ b/service/endpoint/internal/src/main/java/org/eclipse/kapua/service/endpoint/internal/EndpointInfoServiceImpl.java @@ -12,6 +12,15 @@ *******************************************************************************/ package org.eclipse.kapua.service.endpoint.internal; +import java.util.AbstractMap; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.function.Predicate; + +import javax.inject.Inject; +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaEntityNotFoundException; import org.eclipse.kapua.KapuaEntityUniquenessException; import org.eclipse.kapua.KapuaException; @@ -29,11 +38,10 @@ import org.eclipse.kapua.service.account.Account; import org.eclipse.kapua.service.account.AccountService; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; +import org.eclipse.kapua.service.authorization.permission.Permission; import org.eclipse.kapua.service.endpoint.EndpointInfo; import org.eclipse.kapua.service.endpoint.EndpointInfoAttributes; import org.eclipse.kapua.service.endpoint.EndpointInfoCreator; -import org.eclipse.kapua.service.endpoint.EndpointInfoFactory; import org.eclipse.kapua.service.endpoint.EndpointInfoListResult; import org.eclipse.kapua.service.endpoint.EndpointInfoQuery; import org.eclipse.kapua.service.endpoint.EndpointInfoRepository; @@ -41,14 +49,6 @@ import org.eclipse.kapua.storage.TxContext; import org.eclipse.kapua.storage.TxManager; -import javax.inject.Inject; -import javax.inject.Singleton; -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.function.Predicate; - /** * {@link EndpointInfoService} implementation. * @@ -57,9 +57,8 @@ @Singleton public class EndpointInfoServiceImpl implements EndpointInfoService { + private final AuthorizationService authorizationService; - private final PermissionFactory permissionFactory; - private final EndpointInfoFactory endpointInfoFactory; private final EndpointInfoRepository repository; private final AccountService accountService; private final TxManager txManager; @@ -68,14 +67,10 @@ public class EndpointInfoServiceImpl public EndpointInfoServiceImpl( AccountService accountService, AuthorizationService authorizationService, - PermissionFactory permissionFactory, - EndpointInfoFactory endpointInfoFactory, EndpointInfoRepository endpointInfoRepository, TxManager txManager) { this.accountService = accountService; this.authorizationService = authorizationService; - this.permissionFactory = permissionFactory; - this.endpointInfoFactory = endpointInfoFactory; this.repository = endpointInfoRepository; this.txManager = txManager; } @@ -106,7 +101,7 @@ public EndpointInfo create(EndpointInfoCreator endpointInfoCreator) KapuaId scopeIdPermission = endpointInfoCreator.getEndpointType().equals(EndpointInfo.ENDPOINT_TYPE_CORS) ? endpointInfoCreator.getScopeId() : null; authorizationService.checkPermission( - permissionFactory.newPermission(Domains.ENDPOINT_INFO, Actions.write, scopeIdPermission) + new Permission(Domains.ENDPOINT_INFO, Actions.write, scopeIdPermission) ); // Check duplicate endpoint checkDuplicateEndpointInfo( @@ -148,7 +143,7 @@ public EndpointInfo update(EndpointInfo endpointInfo) throws KapuaException { KapuaId scopeIdPermission = endpointInfo.getEndpointType().equals(EndpointInfo.ENDPOINT_TYPE_CORS) ? endpointInfo.getScopeId() : null; authorizationService.checkPermission( - permissionFactory.newPermission(Domains.ENDPOINT_INFO, Actions.write, scopeIdPermission) + new Permission(Domains.ENDPOINT_INFO, Actions.write, scopeIdPermission) ); // Check duplicate endpoint checkDuplicateEndpointInfo( @@ -178,7 +173,7 @@ public void delete(KapuaId scopeId, KapuaId endpointInfoId) throws KapuaExceptio } authorizationService.checkPermission( - permissionFactory.newPermission(Domains.ENDPOINT_INFO, Actions.delete, scopeIdPermission) + new Permission(Domains.ENDPOINT_INFO, Actions.delete, scopeIdPermission) ); // Do delete return repository.delete(tx, scopeId, endpointInfoId); @@ -193,7 +188,7 @@ public EndpointInfo find(KapuaId scopeId, KapuaId endpointInfoId) // Check Access return txManager.execute(tx -> { authorizationService.checkPermission( - permissionFactory.newPermission(Domains.ENDPOINT_INFO, Actions.read, scopeId) + new Permission(Domains.ENDPOINT_INFO, Actions.read, scopeId) ); EndpointInfo endpointInfoToFind = repository.find(tx, KapuaId.ANY, endpointInfoId) .orElseThrow(() -> new KapuaEntityNotFoundException(EndpointInfo.TYPE, endpointInfoId)); // search the endpoint in any scope @@ -204,10 +199,11 @@ public EndpointInfo find(KapuaId scopeId, KapuaId endpointInfoId) //found but in another scope...is defined in the scope of the first Account that has defined endpoints? (proceeding upwards) String type = endpointInfoToFind.getEndpointType(); //now find the endpoints of the search type that I can use (aka, the nearest proceeding upwards in Accounts hierarchy) - EndpointInfoQuery query = endpointInfoFactory.newQuery(scopeId); + EndpointInfoQuery query = new EndpointInfoQuery(scopeId); EndpointInfoListResult nearestUsableEndpoints = doQuery(tx, query, type); - if (nearestUsableEndpoints.isEmpty() || !nearestUsableEndpoints.getFirstItem().getScopeId().equals(endpointInfoToFind.getScopeId())) { //the second condition is equivalent to verify if the searched endpoint is in this list + if (nearestUsableEndpoints.isEmpty() || !nearestUsableEndpoints.getFirstItem().getScopeId() + .equals(endpointInfoToFind.getScopeId())) { //the second condition is equivalent to verify if the searched endpoint is in this list throw new KapuaEntityNotFoundException(EndpointInfo.TYPE, endpointInfoId); } else { return endpointInfoToFind; @@ -230,7 +226,7 @@ private Long doCount(TxContext txContext, KapuaQuery query, String section) thro ArgumentValidator.notNull(query, "query"); // Check Access authorizationService.checkPermission( - permissionFactory.newPermission(Domains.ENDPOINT_INFO, Actions.read, query.getScopeId()) + new Permission(Domains.ENDPOINT_INFO, Actions.read, query.getScopeId()) ); return traverse( txContext, @@ -255,7 +251,7 @@ private EndpointInfoListResult doQuery(TxContext tx, KapuaQuery query, String se // // Check Access authorizationService.checkPermission( - permissionFactory.newPermission(Domains.ENDPOINT_INFO, Actions.read, query.getScopeId()) + new Permission(Domains.ENDPOINT_INFO, Actions.read, query.getScopeId()) ); return traverse( tx, @@ -266,7 +262,6 @@ private EndpointInfoListResult doQuery(TxContext tx, KapuaQuery query, String se ); } - // // Private methods and interfaces // @@ -275,19 +270,23 @@ private EndpointInfoListResult doQuery(TxContext tx, KapuaQuery query, String se //to overcome this, I created this interface which is a custom form of a Bifunction throwing the checked KapuaException @FunctionalInterface public interface kapuaBiFunction { + R apply(A input1, B input2) throws KapuaException; } - /** - * Traverse the account hierarchy bottom-up to search for {@link EndpointInfo} respecting the given query, - * performing for each layer the given queryExecutor until the given isEmptyResult dictates to stop OR when endpoints of the same section are found in one layer - * In other terms, this method applies a given function to the "nearest usable endpoints", aka the ones that I see in a given scopeID + * Traverse the account hierarchy bottom-up to search for {@link EndpointInfo} respecting the given query, performing for each layer the given queryExecutor until the given isEmptyResult dictates + * to stop OR when endpoints of the same section are found in one layer In other terms, this method applies a given function to the "nearest usable endpoints", aka the ones that I see in a given + * scopeID * - * @param query The query to filter the {@link EndpointInfo}s. - * @param section section of {@link EndpointInfo} where we want to search the information - * @param queryExecutor function to apply at each layer - * @param isEmptyResult predicate that dictates to stop the traversal when false + * @param query + * The query to filter the {@link EndpointInfo}s. + * @param section + * section of {@link EndpointInfo} where we want to search the information + * @param queryExecutor + * function to apply at each layer + * @param isEmptyResult + * predicate that dictates to stop the traversal when false */ protected R traverse( TxContext tx, @@ -337,18 +336,25 @@ protected R traverse( /** * Checks whether another {@link EndpointInfo} already exists with the given values. * - * @param scopeId The ScopeId of the {@link EndpointInfo} - * @param entityId The entity id, if exists. On update you need to exclude the same entity. - * @param schema The {@link EndpointInfo#getSchema()} value. - * @param dns The {@link EndpointInfo#getDns()} value. - * @param port The {@link EndpointInfo#getPort()} value. - * @param type The {@link EndpointInfo#getEndpointType()} value. - * @throws KapuaException if the values provided matches another {@link EndpointInfo} + * @param scopeId + * The ScopeId of the {@link EndpointInfo} + * @param entityId + * The entity id, if exists. On update you need to exclude the same entity. + * @param schema + * The {@link EndpointInfo#getSchema()} value. + * @param dns + * The {@link EndpointInfo#getDns()} value. + * @param port + * The {@link EndpointInfo#getPort()} value. + * @param type + * The {@link EndpointInfo#getEndpointType()} value. + * @throws KapuaException + * if the values provided matches another {@link EndpointInfo} * @since 1.0.0 */ private void checkDuplicateEndpointInfo(KapuaId scopeId, KapuaId entityId, String schema, String dns, int port, String type) throws KapuaException { - EndpointInfoQuery query = new EndpointInfoQueryImpl(scopeId); + EndpointInfoQuery query = new EndpointInfoQuery(scopeId); AndPredicate andPredicate = query.andPredicate( query.attributePredicate(EndpointInfoAttributes.SCHEMA, schema), @@ -375,7 +381,7 @@ private void checkDuplicateEndpointInfo(KapuaId scopeId, KapuaId entityId, Strin } private boolean countAllEndpointsInScope(TxContext txContext, KapuaId scopeId, String section) throws KapuaException { - EndpointInfoQuery totalQuery = endpointInfoFactory.newQuery(scopeId); + EndpointInfoQuery totalQuery = new EndpointInfoQuery(scopeId); addSectionToPredicate(totalQuery, section); long totalCount = repository.count(txContext, totalQuery); return totalCount != 0; diff --git a/service/endpoint/internal/src/main/java/org/eclipse/kapua/service/endpoint/internal/EndpointModule.java b/service/endpoint/internal/src/main/java/org/eclipse/kapua/service/endpoint/internal/EndpointModule.java index b4d2fac80db..e6a9c925be1 100644 --- a/service/endpoint/internal/src/main/java/org/eclipse/kapua/service/endpoint/internal/EndpointModule.java +++ b/service/endpoint/internal/src/main/java/org/eclipse/kapua/service/endpoint/internal/EndpointModule.java @@ -12,9 +12,6 @@ *******************************************************************************/ package org.eclipse.kapua.service.endpoint.internal; -import com.google.inject.Provides; -import com.google.inject.Singleton; -import com.google.inject.multibindings.ProvidesIntoSet; import org.eclipse.kapua.commons.core.AbstractKapuaModule; import org.eclipse.kapua.commons.jpa.KapuaJpaRepositoryConfiguration; import org.eclipse.kapua.commons.jpa.KapuaJpaTxManagerFactory; @@ -24,12 +21,16 @@ import org.eclipse.kapua.model.domain.DomainEntry; import org.eclipse.kapua.service.account.AccountService; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; import org.eclipse.kapua.service.endpoint.EndpointInfoFactory; import org.eclipse.kapua.service.endpoint.EndpointInfoRepository; import org.eclipse.kapua.service.endpoint.EndpointInfoService; +import com.google.inject.Provides; +import com.google.inject.Singleton; +import com.google.inject.multibindings.ProvidesIntoSet; + public class EndpointModule extends AbstractKapuaModule { + @Override protected void configureModule() { bind(EndpointInfoFactory.class).to(EndpointInfoFactoryImpl.class); @@ -39,16 +40,12 @@ protected void configureModule() { @Singleton EndpointInfoService endpointInfoService( AuthorizationService authorizationService, - PermissionFactory permissionFactory, - EndpointInfoFactory endpointInfoFactory, AccountService accountService, EndpointInfoRepository endpointInfoRepository, KapuaJpaTxManagerFactory jpaTxManagerFactory) { return new EndpointInfoServiceImpl( accountService, authorizationService, - permissionFactory, - endpointInfoFactory, endpointInfoRepository, jpaTxManagerFactory.create("kapua-endpoint")); } diff --git a/service/endpoint/pom.xml b/service/endpoint/pom.xml index 7c481c805c5..b823a49e110 100644 --- a/service/endpoint/pom.xml +++ b/service/endpoint/pom.xml @@ -19,7 +19,7 @@ kapua-service org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT pom diff --git a/service/endpoint/test-steps/pom.xml b/service/endpoint/test-steps/pom.xml index eb0158d80cf..d21bd706916 100644 --- a/service/endpoint/test-steps/pom.xml +++ b/service/endpoint/test-steps/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-endpoint - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-endpoint-test-steps diff --git a/service/endpoint/test-steps/src/main/java/org/eclipse/kapua/service/endpoint/steps/EndpointServiceSteps.java b/service/endpoint/test-steps/src/main/java/org/eclipse/kapua/service/endpoint/steps/EndpointServiceSteps.java index 447ae1695e1..35bc1474d2b 100644 --- a/service/endpoint/test-steps/src/main/java/org/eclipse/kapua/service/endpoint/steps/EndpointServiceSteps.java +++ b/service/endpoint/test-steps/src/main/java/org/eclipse/kapua/service/endpoint/steps/EndpointServiceSteps.java @@ -12,15 +12,11 @@ *******************************************************************************/ package org.eclipse.kapua.service.endpoint.steps; +import java.util.List; +import java.util.concurrent.Callable; + +import javax.inject.Inject; -import com.google.inject.Singleton; -import io.cucumber.datatable.DataTable; -import io.cucumber.java.After; -import io.cucumber.java.Before; -import io.cucumber.java.Scenario; -import io.cucumber.java.en.And; -import io.cucumber.java.en.Then; -import io.cucumber.java.en.When; import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.KapuaIllegalNullArgumentException; import org.eclipse.kapua.commons.security.KapuaSecurityUtils; @@ -38,9 +34,15 @@ import org.eclipse.kapua.service.endpoint.EndpointInfoService; import org.junit.Assert; -import javax.inject.Inject; -import java.util.List; -import java.util.concurrent.Callable; +import com.google.inject.Singleton; + +import io.cucumber.datatable.DataTable; +import io.cucumber.java.After; +import io.cucumber.java.Before; +import io.cucumber.java.Scenario; +import io.cucumber.java.en.And; +import io.cucumber.java.en.Then; +import io.cucumber.java.en.When; @Singleton public class EndpointServiceSteps extends TestBase { @@ -48,13 +50,13 @@ public class EndpointServiceSteps extends TestBase { private EndpointInfoService endpointInfoService; private EndpointInfoFactory endpointInfoFactory; -// **************************************************************************************** -// * Implementation of Gherkin steps used in JobService.feature scenarios. * -// * * -// * MockedLocator is used for Location Service. Mockito is used to mock other * -// * services that the Account services dependent on. Dependent services are: * -// * - Authorization Service * -// **************************************************************************************** + // **************************************************************************************** + // * Implementation of Gherkin steps used in JobService.feature scenarios. * + // * * + // * MockedLocator is used for Location Service. Mockito is used to mock other * + // * services that the Account services dependent on. Dependent services are: * + // * - Authorization Service * + // **************************************************************************************** private static final String ENDPOINT_INFO = "EndpointInfo"; @@ -64,7 +66,7 @@ public EndpointServiceSteps(StepData stepData) { super(stepData); } - @After(value="@setup") + @After(value = "@setup") public void setServices() { KapuaLocator locator = KapuaLocator.getInstance(); endpointInfoService = locator.getService(EndpointInfoService.class); @@ -81,7 +83,7 @@ public void setServices() { // * Setup and tear-down steps * // ************************************************************************************ - @Before(value="@env_docker or @env_docker_base or @env_none", order=10) + @Before(value = "@env_docker or @env_docker_base or @env_none", order = 10) public void beforeScenarioNone(Scenario scenario) { updateScenario(scenario); } @@ -92,7 +94,7 @@ public void beforeScenarioNone(Scenario scenario) { @And("I create endpoint with schema {string}, domain {string} and port {int}") public void iCreateEndpointWithSchemaDnsAndPort(String schema, String dns, int port) throws Exception { - EndpointInfoCreator endpointInfoCreator = endpointInfoFactory.newCreator(getCurrentScopeId()); + EndpointInfoCreator endpointInfoCreator = new EndpointInfoCreator(getCurrentScopeId()); endpointInfoCreator.setSchema(schema); endpointInfoCreator.setDns(dns); endpointInfoCreator.setPort(port); @@ -115,7 +117,7 @@ public void iTryToCreateInvalidEndpoint() throws Exception { "æÒ\uF8FFÔÓÌÏÎÍÅ«" + "◊ш¯Èˇ¿"; for (int i = 0; i < invalidSymbols.length(); i++) { - EndpointInfoCreator endpointInfoCreator = endpointInfoFactory.newCreator(getCurrentScopeId()); + EndpointInfoCreator endpointInfoCreator = new EndpointInfoCreator(getCurrentScopeId()); String schema = invalidSymbols + invalidSymbols.charAt(i); endpointInfoCreator.setSchema(schema); endpointInfoCreator.setDns("dns.com"); @@ -133,7 +135,7 @@ public void iTryToCreateInvalidEndpoint() throws Exception { @And("I create endpoint with domain name {string} and port {int} without schema") public void iCreateEndpointWithDnsAndPort(String dns, int port) throws Exception { - EndpointInfoCreator endpointInfoCreator = endpointInfoFactory.newCreator(getCurrentScopeId()); + EndpointInfoCreator endpointInfoCreator = new EndpointInfoCreator(getCurrentScopeId()); endpointInfoCreator.setDns(dns); endpointInfoCreator.setPort(port); endpointInfoCreator.setEndpointType(EndpointInfo.ENDPOINT_TYPE_RESOURCE); @@ -147,7 +149,7 @@ public void iCreateEndpointWithDnsAndPort(String dns, int port) throws Exception @And("I create endpoint with schema {string} without domain name and port") public void iCreateEndpointWithSchemaOnly(String schema) throws Exception { - EndpointInfoCreator endpointInfoCreator = endpointInfoFactory.newCreator(getCurrentScopeId()); + EndpointInfoCreator endpointInfoCreator = new EndpointInfoCreator(getCurrentScopeId()); endpointInfoCreator.setSchema(schema); endpointInfoCreator.setEndpointType(EndpointInfo.ENDPOINT_TYPE_RESOURCE); try { @@ -160,7 +162,7 @@ public void iCreateEndpointWithSchemaOnly(String schema) throws Exception { @And("I create endpoint with NULL parameters") public void iCreateEndpointWithNullParameters() throws Exception { - EndpointInfoCreator endpointInfoCreator = endpointInfoFactory.newCreator(getCurrentScopeId()); + EndpointInfoCreator endpointInfoCreator = new EndpointInfoCreator(getCurrentScopeId()); endpointInfoCreator.setSchema(null); endpointInfoCreator.setDns(null); endpointInfoCreator.setPort(0); @@ -177,7 +179,7 @@ public void iCreateEndpointWithNullParameters() throws Exception { public void iDeleteEndpointWithSchema(String schema, String domain, int port) throws Throwable { primeException(); try { - EndpointInfoQuery endpointInfoQuery = endpointInfoFactory.newQuery(getCurrentScopeId()); + EndpointInfoQuery endpointInfoQuery = new EndpointInfoQuery(getCurrentScopeId()); endpointInfoQuery.setPredicate(endpointInfoQuery.attributePredicate(EndpointInfoAttributes.SCHEMA, schema, AttributePredicate.Operator.EQUAL)); EndpointInfo endpointInfo = endpointInfoService.query(endpointInfoQuery).getFirstItem(); Assert.assertEquals(schema, endpointInfo.getSchema()); @@ -203,7 +205,7 @@ public void foundEndpointBySchema(String schema) throws Exception { public void foundEndpointBySchemaDomainPortSection(String schema, String domain, int port, String section) throws Exception { primeException(); try { - EndpointInfoQuery endpointInfoQuery = endpointInfoFactory.newQuery(getCurrentScopeId()); + EndpointInfoQuery endpointInfoQuery = new EndpointInfoQuery(getCurrentScopeId()); AndPredicate andPredicate = endpointInfoQuery.andPredicate(); if (section.equals("cors")) { @@ -263,7 +265,7 @@ public void editEndpointSchema(String schema) throws Exception { public void iDeleteEndpointWithSchema(String schema) throws Exception { primeException(); try { - EndpointInfoQuery endpointInfoQuery = endpointInfoFactory.newQuery(getCurrentScopeId()); + EndpointInfoQuery endpointInfoQuery = new EndpointInfoQuery(getCurrentScopeId()); endpointInfoQuery.setPredicate(endpointInfoQuery.attributePredicate(EndpointInfoAttributes.SCHEMA, schema, AttributePredicate.Operator.EQUAL)); EndpointInfo endpointInfo = endpointInfoService.query(endpointInfoQuery).getFirstItem(); endpointInfoService.delete(SYS_SCOPE_ID, endpointInfo.getId()); @@ -286,7 +288,7 @@ public void iDeleteTheLastCreatedEndpoint() throws Exception { public void iDeleteEndpointWithSchemaDomainAndPort(String schema, String domainName, int port) throws Exception { primeException(); try { - EndpointInfoQuery endpointInfoQuery = endpointInfoFactory.newQuery(getCurrentScopeId()); + EndpointInfoQuery endpointInfoQuery = new EndpointInfoQuery(getCurrentScopeId()); endpointInfoQuery.setPredicate(endpointInfoQuery.attributePredicate(EndpointInfoAttributes.SCHEMA, schema, AttributePredicate.Operator.EQUAL)); endpointInfoQuery.setPredicate(endpointInfoQuery.attributePredicate(EndpointInfoAttributes.DNS, domainName, AttributePredicate.Operator.EQUAL)); endpointInfoQuery.setPredicate(endpointInfoQuery.attributePredicate(EndpointInfoAttributes.PORT, port, AttributePredicate.Operator.EQUAL)); @@ -302,7 +304,7 @@ public void iDeleteEndpointWithSchemaDomainAndPort(String schema, String domainN public void iSearchForAllEndpoints() throws Exception { primeException(); try { - EndpointInfoQuery endpointInfoQuery = endpointInfoFactory.newQuery(getCurrentScopeId()); + EndpointInfoQuery endpointInfoQuery = new EndpointInfoQuery(getCurrentScopeId()); EndpointInfoListResult endpointInfo = endpointInfoService.query(endpointInfoQuery); stepData.put("NumberOfEndpoints", endpointInfo.getSize()); } catch (Exception ex) { @@ -340,7 +342,7 @@ public void notFoundEndpointWithSchema(String endpointSchema) { public void iDeleteEndpointsWithSchema(String schema) throws Throwable { primeException(); try { - EndpointInfoQuery endpointInfoQuery = endpointInfoFactory.newQuery(getCurrentScopeId()); + EndpointInfoQuery endpointInfoQuery = new EndpointInfoQuery(getCurrentScopeId()); endpointInfoQuery.setPredicate(endpointInfoQuery.attributePredicate(EndpointInfoAttributes.SCHEMA, schema, AttributePredicate.Operator.EQUAL)); EndpointInfoListResult endpointsToDelete = endpointInfoService.query(endpointInfoQuery); for (int i = 0; i < endpointsToDelete.getSize(); i++) { @@ -393,7 +395,7 @@ public void iEditLastCreatedEndpointPort(int port) throws Throwable { @Then("I edit port number to {int} in endpoint with schema {string}, domain {string} and port {int}") public void iEditLastCreatedEndpointPortInEndpoint(int newPort, String schema, String domainName, int port) throws Throwable { try { - EndpointInfoQuery endpointInfoQuery = endpointInfoFactory.newQuery(getCurrentScopeId()); + EndpointInfoQuery endpointInfoQuery = new EndpointInfoQuery(getCurrentScopeId()); endpointInfoQuery.setPredicate(endpointInfoQuery.attributePredicate(EndpointInfoAttributes.SCHEMA, schema, AttributePredicate.Operator.EQUAL)); endpointInfoQuery.setPredicate(endpointInfoQuery.attributePredicate(EndpointInfoAttributes.DNS, domainName, AttributePredicate.Operator.EQUAL)); endpointInfoQuery.setPredicate(endpointInfoQuery.attributePredicate(EndpointInfoAttributes.PORT, port, AttributePredicate.Operator.EQUAL)); @@ -406,8 +408,8 @@ public void iEditLastCreatedEndpointPortInEndpoint(int newPort, String schema, S } @And("I create endpoint with schema {string} and port {int} without domain name") - public void iCreateEndpointWithSchemaAndPortWithoutDomain(String schema, int port ) throws Throwable { - EndpointInfoCreator endpointInfoCreator = endpointInfoFactory.newCreator(getCurrentScopeId()); + public void iCreateEndpointWithSchemaAndPortWithoutDomain(String schema, int port) throws Throwable { + EndpointInfoCreator endpointInfoCreator = new EndpointInfoCreator(getCurrentScopeId()); endpointInfoCreator.setSchema(schema); endpointInfoCreator.setPort(port); endpointInfoCreator.setDns(null); @@ -421,8 +423,8 @@ public void iCreateEndpointWithSchemaAndPortWithoutDomain(String schema, int por } @And("I create endpoint with domain name {string} without schema and port") - public void iCreateEndpointWithDomainWithoutSchemaAndPort(String domainName) throws Throwable{ - EndpointInfoCreator endpointInfoCreator = endpointInfoFactory.newCreator(getCurrentScopeId()); + public void iCreateEndpointWithDomainWithoutSchemaAndPort(String domainName) throws Throwable { + EndpointInfoCreator endpointInfoCreator = new EndpointInfoCreator(getCurrentScopeId()); endpointInfoCreator.setDns(domainName); endpointInfoCreator.setEndpointType(EndpointInfo.ENDPOINT_TYPE_RESOURCE); try { @@ -435,7 +437,7 @@ public void iCreateEndpointWithDomainWithoutSchemaAndPort(String domainName) thr @And("I create endpoint with schema {string} and domain {string} without port") public void iCreateEndpointWithSchemaAndDomainWithoutPort(String schema, String domainName) throws Throwable { - EndpointInfoCreator endpointInfoCreator = endpointInfoFactory.newCreator(getCurrentScopeId()); + EndpointInfoCreator endpointInfoCreator = new EndpointInfoCreator(getCurrentScopeId()); endpointInfoCreator.setDns(domainName); endpointInfoCreator.setSchema(schema); endpointInfoCreator.setEndpointType(EndpointInfo.ENDPOINT_TYPE_RESOURCE); @@ -448,8 +450,8 @@ public void iCreateEndpointWithSchemaAndDomainWithoutPort(String schema, String } @And("I create endpoint with port {int} without schema and domain name") - public void iCreateEndpointWithPortWithoutSchemaAndDomain(int port) throws Throwable{ - EndpointInfoCreator endpointInfoCreator = endpointInfoFactory.newCreator(getCurrentScopeId()); + public void iCreateEndpointWithPortWithoutSchemaAndDomain(int port) throws Throwable { + EndpointInfoCreator endpointInfoCreator = new EndpointInfoCreator(getCurrentScopeId()); endpointInfoCreator.setPort(port); endpointInfoCreator.setEndpointType(EndpointInfo.ENDPOINT_TYPE_RESOURCE); try { @@ -462,7 +464,7 @@ public void iCreateEndpointWithPortWithoutSchemaAndDomain(int port) throws Throw @And("I create endpoint with schema {string}, domain {string}, port {int} and {string} secure field") public void iCreateEndpointWithSchemaDomainPortAndSecureField(String schema, String domainName, int port, String secureField) throws Throwable { - EndpointInfoCreator endpointInfoCreator = endpointInfoFactory.newCreator(getCurrentScopeId()); + EndpointInfoCreator endpointInfoCreator = new EndpointInfoCreator(getCurrentScopeId()); endpointInfoCreator.setSchema(schema); endpointInfoCreator.setDns(domainName); endpointInfoCreator.setPort(port); @@ -497,7 +499,7 @@ public void iEditLastCreatedEndpointSecureField(String secureField) throws Throw @When("^I create a CORS filter with schema \"([^\"]*)\", domain \"([^\"]*)\" and port (\\d+)$") public void iCreateCORSFilter(String schema, String domain, int port) throws Exception { - EndpointInfoCreator endpointInfoCreator = endpointInfoFactory.newCreator(getCurrentScopeId()); + EndpointInfoCreator endpointInfoCreator = new EndpointInfoCreator(getCurrentScopeId()); endpointInfoCreator.setSchema(schema); endpointInfoCreator.setDns(domain); endpointInfoCreator.setPort(port); @@ -520,9 +522,10 @@ public void iCreateMultipleCORSFilter(DataTable corsFilters) throws Throwable { @Then("I have (\\d+) CORS filters?$") public void iHaveCORSFilter(int expectedNum) throws KapuaException { int corsFilter = KapuaSecurityUtils.doPrivileged(new Callable() { + @Override public Integer call() throws Exception { - EndpointInfoQuery endpointInfoQuery = endpointInfoFactory.newQuery(getCurrentScopeId()); + EndpointInfoQuery endpointInfoQuery = new EndpointInfoQuery(getCurrentScopeId()); EndpointInfoListResult corsFilters = endpointInfoService.query(endpointInfoQuery, EndpointInfo.ENDPOINT_TYPE_CORS); return corsFilters.getSize(); } @@ -535,7 +538,7 @@ public void iDeleteAllCORSFilters() throws Exception { primeException(); try { - EndpointInfoQuery endpointInfoQuery = endpointInfoFactory.newQuery(getCurrentScopeId()); + EndpointInfoQuery endpointInfoQuery = new EndpointInfoQuery(getCurrentScopeId()); EndpointInfoListResult endpointsToDelete = endpointInfoService.query(endpointInfoQuery, EndpointInfo.ENDPOINT_TYPE_CORS); for (int i = 0; i < endpointsToDelete.getSize(); i++) { diff --git a/service/job/api/pom.xml b/service/job/api/pom.xml index 8dfac9aefe9..4980855413a 100644 --- a/service/job/api/pom.xml +++ b/service/job/api/pom.xml @@ -17,7 +17,7 @@ org.eclipse.kapua kapua-job - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-job-api diff --git a/service/job/api/src/main/java/org/eclipse/kapua/service/job/JobCreator.java b/service/job/api/src/main/java/org/eclipse/kapua/service/job/JobCreator.java index 543cb6b7b10..7de4660fc46 100644 --- a/service/job/api/src/main/java/org/eclipse/kapua/service/job/JobCreator.java +++ b/service/job/api/src/main/java/org/eclipse/kapua/service/job/JobCreator.java @@ -12,16 +12,19 @@ *******************************************************************************/ package org.eclipse.kapua.service.job; -import org.eclipse.kapua.model.KapuaEntityCreator; -import org.eclipse.kapua.model.KapuaNamedEntityCreator; -import org.eclipse.kapua.service.job.step.JobStep; +import java.util.ArrayList; +import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; import javax.xml.bind.annotation.XmlType; -import java.util.List; + +import org.eclipse.kapua.model.KapuaEntityCreator; +import org.eclipse.kapua.model.KapuaNamedEntityCreator; +import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.service.job.step.JobStep; /** * {@link Job} {@link KapuaEntityCreator} definition. @@ -30,8 +33,24 @@ */ @XmlRootElement(name = "jobCreator") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = JobXmlRegistry.class, factoryMethod = "newJobCreator") -public interface JobCreator extends KapuaNamedEntityCreator { +@XmlType +public class JobCreator extends KapuaNamedEntityCreator { + + private static final long serialVersionUID = 3119071638220738358L; + + private List jobSteps; + private String jobXmlDefinition; + + public JobCreator() { + } + + public JobCreator(KapuaId scopeId) { + super(scopeId); + } + + public JobCreator(KapuaId scopeId, String name) { + super(scopeId, name); + } /** * Gets the {@link List} of {@link JobStep}. @@ -42,17 +61,26 @@ public interface JobCreator extends KapuaNamedEntityCreator { */ @Deprecated @XmlTransient - List getJobSteps(); + public List getJobSteps() { + if (jobSteps == null) { + jobSteps = new ArrayList<>(); + } + + return jobSteps; + } /** * Sets the {@link List} of {@link JobStep}. * - * @param jobSteps The {@link List} of {@link JobStep}. + * @param jobSteps + * The {@link List} of {@link JobStep}. * @since 1.0.0 * @deprecated Since 1.1.0. The {@link JobStep} are no longer bound to the {@link Job}. */ @Deprecated - void setJobSteps(List jobSteps); + public void setJobSteps(List jobSteps) { + this.jobSteps = jobSteps; + } /** * Gets the jBatch Job xml definition. @@ -62,16 +90,21 @@ public interface JobCreator extends KapuaNamedEntityCreator { * @deprecated Since 1.1.0. The definition is no longer generated. */ @Deprecated - String getJobXmlDefinition(); + public String getJobXmlDefinition() { + return jobXmlDefinition; + } /** * Sets the jBatch Job xml definition. * - * @param jobXmlDefinition The jBatch Job xml definition. + * @param jobXmlDefinition + * The jBatch Job xml definition. * @since 1.0.0 * @deprecated Since 1.1.0. The definition is no longer generated. */ @Deprecated - void setJobXmlDefinition(String jobXmlDefinition); + public void setJobXmlDefinition(String jobXmlDefinition) { + this.jobXmlDefinition = jobXmlDefinition; + } } diff --git a/service/job/api/src/main/java/org/eclipse/kapua/service/job/JobFactory.java b/service/job/api/src/main/java/org/eclipse/kapua/service/job/JobFactory.java index 2019e306624..4f8980d21b1 100644 --- a/service/job/api/src/main/java/org/eclipse/kapua/service/job/JobFactory.java +++ b/service/job/api/src/main/java/org/eclipse/kapua/service/job/JobFactory.java @@ -20,6 +20,6 @@ * @see org.eclipse.kapua.model.KapuaEntityFactory * @since 1.0.0 */ -public interface JobFactory extends KapuaEntityFactory { +public interface JobFactory extends KapuaEntityFactory { } diff --git a/service/job/api/src/main/java/org/eclipse/kapua/service/job/JobListResult.java b/service/job/api/src/main/java/org/eclipse/kapua/service/job/JobListResult.java index 8973c004e95..6b070dc7347 100644 --- a/service/job/api/src/main/java/org/eclipse/kapua/service/job/JobListResult.java +++ b/service/job/api/src/main/java/org/eclipse/kapua/service/job/JobListResult.java @@ -23,11 +23,11 @@ * {@link JobListResult} definition. * * @since 1.0.0 - * */ @XmlRootElement(name = "jobListResult") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = JobXmlRegistry.class, factoryMethod = "newJobListResult") -public interface JobListResult extends KapuaListResult { +@XmlType +public class JobListResult extends KapuaListResult { + private static final long serialVersionUID = -7466853155307881848L; } diff --git a/service/job/api/src/main/java/org/eclipse/kapua/service/job/JobMatchPredicate.java b/service/job/api/src/main/java/org/eclipse/kapua/service/job/JobMatchPredicate.java index 36c38f2d7a1..d11329a8c7b 100644 --- a/service/job/api/src/main/java/org/eclipse/kapua/service/job/JobMatchPredicate.java +++ b/service/job/api/src/main/java/org/eclipse/kapua/service/job/JobMatchPredicate.java @@ -12,8 +12,24 @@ *******************************************************************************/ package org.eclipse.kapua.service.job; -import org.eclipse.kapua.model.query.predicate.MatchPredicate; +import java.util.Arrays; -public interface JobMatchPredicate extends MatchPredicate { +import org.eclipse.kapua.model.query.predicate.AbstractMatchPredicate; + +public class JobMatchPredicate extends AbstractMatchPredicate { + + /** + * Constructor. + * + * @param matchTerm + * @since 2.0.0 + */ + public JobMatchPredicate(T matchTerm) { + this.attributeNames = Arrays.asList( + JobAttributes.NAME, + JobAttributes.DESCRIPTION + ); + this.matchTerm = matchTerm; + } } \ No newline at end of file diff --git a/service/job/api/src/main/java/org/eclipse/kapua/service/job/JobQuery.java b/service/job/api/src/main/java/org/eclipse/kapua/service/job/JobQuery.java index cc8af6b377d..ffbd4da3a6c 100644 --- a/service/job/api/src/main/java/org/eclipse/kapua/service/job/JobQuery.java +++ b/service/job/api/src/main/java/org/eclipse/kapua/service/job/JobQuery.java @@ -12,13 +12,15 @@ *******************************************************************************/ package org.eclipse.kapua.service.job; -import org.eclipse.kapua.model.query.KapuaQuery; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; +import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.query.AbstractKapuaNamedQuery; +import org.eclipse.kapua.model.query.KapuaQuery; + /** * {@link Job} {@link KapuaQuery} definition. * @@ -27,17 +29,35 @@ */ @XmlRootElement(name = "query") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = JobXmlRegistry.class, factoryMethod = "newQuery") -public interface JobQuery extends KapuaQuery { +@XmlType +public class JobQuery extends AbstractKapuaNamedQuery { + + public JobQuery() { + } + + /** + * Constructor. + * + * @param scopeId + * The {@link #getScopeId()}. + * @since 1.0.0 + */ + public JobQuery(KapuaId scopeId) { + super(scopeId); + } /** * Instantiates a new {@link JobMatchPredicate}. * - * @param matchTerm The term to use to match. - * @param The type of the term + * @param matchTerm + * The term to use to match. + * @param + * The type of the term * @return The newly instantiated {@link JobMatchPredicate}. * @since 2.0.0 */ - JobMatchPredicate matchPredicate(T matchTerm); + public JobMatchPredicate matchPredicate(T matchTerm) { + return new JobMatchPredicate<>(matchTerm); + } } diff --git a/service/job/api/src/main/java/org/eclipse/kapua/service/job/JobXmlRegistry.java b/service/job/api/src/main/java/org/eclipse/kapua/service/job/JobXmlRegistry.java index c8a7ee86d60..8606074b9f7 100644 --- a/service/job/api/src/main/java/org/eclipse/kapua/service/job/JobXmlRegistry.java +++ b/service/job/api/src/main/java/org/eclipse/kapua/service/job/JobXmlRegistry.java @@ -12,10 +12,10 @@ *******************************************************************************/ package org.eclipse.kapua.service.job; -import org.eclipse.kapua.locator.KapuaLocator; - import javax.xml.bind.annotation.XmlRegistry; +import org.eclipse.kapua.locator.KapuaLocator; + /** * {@link Job} xml factory class * @@ -35,25 +35,7 @@ public Job newJob() { return jobFactory.newEntity(null); } - /** - * Creates a new job creator instance - * - * @return - */ - public JobCreator newJobCreator() { - return jobFactory.newCreator(null); - } - - /** - * Creates a new job list result instance - * - * @return - */ - public JobListResult newJobListResult() { - return jobFactory.newListResult(); - } - public JobQuery newQuery() { - return jobFactory.newQuery(null); + return new JobQuery(null); } } diff --git a/service/job/api/src/main/java/org/eclipse/kapua/service/job/execution/JobExecutionCreator.java b/service/job/api/src/main/java/org/eclipse/kapua/service/job/execution/JobExecutionCreator.java index bcb3a25e34a..ba271c2775c 100644 --- a/service/job/api/src/main/java/org/eclipse/kapua/service/job/execution/JobExecutionCreator.java +++ b/service/job/api/src/main/java/org/eclipse/kapua/service/job/execution/JobExecutionCreator.java @@ -12,9 +12,8 @@ *******************************************************************************/ package org.eclipse.kapua.service.job.execution; -import org.eclipse.kapua.model.KapuaUpdatableEntityCreator; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.model.id.KapuaIdAdapter; +import java.util.Date; +import java.util.Set; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; @@ -22,8 +21,11 @@ import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; -import java.util.Date; -import java.util.Set; + +import org.eclipse.kapua.model.KapuaEntityCreator; +import org.eclipse.kapua.model.KapuaUpdatableEntityCreator; +import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.id.KapuaIdAdapter; /** * {@link JobExecutionCreator} defintion. @@ -32,32 +34,57 @@ */ @XmlRootElement(name = "jobExecutionCreator") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = JobExecutionXmlRegistry.class, factoryMethod = "newJobExecutionCreator") -public interface JobExecutionCreator extends KapuaUpdatableEntityCreator { +@XmlType +public class JobExecutionCreator extends KapuaUpdatableEntityCreator { + + private static final long serialVersionUID = 3119071638220738358L; + + private KapuaId jobId; + private Date startedOn; + private Set targetIds; + + public JobExecutionCreator() { + } + + public JobExecutionCreator(KapuaId scopeId) { + super(scopeId); + } + + public JobExecutionCreator(KapuaEntityCreator entityCreator) { + super(entityCreator); + } /** * @return * @since 1.0.0 */ - KapuaId getJobId(); + public KapuaId getJobId() { + return jobId; + } /** * @param jobId * @since 1.0.0 */ - void setJobId(KapuaId jobId); + public void setJobId(KapuaId jobId) { + this.jobId = jobId; + } /** * @return * @since 1.0.0 */ - Date getStartedOn(); + public Date getStartedOn() { + return startedOn; + } /** * @param startedOn * @since 1.0.0 */ - void setStartedOn(Date startedOn); + public void setStartedOn(Date startedOn) { + this.startedOn = startedOn; + } /** * @return @@ -65,11 +92,15 @@ public interface JobExecutionCreator extends KapuaUpdatableEntityCreator Set getTargetIds(); + public Set getTargetIds() { + return targetIds; + } /** - * @param tagTargetIds + * @param targetIds * @since 1.1.0 */ - void setTargetIds(Set tagTargetIds); + public void setTargetIds(Set targetIds) { + this.targetIds = targetIds; + } } diff --git a/service/job/api/src/main/java/org/eclipse/kapua/service/job/execution/JobExecutionFactory.java b/service/job/api/src/main/java/org/eclipse/kapua/service/job/execution/JobExecutionFactory.java index ff4fb3d0e98..290775a71de 100644 --- a/service/job/api/src/main/java/org/eclipse/kapua/service/job/execution/JobExecutionFactory.java +++ b/service/job/api/src/main/java/org/eclipse/kapua/service/job/execution/JobExecutionFactory.java @@ -20,6 +20,6 @@ * @see org.eclipse.kapua.model.KapuaEntityFactory * @since 1.0.0 */ -public interface JobExecutionFactory extends KapuaEntityFactory { +public interface JobExecutionFactory extends KapuaEntityFactory { } diff --git a/service/job/api/src/main/java/org/eclipse/kapua/service/job/execution/JobExecutionListResult.java b/service/job/api/src/main/java/org/eclipse/kapua/service/job/execution/JobExecutionListResult.java index 59a93a12798..02dcea3020c 100644 --- a/service/job/api/src/main/java/org/eclipse/kapua/service/job/execution/JobExecutionListResult.java +++ b/service/job/api/src/main/java/org/eclipse/kapua/service/job/execution/JobExecutionListResult.java @@ -23,11 +23,10 @@ * {@link JobExecutionListResult} definition. * * @since 1.0.0 - * */ @XmlRootElement(name = "jobExecutionListResult") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = JobExecutionXmlRegistry.class, factoryMethod = "newJobExecutionListResult") -public interface JobExecutionListResult extends KapuaListResult { +@XmlType +public class JobExecutionListResult extends KapuaListResult { } diff --git a/service/job/api/src/main/java/org/eclipse/kapua/service/job/execution/JobExecutionQuery.java b/service/job/api/src/main/java/org/eclipse/kapua/service/job/execution/JobExecutionQuery.java index 74e68ba2e40..4c3be4c644e 100644 --- a/service/job/api/src/main/java/org/eclipse/kapua/service/job/execution/JobExecutionQuery.java +++ b/service/job/api/src/main/java/org/eclipse/kapua/service/job/execution/JobExecutionQuery.java @@ -12,13 +12,16 @@ *******************************************************************************/ package org.eclipse.kapua.service.job.execution; -import org.eclipse.kapua.model.query.KapuaQuery; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; +import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.query.KapuaQuery; +import org.eclipse.kapua.model.query.KapuaSortCriteria; +import org.eclipse.kapua.model.query.SortOrder; + /** * {@link JobExecution} {@link KapuaQuery} definition. * @@ -27,6 +30,25 @@ */ @XmlRootElement(name = "query") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = JobExecutionXmlRegistry.class, factoryMethod = "newQuery") -public interface JobExecutionQuery extends KapuaQuery { +@XmlType +public class JobExecutionQuery extends KapuaQuery { + + public JobExecutionQuery() { + } + + /** + * Constructor. + * + * @param scopeId + * The {@link #getScopeId()}. + * @since 1.0.0 + */ + public JobExecutionQuery(KapuaId scopeId) { + super(scopeId); + } + + @Override + public KapuaSortCriteria getDefaultSortCriteria() { + return fieldSortCriteria(JobExecutionAttributes.STARTED_ON, SortOrder.DESCENDING); + } } diff --git a/service/job/api/src/main/java/org/eclipse/kapua/service/job/execution/JobExecutionXmlRegistry.java b/service/job/api/src/main/java/org/eclipse/kapua/service/job/execution/JobExecutionXmlRegistry.java index b1a6903c338..4c4cfb818e9 100644 --- a/service/job/api/src/main/java/org/eclipse/kapua/service/job/execution/JobExecutionXmlRegistry.java +++ b/service/job/api/src/main/java/org/eclipse/kapua/service/job/execution/JobExecutionXmlRegistry.java @@ -12,10 +12,10 @@ *******************************************************************************/ package org.eclipse.kapua.service.job.execution; -import org.eclipse.kapua.locator.KapuaLocator; - import javax.xml.bind.annotation.XmlRegistry; +import org.eclipse.kapua.locator.KapuaLocator; + /** * {@link JobExecution} xml factory class * @@ -34,26 +34,4 @@ public class JobExecutionXmlRegistry { public JobExecution newJobExecution() { return jobExecutionFactory.newEntity(null); } - - /** - * Creates a new job creator instance - * - * @return - */ - public JobExecutionCreator newJobExecutionCreator() { - return jobExecutionFactory.newCreator(null); - } - - /** - * Creates a new job list result instance - * - * @return - */ - public JobExecutionListResult newJobExecutionListResult() { - return jobExecutionFactory.newListResult(); - } - - public JobExecutionQuery newQuery() { - return jobExecutionFactory.newQuery(null); - } } diff --git a/service/job/api/src/main/java/org/eclipse/kapua/service/job/step/JobStepCreator.java b/service/job/api/src/main/java/org/eclipse/kapua/service/job/step/JobStepCreator.java index 86c62efde68..7431f4fe8c3 100644 --- a/service/job/api/src/main/java/org/eclipse/kapua/service/job/step/JobStepCreator.java +++ b/service/job/api/src/main/java/org/eclipse/kapua/service/job/step/JobStepCreator.java @@ -12,10 +12,8 @@ *******************************************************************************/ package org.eclipse.kapua.service.job.step; -import org.eclipse.kapua.model.KapuaNamedEntityCreator; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.model.id.KapuaIdAdapter; -import org.eclipse.kapua.service.job.step.definition.JobStepProperty; +import java.util.ArrayList; +import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; @@ -24,7 +22,11 @@ import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; -import java.util.List; + +import org.eclipse.kapua.model.KapuaNamedEntityCreator; +import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.id.KapuaIdAdapter; +import org.eclipse.kapua.service.job.step.definition.JobStepProperty; /** * {@link JobStepCreator} {@link org.eclipse.kapua.model.KapuaEntityCreator} definition @@ -33,56 +35,93 @@ */ @XmlRootElement(name = "jobStepCreator") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = JobStepXmlRegistry.class, factoryMethod = "newJobStepCreator") -public interface JobStepCreator extends KapuaNamedEntityCreator { +@XmlType +public class JobStepCreator extends KapuaNamedEntityCreator { + + private static final long serialVersionUID = 3119071638220738358L; + + private KapuaId jobId; + private Integer stepIndex; + private KapuaId jobStepDefinitionId; + private List jobStepProperty; + + public JobStepCreator() { + } + + public JobStepCreator(KapuaId scopeId) { + super(scopeId); + } + + public JobStepCreator(KapuaId scopeId, String name) { + super(scopeId, name); + } @XmlJavaTypeAdapter(KapuaIdAdapter.class) - KapuaId getJobId(); + public KapuaId getJobId() { + return jobId; + } - void setJobId(KapuaId jobId); + public void setJobId(KapuaId jobId) { + this.jobId = jobId; + } - Integer getStepIndex(); + public Integer getStepIndex() { + return stepIndex; + } - void setStepIndex(Integer stepIndex); + public void setStepIndex(Integer stepIndex) { + this.stepIndex = stepIndex; + } @XmlJavaTypeAdapter(KapuaIdAdapter.class) - KapuaId getJobStepDefinitionId(); + public KapuaId getJobStepDefinitionId() { + return jobStepDefinitionId; + } - void setJobStepDefinitionId(KapuaId jobStepDefinitionId); + public void setJobStepDefinitionId(KapuaId jobStepDefinitionId) { + this.jobStepDefinitionId = jobStepDefinitionId; + } @XmlElementWrapper(name = "stepProperties") @XmlElement(name = "stepProperty") -

        List

        getStepProperties(); + public List getStepProperties() { + if (jobStepProperty == null) { + jobStepProperty = new ArrayList<>(); + } - void setStepProperties(List jobStepProperties); + return jobStepProperty; + } + + public void setStepProperties(List jobStepProperty) { + this.jobStepProperty = jobStepProperty; + } /** - * @deprecated since 2.0.0. Please make use of {@link #getStepProperties()}. This method is deprecated - * because of issue #3580 (i.e. the step properties' field is called different depending on what request are you using). + * @deprecated since 2.0.0. Please make use of {@link #getStepProperties()}. This method is deprecated because of issue #3580 (i.e. the step properties' field is called different depending on what + * request are you using). */ @Deprecated @XmlElementWrapper(name = "jobStepProperties") @XmlElement(name = "jobStepProperty") - default

        List

        getJobStepPropertiesDeprecated() { + public List getJobStepPropertiesDeprecated() { return getStepProperties(); } /** - * @deprecated since 2.0.0. Please make use of {@link #setStepProperties(List)}. This method is deprecated - * because of issue #3580 (i.e. the step properties' field is called different depending on what request are you using). + * @deprecated since 2.0.0. Please make use of {@link #setStepProperties(List)}. This method is deprecated because of issue #3580 (i.e. the step properties' field is called different depending on + * what request are you using). */ @Deprecated - default void setJobStepProperties(List jobStepProperties) { + public void setJobStepProperties(List jobStepProperties) { setStepProperties(jobStepProperties); } - /** - * @deprecated since 2.0.0. Please make use of {@link #setStepProperties(List)}. This method is deprecated - * because of issue #3580 (i.e. the step properties' field is called different depending on what request are you using). + * @deprecated since 2.0.0. Please make use of {@link #setStepProperties(List)}. This method is deprecated because of issue #3580 (i.e. the step properties' field is called different depending on + * what request are you using). */ @Deprecated - default void setJobStepPropertiesDeprecated(List jobStepProperties) { + public void setJobStepPropertiesDeprecated(List jobStepProperties) { setStepProperties(jobStepProperties); } } diff --git a/service/job/api/src/main/java/org/eclipse/kapua/service/job/step/JobStepFactory.java b/service/job/api/src/main/java/org/eclipse/kapua/service/job/step/JobStepFactory.java index 8509317161f..47e7f8fc121 100644 --- a/service/job/api/src/main/java/org/eclipse/kapua/service/job/step/JobStepFactory.java +++ b/service/job/api/src/main/java/org/eclipse/kapua/service/job/step/JobStepFactory.java @@ -21,14 +21,17 @@ * @see org.eclipse.kapua.model.KapuaEntityFactory * @since 1.0.0 */ -public interface JobStepFactory extends KapuaEntityFactory { +public interface JobStepFactory extends KapuaEntityFactory { /** * Instantiates a new {@link JobStepProperty}. * - * @param name The name to set into the {@link JobStepProperty}. - * @param propertyType The type to set into the {@link JobStepProperty}. - * @param propertyValue The value to set into the {@link JobStepProperty}. + * @param name + * The name to set into the {@link JobStepProperty}. + * @param propertyType + * The type to set into the {@link JobStepProperty}. + * @param propertyValue + * The value to set into the {@link JobStepProperty}. * @return The newly instantiated {@link JobStepProperty} * @since 1.0.0 */ diff --git a/service/job/api/src/main/java/org/eclipse/kapua/service/job/step/JobStepListResult.java b/service/job/api/src/main/java/org/eclipse/kapua/service/job/step/JobStepListResult.java index 8b0dd67edd9..a568f646352 100644 --- a/service/job/api/src/main/java/org/eclipse/kapua/service/job/step/JobStepListResult.java +++ b/service/job/api/src/main/java/org/eclipse/kapua/service/job/step/JobStepListResult.java @@ -23,11 +23,12 @@ * {@link JobStepListResult} definition. * * @since 1.0.0 - * */ @XmlRootElement(name = "jobStepListResult") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = JobStepXmlRegistry.class, factoryMethod = "newJobStepListResult") -public interface JobStepListResult extends KapuaListResult { +@XmlType +public class JobStepListResult extends KapuaListResult { + + private static final long serialVersionUID = -7466853155307881848L; } diff --git a/service/job/api/src/main/java/org/eclipse/kapua/service/job/step/JobStepQuery.java b/service/job/api/src/main/java/org/eclipse/kapua/service/job/step/JobStepQuery.java deleted file mode 100644 index 464319a1fab..00000000000 --- a/service/job/api/src/main/java/org/eclipse/kapua/service/job/step/JobStepQuery.java +++ /dev/null @@ -1,32 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2017, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.job.step; - -import org.eclipse.kapua.model.query.KapuaQuery; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlType; - -/** - * {@link JobStep} {@link KapuaQuery} definition. - * - * @see KapuaQuery - * @since 1.0.0 - */ -@XmlRootElement(name = "query") -@XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = JobStepXmlRegistry.class, factoryMethod = "newQuery") -public interface JobStepQuery extends KapuaQuery { -} diff --git a/service/job/api/src/main/java/org/eclipse/kapua/service/job/step/JobStepService.java b/service/job/api/src/main/java/org/eclipse/kapua/service/job/step/JobStepService.java index 1f05f980635..76b2653fd29 100644 --- a/service/job/api/src/main/java/org/eclipse/kapua/service/job/step/JobStepService.java +++ b/service/job/api/src/main/java/org/eclipse/kapua/service/job/step/JobStepService.java @@ -19,9 +19,8 @@ import org.eclipse.kapua.service.job.step.definition.JobStepProperty; /** - * {@link JobStepService} exposes APIs to manage JobStep objects.
        - * It includes APIs to create, update, find, list and delete Jobs.
        - * Instances of the JobStepService can be acquired through the ServiceLocator object. + * {@link JobStepService} exposes APIs to manage JobStep objects.
        It includes APIs to create, update, find, list and delete Jobs.
        Instances of the JobStepService can be acquired through the + * ServiceLocator object. * * @since 1.0 */ @@ -31,7 +30,8 @@ public interface JobStepService extends KapuaEntityService { +@XmlType +public class JobStepDefinitionCreator extends KapuaNamedEntityCreator { + + private static final long serialVersionUID = 4602067255120049746L; + + private JobStepType jobStepType; + private String readerName; + private String processorName; + private String writerName; + private List jobStepProperties; + + public JobStepDefinitionCreator() { + } + + public JobStepDefinitionCreator(KapuaId scopeId) { + super(scopeId); + } + + public JobStepDefinitionCreator(KapuaId scopeId, String name) { + super(scopeId, name); + } + + public JobStepType getStepType() { + return jobStepType; + } - JobStepType getStepType(); + public JobStepDefinitionCreator setStepType(JobStepType jobStepType) { + this.jobStepType = jobStepType; + return this; + } - void setStepType(JobStepType jobStepType); + public String getReaderName() { + return readerName; + } - String getReaderName(); + public JobStepDefinitionCreator setReaderName(String readerName) { + this.readerName = readerName; + return this; + } - void setReaderName(String readerName); + public String getProcessorName() { + return processorName; + } - String getProcessorName(); + public JobStepDefinitionCreator setProcessorName(String processorName) { + this.processorName = processorName; + return this; + } - void setProcessorName(String processorName); + public String getWriterName() { + return writerName; + } - String getWriterName(); + public JobStepDefinitionCreator setWriterName(String writerName) { + this.writerName = writerName; + return this; + } - void setWriterName(String writesName); + public List getStepProperties() { + if (jobStepProperties == null) { + jobStepProperties = new ArrayList<>(); + } - List getStepProperties(); + return jobStepProperties; + } - void setStepProperties(List jobStepProperties); + public JobStepDefinitionCreator setStepProperties(List jobStepProperties) { + this.jobStepProperties = jobStepProperties; + return this; + } } diff --git a/service/job/api/src/main/java/org/eclipse/kapua/service/job/step/definition/JobStepDefinitionFactory.java b/service/job/api/src/main/java/org/eclipse/kapua/service/job/step/definition/JobStepDefinitionFactory.java index 7e7d0f9068f..051a3f8e22c 100644 --- a/service/job/api/src/main/java/org/eclipse/kapua/service/job/step/definition/JobStepDefinitionFactory.java +++ b/service/job/api/src/main/java/org/eclipse/kapua/service/job/step/definition/JobStepDefinitionFactory.java @@ -20,15 +20,19 @@ * @see org.eclipse.kapua.model.KapuaEntityFactory * @since 1.0.0 */ -public interface JobStepDefinitionFactory extends KapuaEntityFactory { +public interface JobStepDefinitionFactory extends KapuaEntityFactory { /** * Instantiates a new {@link JobStepProperty}. * - * @param name The name to set into the {@link JobStepProperty}. - * @param type The type to set into the {@link JobStepProperty}. - * @param value The value to set into the {@link JobStepProperty}. - * @param exampleValue The example value to set into the {@link JobStepProperty} + * @param name + * The name to set into the {@link JobStepProperty}. + * @param type + * The type to set into the {@link JobStepProperty}. + * @param value + * The value to set into the {@link JobStepProperty}. + * @param exampleValue + * The example value to set into the {@link JobStepProperty} * @return The newly instantiated {@link JobStepProperty}. * @since 1.1.0 */ @@ -37,9 +41,12 @@ public interface JobStepDefinitionFactory extends KapuaEntityFactory { +@XmlType +public class JobStepDefinitionListResult extends KapuaListResult { + + private static final long serialVersionUID = 977813250632719295L; } diff --git a/service/job/api/src/main/java/org/eclipse/kapua/service/job/step/definition/JobStepDefinitionQuery.java b/service/job/api/src/main/java/org/eclipse/kapua/service/job/step/definition/JobStepDefinitionQuery.java index be9874b0465..6bc361be1f8 100644 --- a/service/job/api/src/main/java/org/eclipse/kapua/service/job/step/definition/JobStepDefinitionQuery.java +++ b/service/job/api/src/main/java/org/eclipse/kapua/service/job/step/definition/JobStepDefinitionQuery.java @@ -12,13 +12,15 @@ *******************************************************************************/ package org.eclipse.kapua.service.job.step.definition; -import org.eclipse.kapua.model.query.KapuaQuery; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; +import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.query.AbstractKapuaNamedQuery; +import org.eclipse.kapua.model.query.KapuaQuery; + /** * {@link JobStepDefinition} {@link KapuaQuery} definition. * @@ -27,6 +29,31 @@ */ @XmlRootElement(name = "query") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = JobStepDefinitionXmlRegistry.class, factoryMethod = "newQuery") -public interface JobStepDefinitionQuery extends KapuaQuery { +@XmlType +public class JobStepDefinitionQuery extends AbstractKapuaNamedQuery { + + public JobStepDefinitionQuery() { + } + + /** + * Constructor. + * + * @param scopeId + * The {@link #getScopeId()}. + * @since 1.0.0 + */ + public JobStepDefinitionQuery(KapuaId scopeId) { + super(scopeId); + } + + /** + * This enables {@link JobStepDefinitionQuery} to retrieve also not scoped {@link JobStepDefinition}s since they are public. + * + * @return {@code true} + * @since 2.0.0 + */ + @Override + public boolean getNotScopedEntities() { + return true; + } } diff --git a/service/job/api/src/main/java/org/eclipse/kapua/service/job/step/definition/JobStepDefinitionRecord.java b/service/job/api/src/main/java/org/eclipse/kapua/service/job/step/definition/JobStepDefinitionRecord.java index 3f16dcf7ee6..8d38c0482cd 100644 --- a/service/job/api/src/main/java/org/eclipse/kapua/service/job/step/definition/JobStepDefinitionRecord.java +++ b/service/job/api/src/main/java/org/eclipse/kapua/service/job/step/definition/JobStepDefinitionRecord.java @@ -12,14 +12,14 @@ *******************************************************************************/ package org.eclipse.kapua.service.job.step.definition; -import org.eclipse.kapua.entity.EntityPropertiesReadException; -import org.eclipse.kapua.entity.EntityPropertiesWriteException; -import org.eclipse.kapua.model.id.KapuaId; - import java.util.Date; import java.util.List; import java.util.Properties; +import org.eclipse.kapua.entity.EntityPropertiesReadException; +import org.eclipse.kapua.entity.EntityPropertiesWriteException; +import org.eclipse.kapua.model.id.KapuaId; + public abstract class JobStepDefinitionRecord implements JobStepDefinition { private static final long serialVersionUID = 8163044089055983759L; @@ -33,13 +33,13 @@ public abstract class JobStepDefinitionRecord implements JobStepDefinition { private List jobStepProperties; public JobStepDefinitionRecord(KapuaId scopeId, - String name, - String description, - JobStepType stepType, - String readerName, - String processorName, - String writerName, - List jobStepProperties) { + String name, + String description, + JobStepType stepType, + String readerName, + String processorName, + String writerName, + List jobStepProperties) { this.scopeId = scopeId; this.name = name; this.description = description; @@ -194,11 +194,9 @@ public void setWriterName(String writerName) { throw new UnsupportedOperationException(); } - @Override public void setStepProperties(List jobStepProperties) { throw new UnsupportedOperationException(); } - } diff --git a/service/job/api/src/main/java/org/eclipse/kapua/service/job/step/definition/JobStepDefinitionXmlRegistry.java b/service/job/api/src/main/java/org/eclipse/kapua/service/job/step/definition/JobStepDefinitionXmlRegistry.java index 019d7fd1776..cf58315f53d 100644 --- a/service/job/api/src/main/java/org/eclipse/kapua/service/job/step/definition/JobStepDefinitionXmlRegistry.java +++ b/service/job/api/src/main/java/org/eclipse/kapua/service/job/step/definition/JobStepDefinitionXmlRegistry.java @@ -12,10 +12,10 @@ *******************************************************************************/ package org.eclipse.kapua.service.job.step.definition; -import org.eclipse.kapua.locator.KapuaLocator; - import javax.xml.bind.annotation.XmlRegistry; +import org.eclipse.kapua.locator.KapuaLocator; + /** * {@link JobStepDefinition} xml factory class * @@ -34,26 +34,4 @@ public class JobStepDefinitionXmlRegistry { public JobStepDefinition newJobStepDefinition() { return jobStepDefinitionFactory.newEntity(null); } - - /** - * Creates a new job creator instance - * - * @return - */ - public JobStepDefinitionCreator newJobStepDefinitionCreator() { - return jobStepDefinitionFactory.newCreator(null); - } - - /** - * Creates a new job list result instance - * - * @return - */ - public JobStepDefinitionListResult newJobStepDefinitionListResult() { - return jobStepDefinitionFactory.newListResult(); - } - - public JobStepDefinitionQuery newQuery() { - return jobStepDefinitionFactory.newQuery(null); - } } diff --git a/service/job/api/src/main/java/org/eclipse/kapua/service/job/targets/JobTargetCreator.java b/service/job/api/src/main/java/org/eclipse/kapua/service/job/targets/JobTargetCreator.java index a5d615868c8..4e5a0aab684 100644 --- a/service/job/api/src/main/java/org/eclipse/kapua/service/job/targets/JobTargetCreator.java +++ b/service/job/api/src/main/java/org/eclipse/kapua/service/job/targets/JobTargetCreator.java @@ -12,34 +12,58 @@ *******************************************************************************/ package org.eclipse.kapua.service.job.targets; -import org.eclipse.kapua.model.KapuaUpdatableEntityCreator; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.model.id.KapuaIdAdapter; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; +import org.eclipse.kapua.model.KapuaEntityCreator; +import org.eclipse.kapua.model.KapuaUpdatableEntityCreator; +import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.id.KapuaIdAdapter; + /** - * {@link JobTargetCreator} encapsulates all the information needed to create a new JobTarget in the system.
        - * The data provided will be used to seed the new JobTarget. + * {@link JobTargetCreator} encapsulates all the information needed to create a new JobTarget in the system.
        The data provided will be used to seed the new JobTarget. * * @since 1.0.0 */ @XmlRootElement(name = "jobTargetCreator") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = JobTargetXmlRegistry.class, factoryMethod = "newJobTargetCreator") -public interface JobTargetCreator extends KapuaUpdatableEntityCreator { +@XmlType +public class JobTargetCreator extends KapuaUpdatableEntityCreator { + + private static final long serialVersionUID = 3119071638220738358L; + + private KapuaId jobId; + private KapuaId jobTargetId; + + public JobTargetCreator() { + } + + public JobTargetCreator(KapuaId scopeId) { + super(scopeId); + } + + public JobTargetCreator(KapuaEntityCreator entityCreator) { + super(entityCreator); + } @XmlJavaTypeAdapter(KapuaIdAdapter.class) - KapuaId getJobId(); + public KapuaId getJobId() { + return jobId; + } - void setJobId(KapuaId jobId); + public void setJobId(KapuaId jobId) { + this.jobId = jobId; + } @XmlJavaTypeAdapter(KapuaIdAdapter.class) - KapuaId getJobTargetId(); + public KapuaId getJobTargetId() { + return jobTargetId; + } - void setJobTargetId(KapuaId jobTargetId); + public void setJobTargetId(KapuaId jobTargetId) { + this.jobTargetId = jobTargetId; + } } diff --git a/service/job/api/src/main/java/org/eclipse/kapua/service/job/targets/JobTargetFactory.java b/service/job/api/src/main/java/org/eclipse/kapua/service/job/targets/JobTargetFactory.java index 27b4e8dae25..83c754cc9ed 100644 --- a/service/job/api/src/main/java/org/eclipse/kapua/service/job/targets/JobTargetFactory.java +++ b/service/job/api/src/main/java/org/eclipse/kapua/service/job/targets/JobTargetFactory.java @@ -20,6 +20,6 @@ * @see org.eclipse.kapua.model.KapuaEntityFactory * @since 1.0.0 */ -public interface JobTargetFactory extends KapuaEntityFactory { +public interface JobTargetFactory extends KapuaEntityFactory { } diff --git a/service/job/api/src/main/java/org/eclipse/kapua/service/job/targets/JobTargetListResult.java b/service/job/api/src/main/java/org/eclipse/kapua/service/job/targets/JobTargetListResult.java index 3ad08fabff5..629c92c318b 100644 --- a/service/job/api/src/main/java/org/eclipse/kapua/service/job/targets/JobTargetListResult.java +++ b/service/job/api/src/main/java/org/eclipse/kapua/service/job/targets/JobTargetListResult.java @@ -23,11 +23,10 @@ * {@link JobTargetListResult} definition. * * @since 1.0.0 - * */ @XmlRootElement(name = "jobTargetListResult") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = JobTargetXmlRegistry.class, factoryMethod = "newJobTargetListResult") -public interface JobTargetListResult extends KapuaListResult { +@XmlType +public class JobTargetListResult extends KapuaListResult { } diff --git a/service/job/api/src/main/java/org/eclipse/kapua/service/job/targets/JobTargetQuery.java b/service/job/api/src/main/java/org/eclipse/kapua/service/job/targets/JobTargetQuery.java deleted file mode 100644 index 237d12699fa..00000000000 --- a/service/job/api/src/main/java/org/eclipse/kapua/service/job/targets/JobTargetQuery.java +++ /dev/null @@ -1,32 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2017, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.job.targets; - -import org.eclipse.kapua.model.query.KapuaQuery; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlType; - -/** - * {@link JobTarget} {@link KapuaQuery} definition. - * - * @see KapuaQuery - * @since 1.0.0 - */ -@XmlRootElement(name = "query") -@XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = JobTargetXmlRegistry.class, factoryMethod = "newQuery") -public interface JobTargetQuery extends KapuaQuery { -} diff --git a/service/job/api/src/main/java/org/eclipse/kapua/service/job/targets/JobTargetService.java b/service/job/api/src/main/java/org/eclipse/kapua/service/job/targets/JobTargetService.java index 91612a3c200..f5e859eb4f6 100644 --- a/service/job/api/src/main/java/org/eclipse/kapua/service/job/targets/JobTargetService.java +++ b/service/job/api/src/main/java/org/eclipse/kapua/service/job/targets/JobTargetService.java @@ -18,9 +18,8 @@ import org.eclipse.kapua.service.KapuaUpdatableEntityService; /** - * {@link JobTargetService} exposes APIs to manage JobTarget objects.
        - * It includes APIs to create, update, find, list and delete Jobs.
        - * Instances of the JobTargetService can be acquired through the ServiceLocator object. + * {@link JobTargetService} exposes APIs to manage JobTarget objects.
        It includes APIs to create, update, find, list and delete Jobs.
        Instances of the JobTargetService can be acquired through + * the ServiceLocator object. * * @since 1.0 */ @@ -30,7 +29,8 @@ public interface JobTargetService extends KapuaEntityService org.eclipse.kapua kapua-job - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-job-internal diff --git a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/execution/internal/JobExecutionCreatorImpl.java b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/execution/internal/JobExecutionCreatorImpl.java deleted file mode 100644 index 10cc8af3b89..00000000000 --- a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/execution/internal/JobExecutionCreatorImpl.java +++ /dev/null @@ -1,69 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2017, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.job.execution.internal; - -import org.eclipse.kapua.commons.model.AbstractKapuaUpdatableEntityCreator; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.job.execution.JobExecution; -import org.eclipse.kapua.service.job.execution.JobExecutionCreator; - -import java.util.Date; -import java.util.Set; - -/** - * {@link JobExecutionCreator} implementation - * - * @since 1.0.0 - */ -public class JobExecutionCreatorImpl extends AbstractKapuaUpdatableEntityCreator implements JobExecutionCreator { - - private static final long serialVersionUID = 3119071638220738358L; - - private KapuaId jobId; - private Date startedOn; - private Set targetIds; - - protected JobExecutionCreatorImpl(KapuaId scopeId) { - super(scopeId); - } - - @Override - public KapuaId getJobId() { - return jobId; - } - - @Override - public void setJobId(KapuaId jobId) { - this.jobId = jobId; - } - - @Override - public Date getStartedOn() { - return startedOn; - } - - @Override - public void setStartedOn(Date startedOn) { - this.startedOn = startedOn; - } - - @Override - public Set getTargetIds() { - return targetIds; - } - - @Override - public void setTargetIds(Set targetIds) { - this.targetIds = targetIds; - } -} diff --git a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/execution/internal/JobExecutionFactoryImpl.java b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/execution/internal/JobExecutionFactoryImpl.java index 71fa2a9f3d0..3eae6ec50f9 100644 --- a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/execution/internal/JobExecutionFactoryImpl.java +++ b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/execution/internal/JobExecutionFactoryImpl.java @@ -12,15 +12,12 @@ *******************************************************************************/ package org.eclipse.kapua.service.job.execution.internal; +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaEntityCloneException; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.job.execution.JobExecution; -import org.eclipse.kapua.service.job.execution.JobExecutionCreator; import org.eclipse.kapua.service.job.execution.JobExecutionFactory; -import org.eclipse.kapua.service.job.execution.JobExecutionListResult; -import org.eclipse.kapua.service.job.execution.JobExecutionQuery; - -import javax.inject.Singleton; /** * {@link JobExecutionFactory} implementation. @@ -35,21 +32,6 @@ public JobExecution newEntity(KapuaId scopeId) { return new JobExecutionImpl(scopeId); } - @Override - public JobExecutionCreator newCreator(KapuaId scopeId) { - return new JobExecutionCreatorImpl(scopeId); - } - - @Override - public JobExecutionQuery newQuery(KapuaId scopeId) { - return new JobExecutionQueryImpl(scopeId); - } - - @Override - public JobExecutionListResult newListResult() { - return new JobExecutionListResultImpl(); - } - @Override public JobExecution clone(JobExecution jobExecution) { try { diff --git a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/execution/internal/JobExecutionImplJpaRepository.java b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/execution/internal/JobExecutionImplJpaRepository.java index c4224d0d2bd..12fa03d1584 100644 --- a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/execution/internal/JobExecutionImplJpaRepository.java +++ b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/execution/internal/JobExecutionImplJpaRepository.java @@ -25,13 +25,14 @@ public class JobExecutionImplJpaRepository extends KapuaUpdatableEntityJpaRepository implements JobExecutionRepository { + public JobExecutionImplJpaRepository(KapuaJpaRepositoryConfiguration jpaRepoConfig) { - super(JobExecutionImpl.class, JobExecution.TYPE, () -> new JobExecutionListResultImpl(), jpaRepoConfig); + super(JobExecutionImpl.class, JobExecution.TYPE, () -> new JobExecutionListResult(), jpaRepoConfig); } @Override public long countByJobId(TxContext tx, KapuaId scopeId, KapuaId jobId) throws KapuaException { - final JobExecutionQuery jobExecutionQuery = new JobExecutionQueryImpl(scopeId); + final JobExecutionQuery jobExecutionQuery = new JobExecutionQuery(scopeId); jobExecutionQuery.setPredicate( jobExecutionQuery.attributePredicate(JobExecutionImpl_.JOB_ID, jobId) ); diff --git a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/execution/internal/JobExecutionListResultImpl.java b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/execution/internal/JobExecutionListResultImpl.java deleted file mode 100644 index f0d37bcad5f..00000000000 --- a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/execution/internal/JobExecutionListResultImpl.java +++ /dev/null @@ -1,26 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2017, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.job.execution.internal; - -import org.eclipse.kapua.commons.model.query.KapuaListResultImpl; -import org.eclipse.kapua.service.job.execution.JobExecution; -import org.eclipse.kapua.service.job.execution.JobExecutionListResult; - -/** - * {@link JobExecutionListResult} implementation. - * - * @since 1.0.0 - */ -public class JobExecutionListResultImpl extends KapuaListResultImpl implements JobExecutionListResult { - -} diff --git a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/execution/internal/JobExecutionModule.java b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/execution/internal/JobExecutionModule.java index 8c98203efa0..ca31e80a6b8 100644 --- a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/execution/internal/JobExecutionModule.java +++ b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/execution/internal/JobExecutionModule.java @@ -12,20 +12,21 @@ *******************************************************************************/ package org.eclipse.kapua.service.job.execution.internal; -import com.google.inject.Provides; +import javax.inject.Named; +import javax.inject.Singleton; + import org.eclipse.kapua.commons.core.AbstractKapuaModule; import org.eclipse.kapua.commons.jpa.KapuaJpaRepositoryConfiguration; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; import org.eclipse.kapua.service.job.execution.JobExecutionFactory; import org.eclipse.kapua.service.job.execution.JobExecutionRepository; import org.eclipse.kapua.service.job.execution.JobExecutionService; import org.eclipse.kapua.storage.TxManager; -import javax.inject.Named; -import javax.inject.Singleton; +import com.google.inject.Provides; public class JobExecutionModule extends AbstractKapuaModule { + @Override protected void configureModule() { bind(JobExecutionFactory.class).to(JobExecutionFactoryImpl.class); @@ -35,12 +36,10 @@ protected void configureModule() { @Singleton JobExecutionService jobExecutionService( AuthorizationService authorizationService, - PermissionFactory permissionFactory, @Named("jobTxManager") TxManager txManager, JobExecutionRepository jobExecutionRepository) { return new JobExecutionServiceImpl( authorizationService, - permissionFactory, txManager, jobExecutionRepository); } diff --git a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/execution/internal/JobExecutionQueryImpl.java b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/execution/internal/JobExecutionQueryImpl.java deleted file mode 100644 index 040361482f9..00000000000 --- a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/execution/internal/JobExecutionQueryImpl.java +++ /dev/null @@ -1,43 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2017, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.job.execution.internal; - -import org.eclipse.kapua.commons.model.query.AbstractKapuaQuery; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.model.query.KapuaSortCriteria; -import org.eclipse.kapua.model.query.SortOrder; -import org.eclipse.kapua.service.job.execution.JobExecutionAttributes; -import org.eclipse.kapua.service.job.execution.JobExecutionQuery; - -/** - * {@link JobExecutionQuery} implementation. - * - * @since 1.0.0 - */ -public class JobExecutionQueryImpl extends AbstractKapuaQuery implements JobExecutionQuery { - - /** - * Constructor. - * - * @param scopeId The {@link #getScopeId()}. - * @since 1.0.0 - */ - public JobExecutionQueryImpl(KapuaId scopeId) { - super(scopeId); - } - - @Override - public KapuaSortCriteria getDefaultSortCriteria() { - return fieldSortCriteria(JobExecutionAttributes.STARTED_ON, SortOrder.DESCENDING); - } -} diff --git a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/execution/internal/JobExecutionServiceImpl.java b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/execution/internal/JobExecutionServiceImpl.java index 320d92548ac..f8968090fbf 100644 --- a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/execution/internal/JobExecutionServiceImpl.java +++ b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/execution/internal/JobExecutionServiceImpl.java @@ -12,6 +12,8 @@ *******************************************************************************/ package org.eclipse.kapua.service.job.execution.internal; +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.commons.model.domains.Domains; import org.eclipse.kapua.commons.util.ArgumentValidator; @@ -19,7 +21,7 @@ import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; +import org.eclipse.kapua.service.authorization.permission.Permission; import org.eclipse.kapua.service.job.execution.JobExecution; import org.eclipse.kapua.service.job.execution.JobExecutionCreator; import org.eclipse.kapua.service.job.execution.JobExecutionListResult; @@ -27,8 +29,6 @@ import org.eclipse.kapua.service.job.execution.JobExecutionService; import org.eclipse.kapua.storage.TxManager; -import javax.inject.Singleton; - /** * {@link JobExecutionService} implementation * @@ -38,17 +38,14 @@ public class JobExecutionServiceImpl implements JobExecutionService { private final AuthorizationService authorizationService; - private final PermissionFactory permissionFactory; private final TxManager txManager; private final JobExecutionRepository jobExecutionRepository; public JobExecutionServiceImpl( AuthorizationService authorizationService, - PermissionFactory permissionFactory, TxManager txManager, JobExecutionRepository jobExecutionRepository) { this.authorizationService = authorizationService; - this.permissionFactory = permissionFactory; this.txManager = txManager; this.jobExecutionRepository = jobExecutionRepository; } @@ -59,11 +56,10 @@ public JobExecution create(JobExecutionCreator jobExecutionCreator) throws Kapua ArgumentValidator.notNull(jobExecutionCreator, "jobExecutionCreator"); ArgumentValidator.notNull(jobExecutionCreator.getScopeId(), "jobExecutionCreator.scopeId"); // Check access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.write, jobExecutionCreator.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.JOB, Actions.write, jobExecutionCreator.getScopeId())); JobExecution jobExecution = new JobExecutionImpl(jobExecutionCreator.getScopeId()); jobExecution.setJobId(jobExecutionCreator.getJobId()); jobExecution.setStartedOn(jobExecutionCreator.getStartedOn()); - jobExecution.setEntityAttributes(jobExecutionCreator.getEntityAttributes()); jobExecution.setTargetIds(jobExecutionCreator.getTargetIds()); // Do create return txManager.execute(tx -> jobExecutionRepository.create(tx, jobExecution)); @@ -75,7 +71,7 @@ public JobExecution update(JobExecution jobExecution) throws KapuaException { ArgumentValidator.notNull(jobExecution, "jobExecution"); ArgumentValidator.notNull(jobExecution.getScopeId(), "jobExecution.scopeId"); // Check access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.write, jobExecution.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.JOB, Actions.write, jobExecution.getScopeId())); return txManager.execute(tx -> jobExecutionRepository.update(tx, jobExecution)); } @@ -86,7 +82,7 @@ public JobExecution find(KapuaId scopeId, KapuaId jobExecutionId) throws KapuaEx ArgumentValidator.notNull(scopeId, "scopeId"); ArgumentValidator.notNull(jobExecutionId, "jobExecutionId"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.read, scopeId)); + authorizationService.checkPermission(new Permission(Domains.JOB, Actions.read, scopeId)); // Do find return txManager.execute(tx -> jobExecutionRepository.find(tx, scopeId, jobExecutionId)) .orElse(null); @@ -97,7 +93,7 @@ public JobExecutionListResult query(KapuaQuery query) throws KapuaException { // Argument Validation ArgumentValidator.notNull(query, "query"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.read, query.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.JOB, Actions.read, query.getScopeId())); // Do query return txManager.execute(tx -> jobExecutionRepository.query(tx, query)); } @@ -108,7 +104,7 @@ public long countByJobId(KapuaId scopeId, KapuaId jobId) throws KapuaException { ArgumentValidator.notNull(scopeId, "scopeId"); ArgumentValidator.notNull(jobId, "jobId"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.read, scopeId)); + authorizationService.checkPermission(new Permission(Domains.JOB, Actions.read, scopeId)); // Do find return txManager.execute(tx -> jobExecutionRepository.countByJobId(tx, scopeId, jobId)); } @@ -118,7 +114,7 @@ public long count(KapuaQuery query) throws KapuaException { // Argument Validation ArgumentValidator.notNull(query, "query"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.read, query.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.JOB, Actions.read, query.getScopeId())); // Do query return txManager.execute(tx -> jobExecutionRepository.count(tx, query)); } @@ -129,7 +125,7 @@ public void delete(KapuaId scopeId, KapuaId jobExecutionId) throws KapuaExceptio ArgumentValidator.notNull(scopeId, "scopeId"); ArgumentValidator.notNull(jobExecutionId, "jobExecutionId"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.delete, scopeId)); + authorizationService.checkPermission(new Permission(Domains.JOB, Actions.delete, scopeId)); // Do delete txManager.execute(tx -> jobExecutionRepository.delete(tx, scopeId, jobExecutionId)); } diff --git a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/internal/JobCreatorImpl.java b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/internal/JobCreatorImpl.java deleted file mode 100644 index e424806204c..00000000000 --- a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/internal/JobCreatorImpl.java +++ /dev/null @@ -1,63 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2017, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.job.internal; - -import org.eclipse.kapua.commons.model.AbstractKapuaNamedEntityCreator; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.job.Job; -import org.eclipse.kapua.service.job.JobCreator; -import org.eclipse.kapua.service.job.step.JobStep; - -import java.util.ArrayList; -import java.util.List; - -/** - * {@link JobCreator} implementation - * - * @since 1.0.0 - */ -public class JobCreatorImpl extends AbstractKapuaNamedEntityCreator implements JobCreator { - - private static final long serialVersionUID = 3119071638220738358L; - - private List jobSteps; - private String jobXmlDefinition; - - public JobCreatorImpl(KapuaId scopeId) { - super(scopeId); - } - - @Override - public List getJobSteps() { - if (jobSteps == null) { - jobSteps = new ArrayList<>(); - } - - return jobSteps; - } - - @Override - public void setJobSteps(List jobSteps) { - this.jobSteps = jobSteps; - } - - @Override - public String getJobXmlDefinition() { - return jobXmlDefinition; - } - - @Override - public void setJobXmlDefinition(String jobXmlDefinition) { - this.jobXmlDefinition = jobXmlDefinition; - } -} diff --git a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/internal/JobFactoryImpl.java b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/internal/JobFactoryImpl.java index 9f5c0ade8e5..d21d9da76e4 100644 --- a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/internal/JobFactoryImpl.java +++ b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/internal/JobFactoryImpl.java @@ -12,15 +12,12 @@ *******************************************************************************/ package org.eclipse.kapua.service.job.internal; +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaEntityCloneException; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.job.Job; -import org.eclipse.kapua.service.job.JobCreator; import org.eclipse.kapua.service.job.JobFactory; -import org.eclipse.kapua.service.job.JobListResult; -import org.eclipse.kapua.service.job.JobQuery; - -import javax.inject.Singleton; /** * {@link JobFactory} implementation. @@ -35,21 +32,6 @@ public Job newEntity(KapuaId scopeId) { return new JobImpl(scopeId); } - @Override - public JobCreator newCreator(KapuaId scopeId) { - return new JobCreatorImpl(scopeId); - } - - @Override - public JobQuery newQuery(KapuaId scopeId) { - return new JobQueryImpl(scopeId); - } - - @Override - public JobListResult newListResult() { - return new JobListResultImpl(); - } - @Override public Job clone(Job job) { try { diff --git a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/internal/JobImplJpaRepository.java b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/internal/JobImplJpaRepository.java index 14fcb9432b3..b4f61507844 100644 --- a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/internal/JobImplJpaRepository.java +++ b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/internal/JobImplJpaRepository.java @@ -23,6 +23,6 @@ public class JobImplJpaRepository implements JobRepository { public JobImplJpaRepository(KapuaJpaRepositoryConfiguration jpaRepoConfig) { - super(JobImpl.class, Job.TYPE, () -> new JobListResultImpl(), jpaRepoConfig); + super(JobImpl.class, Job.TYPE, () -> new JobListResult(), jpaRepoConfig); } } diff --git a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/internal/JobListResultImpl.java b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/internal/JobListResultImpl.java deleted file mode 100644 index 20e01878c1f..00000000000 --- a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/internal/JobListResultImpl.java +++ /dev/null @@ -1,28 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2017, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.job.internal; - -import org.eclipse.kapua.commons.model.query.KapuaListResultImpl; -import org.eclipse.kapua.service.job.Job; -import org.eclipse.kapua.service.job.JobListResult; - -/** - * {@link JobListResult} implementation. - * - * @since 1.0.0 - */ -public class JobListResultImpl extends KapuaListResultImpl implements JobListResult { - - private static final long serialVersionUID = -7466853155307881848L; - -} diff --git a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/internal/JobMatchPredicateImpl.java b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/internal/JobMatchPredicateImpl.java deleted file mode 100644 index 64257773f43..00000000000 --- a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/internal/JobMatchPredicateImpl.java +++ /dev/null @@ -1,37 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2020, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.job.internal; - -import org.eclipse.kapua.commons.model.query.predicate.AbstractMatchPredicate; -import org.eclipse.kapua.service.job.JobAttributes; -import org.eclipse.kapua.service.job.JobMatchPredicate; - -import java.util.Arrays; - -public class JobMatchPredicateImpl extends AbstractMatchPredicate implements JobMatchPredicate { - - /** - * Constructor. - * - * @param matchTerm - * @since 2.0.0 - */ - public JobMatchPredicateImpl(T matchTerm) { - this.attributeNames = Arrays.asList( - JobAttributes.NAME, - JobAttributes.DESCRIPTION - ); - this.matchTerm = matchTerm; - } - -} \ No newline at end of file diff --git a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/internal/JobModule.java b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/internal/JobModule.java index 2108b2af4df..b72bc487b81 100644 --- a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/internal/JobModule.java +++ b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/internal/JobModule.java @@ -27,7 +27,6 @@ import org.eclipse.kapua.model.domain.Domain; import org.eclipse.kapua.model.domain.DomainEntry; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; import org.eclipse.kapua.service.job.JobFactory; import org.eclipse.kapua.service.job.JobRepository; import org.eclipse.kapua.service.job.JobService; @@ -63,7 +62,6 @@ TxManager jobTxManager( JobService jobService( Map, ServiceConfigurationManager> serviceConfigurationManagersByServiceClass, JobEngineService jobEngineService, - PermissionFactory permissionFactory, AuthorizationService authorizationService, @Named("jobTxManager") TxManager txManager, JobRepository jobRepository, @@ -72,7 +70,6 @@ JobService jobService( return new JobServiceImpl( serviceConfigurationManagersByServiceClass.get(JobService.class), jobEngineService, - permissionFactory, authorizationService, txManager, jobRepository, diff --git a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/internal/JobQueryImpl.java b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/internal/JobQueryImpl.java deleted file mode 100644 index 4d9b095a7ca..00000000000 --- a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/internal/JobQueryImpl.java +++ /dev/null @@ -1,41 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2017, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.job.internal; - -import org.eclipse.kapua.commons.model.query.AbstractKapuaNamedQuery; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.job.JobMatchPredicate; -import org.eclipse.kapua.service.job.JobQuery; - -/** - * {@link JobQuery} implementation. - * - * @since 1.0.0 - */ -public class JobQueryImpl extends AbstractKapuaNamedQuery implements JobQuery { - - /** - * Constructor. - * - * @param scopeId The {@link #getScopeId()}. - * @since 1.0.0 - */ - public JobQueryImpl(KapuaId scopeId) { - super(scopeId); - } - - @Override - public JobMatchPredicate matchPredicate(T matchTerm) { - return new JobMatchPredicateImpl<>(matchTerm); - } -} diff --git a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/internal/JobServiceConfigurationManagerModule.java b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/internal/JobServiceConfigurationManagerModule.java index 9c81df96897..a2d3b44768a 100644 --- a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/internal/JobServiceConfigurationManagerModule.java +++ b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/internal/JobServiceConfigurationManagerModule.java @@ -29,7 +29,6 @@ import org.eclipse.kapua.commons.jpa.KapuaJpaRepositoryConfiguration; import org.eclipse.kapua.commons.model.domains.Domains; import org.eclipse.kapua.commons.util.xml.XmlUtil; -import org.eclipse.kapua.service.job.JobFactory; import org.eclipse.kapua.service.job.JobRepository; import org.eclipse.kapua.service.job.JobService; import org.eclipse.kapua.storage.TxManager; @@ -55,8 +54,6 @@ protected void configureModule() { @Singleton public ServiceConfigurationManager jobServiceConfigurationManager( @Named("jobTxManager") TxManager txManager, - - JobFactory factory, RootUserTester rootUserTester, AccountRelativeFinder accountRelativeFinder, JobRepository jobRepository, @@ -76,7 +73,6 @@ public ServiceConfigurationManager jobServiceConfigurationManager( rootUserTester, accountRelativeFinder, new UsedEntitiesCounterImpl( - factory, jobRepository ), new ResourceBasedServiceConfigurationMetadataProvider(xmlUtil))); diff --git a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/internal/JobServiceImpl.java b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/internal/JobServiceImpl.java index 2eae0dc119d..3d5b0b88b1b 100755 --- a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/internal/JobServiceImpl.java +++ b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/internal/JobServiceImpl.java @@ -12,6 +12,8 @@ *******************************************************************************/ package org.eclipse.kapua.service.job.internal; +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaDuplicateNameException; import org.eclipse.kapua.KapuaEntityNotFoundException; import org.eclipse.kapua.KapuaException; @@ -26,7 +28,7 @@ import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; +import org.eclipse.kapua.service.authorization.permission.Permission; import org.eclipse.kapua.service.job.Job; import org.eclipse.kapua.service.job.JobCreator; import org.eclipse.kapua.service.job.JobListResult; @@ -37,8 +39,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.inject.Singleton; - /** * {@link JobService} implementation * @@ -56,21 +56,21 @@ public class JobServiceImpl extends KapuaConfigurableServiceBase implements JobS /** * Default constructor for injection * - * @param permissionFactory The {@link PermissionFactory} instance - * @param authorizationService The {@link AuthorizationService} instance + * @param authorizationService + * The {@link AuthorizationService} instance * @param jobRepository - * @param triggerService The {@link TriggerService} instance + * @param triggerService + * The {@link TriggerService} instance * @since 2.0.0 */ public JobServiceImpl( ServiceConfigurationManager serviceConfigurationManager, JobEngineService jobEngineService, - PermissionFactory permissionFactory, AuthorizationService authorizationService, TxManager txManager, JobRepository jobRepository, TriggerService triggerService) { - super(txManager, serviceConfigurationManager, Domains.JOB, authorizationService, permissionFactory); + super(txManager, serviceConfigurationManager, Domains.JOB, authorizationService); this.jobEngineService = jobEngineService; this.jobRepository = jobRepository; this.triggerService = triggerService; @@ -83,7 +83,7 @@ public Job create(JobCreator creator) throws KapuaException { ArgumentValidator.notNull(creator.getScopeId(), "jobCreator.scopeId"); ArgumentValidator.validateEntityName(creator.getName(), "jobCreator.name"); // Check access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.write, creator.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.JOB, Actions.write, creator.getScopeId())); return txManager.execute(tx -> { // Check entity limit serviceConfigurationManager.checkAllowedEntities(tx, creator.getScopeId(), "Jobs"); @@ -107,7 +107,7 @@ public Job update(Job job) throws KapuaException { ArgumentValidator.notNull(job.getScopeId(), "job.scopeId"); ArgumentValidator.validateEntityName(job.getName(), "job.name"); // Check access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.write, job.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.JOB, Actions.write, job.getScopeId())); return txManager.execute(tx -> { // Check existence @@ -129,7 +129,7 @@ public Job find(KapuaId scopeId, KapuaId jobId) throws KapuaException { ArgumentValidator.notNull(scopeId, "scopeId"); ArgumentValidator.notNull(jobId, KapuaEntityAttributes.ENTITY_ID); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.read, scopeId)); + authorizationService.checkPermission(new Permission(Domains.JOB, Actions.read, scopeId)); // Do find return txManager.execute(tx -> jobRepository.find(tx, scopeId, jobId)) .orElse(null); @@ -140,7 +140,7 @@ public JobListResult query(KapuaQuery query) throws KapuaException { // Argument Validation ArgumentValidator.notNull(query, "query"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.read, query.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.JOB, Actions.read, query.getScopeId())); // Do query return txManager.execute(tx -> jobRepository.query(tx, query)); } @@ -150,7 +150,7 @@ public long count(KapuaQuery query) throws KapuaException { // Argument Validation ArgumentValidator.notNull(query, "query"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.read, query.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.JOB, Actions.read, query.getScopeId())); // Do query return txManager.execute(tx -> jobRepository.count(tx, query)); } @@ -169,13 +169,17 @@ public void deleteForced(KapuaId scopeId, KapuaId jobId) throws KapuaException { /** * Deletes the {@link Job} like {@link #delete(KapuaId, KapuaId)}. *

        - * If {@code forced} is {@code true} {@link org.eclipse.kapua.service.authorization.permission.Permission} checked will be {@code job:delete:null}, - * and when invoking {@link JobEngineService#cleanJobData(KapuaId, KapuaId)} any exception is logged and ignored. + * If {@code forced} is {@code true} {@link org.eclipse.kapua.service.authorization.permission.Permission} checked will be {@code job:delete:null}, and when invoking + * {@link JobEngineService#cleanJobData(KapuaId, KapuaId)} any exception is logged and ignored. * - * @param scopeId The {@link KapuaId} scopeId of the {@link Job}. - * @param jobId The {@link KapuaId} of the {@link Job}. - * @param forced Whether or not the {@link Job} must be forcibly deleted. - * @throws KapuaException In case something bad happens. + * @param scopeId + * The {@link KapuaId} scopeId of the {@link Job}. + * @param jobId + * The {@link KapuaId} of the {@link Job}. + * @param forced + * Whether or not the {@link Job} must be forcibly deleted. + * @throws KapuaException + * In case something bad happens. * @since 1.1.0 */ private void deleteInternal(KapuaId scopeId, KapuaId jobId, boolean forced) throws KapuaException { @@ -183,7 +187,7 @@ private void deleteInternal(KapuaId scopeId, KapuaId jobId, boolean forced) thro ArgumentValidator.notNull(scopeId, "scopeId"); ArgumentValidator.notNull(jobId, KapuaEntityAttributes.ENTITY_ID); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.delete, forced ? null : scopeId)); + authorizationService.checkPermission(new Permission(Domains.JOB, Actions.delete, forced ? null : scopeId)); txManager.execute(tx -> { // Check existence diff --git a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/step/definition/internal/JobStepDefinitionAligner.java b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/step/definition/internal/JobStepDefinitionAligner.java index 30c7818bc74..6357f515446 100644 --- a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/step/definition/internal/JobStepDefinitionAligner.java +++ b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/step/definition/internal/JobStepDefinitionAligner.java @@ -30,6 +30,7 @@ import org.eclipse.kapua.locator.initializers.KapuaInitializingMethod; import org.eclipse.kapua.model.KapuaNamedEntity; import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.service.job.step.definition.JobStepDefinition; import org.eclipse.kapua.service.job.step.definition.JobStepDefinitionRepository; import org.eclipse.kapua.service.job.step.definition.JobStepProperty; @@ -100,7 +101,7 @@ public void populate() { KapuaSecurityUtils.doPrivileged(() -> { txManager.execute(tx -> { // Retrieve all JobStepDefinition from the database - List dbJobStepDefinitions = jobStepDefinitionRepository.query(tx, new JobStepDefinitionQueryImpl(null)).getItems() + List dbJobStepDefinitions = jobStepDefinitionRepository.query(tx, new KapuaQuery((KapuaId) null)).getItems() .stream() .map(dbJobStepDefinition -> (JobStepDefinitionImpl) dbJobStepDefinition) .collect(Collectors.toList()); diff --git a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/step/definition/internal/JobStepDefinitionCreatorImpl.java b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/step/definition/internal/JobStepDefinitionCreatorImpl.java deleted file mode 100644 index 61823f3ef72..00000000000 --- a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/step/definition/internal/JobStepDefinitionCreatorImpl.java +++ /dev/null @@ -1,98 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2017, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.job.step.definition.internal; - -import org.eclipse.kapua.commons.model.AbstractKapuaNamedEntityCreator; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.job.step.definition.JobStepDefinition; -import org.eclipse.kapua.service.job.step.definition.JobStepDefinitionCreator; -import org.eclipse.kapua.service.job.step.definition.JobStepProperty; -import org.eclipse.kapua.service.job.step.definition.JobStepType; - -import java.util.ArrayList; -import java.util.List; - -/** - * {@link JobStepDefinitionCreator} implementation - * - * @since 1.0.0 - */ -public class JobStepDefinitionCreatorImpl extends AbstractKapuaNamedEntityCreator implements JobStepDefinitionCreator { - - private static final long serialVersionUID = 4602067255120049746L; - - private JobStepType jobStepType; - private String readerName; - private String processorName; - private String writerName; - private List jobStepProperties; - - public JobStepDefinitionCreatorImpl(KapuaId scopeId) { - super(scopeId); - } - - @Override - public JobStepType getStepType() { - return jobStepType; - } - - @Override - public void setStepType(JobStepType jobStepType) { - this.jobStepType = jobStepType; - } - - @Override - public String getReaderName() { - return readerName; - } - - @Override - public void setReaderName(String readerName) { - this.readerName = readerName; - } - - @Override - public String getProcessorName() { - return processorName; - } - - @Override - public void setProcessorName(String processorName) { - this.processorName = processorName; - } - - @Override - public String getWriterName() { - return writerName; - } - - @Override - public void setWriterName(String writerName) { - this.writerName = writerName; - } - - @Override - public List getStepProperties() { - if (jobStepProperties == null) { - jobStepProperties = new ArrayList<>(); - } - - return jobStepProperties; - } - - @Override - public void setStepProperties(List jobStepProperties) { - this.jobStepProperties = jobStepProperties; - } - -} diff --git a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/step/definition/internal/JobStepDefinitionFactoryImpl.java b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/step/definition/internal/JobStepDefinitionFactoryImpl.java index 6363e60b085..e43dfb3e77e 100644 --- a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/step/definition/internal/JobStepDefinitionFactoryImpl.java +++ b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/step/definition/internal/JobStepDefinitionFactoryImpl.java @@ -17,10 +17,7 @@ import org.eclipse.kapua.KapuaEntityCloneException; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.job.step.definition.JobStepDefinition; -import org.eclipse.kapua.service.job.step.definition.JobStepDefinitionCreator; import org.eclipse.kapua.service.job.step.definition.JobStepDefinitionFactory; -import org.eclipse.kapua.service.job.step.definition.JobStepDefinitionListResult; -import org.eclipse.kapua.service.job.step.definition.JobStepDefinitionQuery; import org.eclipse.kapua.service.job.step.definition.JobStepProperty; /** @@ -36,21 +33,6 @@ public JobStepDefinition newEntity(KapuaId scopeId) { return new JobStepDefinitionImpl(scopeId); } - @Override - public JobStepDefinitionCreator newCreator(KapuaId scopeId) { - return new JobStepDefinitionCreatorImpl(scopeId); - } - - @Override - public JobStepDefinitionQuery newQuery(KapuaId scopeId) { - return new JobStepDefinitionQueryImpl(scopeId); - } - - @Override - public JobStepDefinitionListResult newListResult() { - return new JobStepDefinitionListResultImpl(); - } - @Override public JobStepProperty newStepProperty(String name, String type, String value) { return new JobStepPropertyImpl(name, type, value, null); diff --git a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/step/definition/internal/JobStepDefinitionImplJpaRepository.java b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/step/definition/internal/JobStepDefinitionImplJpaRepository.java index 484085a0538..9614d08874e 100644 --- a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/step/definition/internal/JobStepDefinitionImplJpaRepository.java +++ b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/step/definition/internal/JobStepDefinitionImplJpaRepository.java @@ -23,7 +23,7 @@ public class JobStepDefinitionImplJpaRepository implements JobStepDefinitionRepository { public JobStepDefinitionImplJpaRepository(KapuaJpaRepositoryConfiguration jpaRepoConfig) { - super(JobStepDefinitionImpl.class, JobStepDefinition.TYPE, () -> new JobStepDefinitionListResultImpl(), jpaRepoConfig); + super(JobStepDefinitionImpl.class, JobStepDefinition.TYPE, () -> new JobStepDefinitionListResult(), jpaRepoConfig); } } diff --git a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/step/definition/internal/JobStepDefinitionListResultImpl.java b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/step/definition/internal/JobStepDefinitionListResultImpl.java deleted file mode 100644 index d829517d144..00000000000 --- a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/step/definition/internal/JobStepDefinitionListResultImpl.java +++ /dev/null @@ -1,29 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2017, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.job.step.definition.internal; - -import org.eclipse.kapua.commons.model.query.KapuaListResultImpl; -import org.eclipse.kapua.service.job.step.definition.JobStepDefinition; -import org.eclipse.kapua.service.job.step.definition.JobStepDefinitionListResult; - -/** - * {@link JobStepDefinitionListResult} definition. - * - * @since 1.0.0 - * - */ -public class JobStepDefinitionListResultImpl extends KapuaListResultImpl implements JobStepDefinitionListResult { - - private static final long serialVersionUID = 977813250632719295L; - -} diff --git a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/step/definition/internal/JobStepDefinitionModule.java b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/step/definition/internal/JobStepDefinitionModule.java index 74ae4c7c3be..44908947471 100644 --- a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/step/definition/internal/JobStepDefinitionModule.java +++ b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/step/definition/internal/JobStepDefinitionModule.java @@ -12,20 +12,21 @@ *******************************************************************************/ package org.eclipse.kapua.service.job.step.definition.internal; -import com.google.inject.Provides; +import javax.inject.Inject; +import javax.inject.Named; + import org.eclipse.kapua.commons.core.AbstractKapuaModule; import org.eclipse.kapua.commons.jpa.KapuaJpaRepositoryConfiguration; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; import org.eclipse.kapua.service.job.step.definition.JobStepDefinitionFactory; import org.eclipse.kapua.service.job.step.definition.JobStepDefinitionRepository; import org.eclipse.kapua.service.job.step.definition.JobStepDefinitionService; import org.eclipse.kapua.storage.TxManager; -import javax.inject.Inject; -import javax.inject.Named; +import com.google.inject.Provides; public class JobStepDefinitionModule extends AbstractKapuaModule { + @Override protected void configureModule() { bind(JobStepDefinitionFactory.class).to(JobStepDefinitionFactoryImpl.class); @@ -38,12 +39,10 @@ protected void configureModule() { @Inject JobStepDefinitionService jobStepDefinitionService( AuthorizationService authorizationService, - PermissionFactory permissionFactory, @Named("jobTxManager") TxManager txManager, JobStepDefinitionRepository repository) { return new JobStepDefinitionServiceImpl( authorizationService, - permissionFactory, txManager, repository ); diff --git a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/step/definition/internal/JobStepDefinitionQueryImpl.java b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/step/definition/internal/JobStepDefinitionQueryImpl.java deleted file mode 100644 index 300924d51e7..00000000000 --- a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/step/definition/internal/JobStepDefinitionQueryImpl.java +++ /dev/null @@ -1,48 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2017, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.job.step.definition.internal; - -import org.eclipse.kapua.commons.model.query.AbstractKapuaNamedQuery; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.job.step.definition.JobStepDefinition; -import org.eclipse.kapua.service.job.step.definition.JobStepDefinitionQuery; - -/** - * {@link JobStepDefinitionQuery} definition. - * - * @since 1.0.0 - */ -public class JobStepDefinitionQueryImpl extends AbstractKapuaNamedQuery implements JobStepDefinitionQuery { - - /** - * Constructor. - * - * @param scopeId - * The {@link #getScopeId()}. - * @since 1.0.0 - */ - public JobStepDefinitionQueryImpl(KapuaId scopeId) { - super(scopeId); - } - - /** - * This enables {@link JobStepDefinitionQuery} to retrieve also not scoped {@link JobStepDefinition}s since they are public. - * - * @return {@code true} - * @since 2.0.0 - */ - @Override - public boolean getNotScopedEntities() { - return true; - } -} diff --git a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/step/definition/internal/JobStepDefinitionServiceImpl.java b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/step/definition/internal/JobStepDefinitionServiceImpl.java index 2458ec68fbf..f8f332650d2 100755 --- a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/step/definition/internal/JobStepDefinitionServiceImpl.java +++ b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/step/definition/internal/JobStepDefinitionServiceImpl.java @@ -13,6 +13,7 @@ package org.eclipse.kapua.service.job.step.definition.internal; import java.util.Optional; + import javax.inject.Singleton; import org.eclipse.kapua.KapuaDuplicateNameInAnotherAccountError; @@ -23,7 +24,7 @@ import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; +import org.eclipse.kapua.service.authorization.permission.Permission; import org.eclipse.kapua.service.job.step.definition.JobStepDefinition; import org.eclipse.kapua.service.job.step.definition.JobStepDefinitionAttributes; import org.eclipse.kapua.service.job.step.definition.JobStepDefinitionCreator; @@ -42,17 +43,14 @@ public class JobStepDefinitionServiceImpl implements JobStepDefinitionService { private final AuthorizationService authorizationService; - private final PermissionFactory permissionFactory; private final TxManager txManager; private final JobStepDefinitionRepository repository; public JobStepDefinitionServiceImpl( AuthorizationService authorizationService, - PermissionFactory permissionFactory, TxManager txManager, JobStepDefinitionRepository repository) { this.authorizationService = authorizationService; - this.permissionFactory = permissionFactory; this.txManager = txManager; this.repository = repository; } @@ -66,7 +64,7 @@ public JobStepDefinition create(JobStepDefinitionCreator stepDefinitionCreator) ArgumentValidator.validateEntityName(stepDefinitionCreator.getName(), "stepDefinitionCreator.name"); ArgumentValidator.notEmptyOrNull(stepDefinitionCreator.getProcessorName(), "stepDefinitionCreator.processorName"); // Check access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.write, null)); + authorizationService.checkPermission(new Permission(Domains.JOB, Actions.write, null)); return txManager.execute(tx -> { // Check duplicate name @@ -98,7 +96,7 @@ public JobStepDefinition update(JobStepDefinition jobStepDefinition) throws Kapu ArgumentValidator.notEmptyOrNull(jobStepDefinition.getProcessorName(), "jobStepDefinition.processorName"); // Check access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.write, null)); + authorizationService.checkPermission(new Permission(Domains.JOB, Actions.write, null)); return txManager.execute(tx -> { // Check duplicate name @@ -118,9 +116,9 @@ public JobStepDefinition find(KapuaId scopeId, KapuaId stepDefinitionId) throws ArgumentValidator.notNull(stepDefinitionId, "stepDefinitionId"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.read, scopeId)); + authorizationService.checkPermission(new Permission(Domains.JOB, Actions.read, scopeId)); - final JobStepDefinitionQuery query = new JobStepDefinitionQueryImpl(scopeId); + final JobStepDefinitionQuery query = new JobStepDefinitionQuery(scopeId); query.setPredicate(query.attributePredicate(JobStepDefinitionAttributes.ENTITY_ID, stepDefinitionId)); // Do find @@ -137,7 +135,7 @@ public JobStepDefinition findByName(String name) throws KapuaException { Optional jobStepDefinition = repository.findByName(tx, name); if (jobStepDefinition.isPresent()) { // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.read, jobStepDefinition.get().getScopeId())); + authorizationService.checkPermission(new Permission(Domains.JOB, Actions.read, jobStepDefinition.get().getScopeId())); } return jobStepDefinition; }).orElse(null); @@ -148,7 +146,7 @@ public JobStepDefinitionListResult query(KapuaQuery query) throws KapuaException // Argument Validation ArgumentValidator.notNull(query, "query"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.read, query.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.JOB, Actions.read, query.getScopeId())); // Do query return txManager.execute(tx -> repository.query(tx, query)); } @@ -158,7 +156,7 @@ public long count(KapuaQuery query) throws KapuaException { // Argument Validation ArgumentValidator.notNull(query, "query"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.read, query.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.JOB, Actions.read, query.getScopeId())); // Do query return txManager.execute(tx -> repository.count(tx, query)); } @@ -169,7 +167,7 @@ public void delete(KapuaId scopeId, KapuaId stepDefinitionId) throws KapuaExcept ArgumentValidator.notNull(scopeId, "scopeId"); ArgumentValidator.notNull(stepDefinitionId, "stepDefinitionId"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.delete, null)); + authorizationService.checkPermission(new Permission(Domains.JOB, Actions.delete, null)); // Do delete txManager.execute(tx -> repository.delete(tx, scopeId, stepDefinitionId)); } diff --git a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/step/internal/JobStepCreatorImpl.java b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/step/internal/JobStepCreatorImpl.java deleted file mode 100644 index b7ac041c9bf..00000000000 --- a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/step/internal/JobStepCreatorImpl.java +++ /dev/null @@ -1,86 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2017, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.job.step.internal; - -import org.eclipse.kapua.commons.model.AbstractKapuaNamedEntityCreator; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.job.step.JobStep; -import org.eclipse.kapua.service.job.step.JobStepCreator; -import org.eclipse.kapua.service.job.step.definition.JobStepProperty; - -import java.util.ArrayList; -import java.util.List; - -/** - * {@link JobStepCreator} implementation - * - * @since 1.0.0 - */ -public class JobStepCreatorImpl extends AbstractKapuaNamedEntityCreator implements JobStepCreator { - - private static final long serialVersionUID = 3119071638220738358L; - - private KapuaId jobId; - private Integer stepIndex; - private KapuaId jobStepDefinitionId; - private List jobStepProperty; - - public JobStepCreatorImpl(KapuaId scopeId) { - super(scopeId); - } - - @Override - public KapuaId getJobId() { - return jobId; - } - - @Override - public void setJobId(KapuaId jobId) { - this.jobId = jobId; - } - - @Override - public Integer getStepIndex() { - return stepIndex; - } - - @Override - public void setStepIndex(Integer stepIndex) { - this.stepIndex = stepIndex; - } - - @Override - public KapuaId getJobStepDefinitionId() { - return jobStepDefinitionId; - } - - @Override - public void setJobStepDefinitionId(KapuaId jobStepDefinitionId) { - this.jobStepDefinitionId = jobStepDefinitionId; - } - - @Override - public List getStepProperties() { - if (jobStepProperty == null) { - jobStepProperty = new ArrayList<>(); - } - - return jobStepProperty; - } - - @Override - public void setStepProperties(List jobStepProperty) { - this.jobStepProperty = jobStepProperty; - } - -} diff --git a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/step/internal/JobStepFactoryImpl.java b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/step/internal/JobStepFactoryImpl.java index acab84ae774..40c77226ced 100644 --- a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/step/internal/JobStepFactoryImpl.java +++ b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/step/internal/JobStepFactoryImpl.java @@ -16,10 +16,7 @@ import org.eclipse.kapua.KapuaEntityCloneException; import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.job.step.JobStepCreator; import org.eclipse.kapua.service.job.step.JobStepFactory; -import org.eclipse.kapua.service.job.step.JobStepListResult; -import org.eclipse.kapua.service.job.step.JobStepQuery; import org.eclipse.kapua.service.job.step.definition.JobStepProperty; import org.eclipse.kapua.service.job.step.definition.internal.JobStepPropertyImpl; @@ -36,21 +33,6 @@ public org.eclipse.kapua.service.job.step.JobStep newEntity(KapuaId scopeId) { return new JobStepImpl(scopeId); } - @Override - public JobStepCreator newCreator(KapuaId scopeId) { - return new JobStepCreatorImpl(scopeId); - } - - @Override - public JobStepQuery newQuery(KapuaId scopeId) { - return new JobStepQueryImpl(scopeId); - } - - @Override - public JobStepListResult newListResult() { - return new JobStepListResultImpl(); - } - @Override public JobStepProperty newStepProperty(String name, String propertyType, String propertyValue) { return new JobStepPropertyImpl(name, propertyType, propertyValue, null); diff --git a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/step/internal/JobStepImplJpaRepository.java b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/step/internal/JobStepImplJpaRepository.java index a92003a6358..c0c9201c1cf 100644 --- a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/step/internal/JobStepImplJpaRepository.java +++ b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/step/internal/JobStepImplJpaRepository.java @@ -26,8 +26,9 @@ public class JobStepImplJpaRepository extends KapuaNamedEntityJpaRepository implements JobStepRepository { + public JobStepImplJpaRepository(KapuaJpaRepositoryConfiguration jpaRepoConfig) { - super(JobStepImpl.class, JobStep.TYPE, () -> new JobStepListResultImpl(), jpaRepoConfig); + super(JobStepImpl.class, JobStep.TYPE, () -> new JobStepListResult(), jpaRepoConfig); } @Override diff --git a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/step/internal/JobStepListResultImpl.java b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/step/internal/JobStepListResultImpl.java deleted file mode 100644 index 4ce385b5462..00000000000 --- a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/step/internal/JobStepListResultImpl.java +++ /dev/null @@ -1,28 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2017, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.job.step.internal; - -import org.eclipse.kapua.commons.model.query.KapuaListResultImpl; -import org.eclipse.kapua.service.job.step.JobStep; -import org.eclipse.kapua.service.job.step.JobStepListResult; - -/** - * {@link JobStepListResult} implementation. - * - * @since 1.0.0 - */ -public class JobStepListResultImpl extends KapuaListResultImpl implements JobStepListResult { - - private static final long serialVersionUID = -7466853155307881848L; - -} diff --git a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/step/internal/JobStepModule.java b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/step/internal/JobStepModule.java index feef46165be..bfaab7faa88 100644 --- a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/step/internal/JobStepModule.java +++ b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/step/internal/JobStepModule.java @@ -17,12 +17,8 @@ import org.eclipse.kapua.commons.core.AbstractKapuaModule; import org.eclipse.kapua.commons.jpa.KapuaJpaRepositoryConfiguration; -import org.eclipse.kapua.commons.jpa.KapuaJpaTxManagerFactory; import org.eclipse.kapua.commons.util.xml.XmlUtil; -import org.eclipse.kapua.model.query.QueryFactory; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; -import org.eclipse.kapua.service.job.execution.JobExecutionFactory; import org.eclipse.kapua.service.job.execution.JobExecutionService; import org.eclipse.kapua.service.job.step.JobStepFactory; import org.eclipse.kapua.service.job.step.JobStepRepository; @@ -48,23 +44,17 @@ JobStepRepository jobStepRepository(KapuaJpaRepositoryConfiguration jpaRepoConfi @Provides @Singleton JobStepService jobStepService(AuthorizationService authorizationService, - PermissionFactory permissionFactory, @Named("jobTxManager") TxManager txManager, JobStepRepository jobStepRepository, JobStepFactory jobStepFactory, JobExecutionService jobExecutionService, - JobExecutionFactory jobExecutionFactory, JobStepDefinitionRepository jobStepDefinitionRepository, - QueryFactory queryFactory, - KapuaJpaTxManagerFactory jpaTxManagerFactory, XmlUtil xmlUtil) { return new JobStepServiceImpl(authorizationService, - permissionFactory, txManager, jobStepRepository, jobStepFactory, jobExecutionService, - jobExecutionFactory, jobStepDefinitionRepository, xmlUtil ); diff --git a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/step/internal/JobStepQueryImpl.java b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/step/internal/JobStepQueryImpl.java deleted file mode 100644 index 1f1123f3877..00000000000 --- a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/step/internal/JobStepQueryImpl.java +++ /dev/null @@ -1,35 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2017, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.job.step.internal; - -import org.eclipse.kapua.commons.model.query.AbstractKapuaNamedQuery; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.job.step.JobStepQuery; - -/** - * {@link JobStepQuery} definition. - * - * @since 1.0.0 - */ -public class JobStepQueryImpl extends AbstractKapuaNamedQuery implements JobStepQuery { - - /** - * Constructor. - * - * @param scopeId The {@link #getScopeId()}. - * @since 1.0.0 - */ - public JobStepQueryImpl(KapuaId scopeId) { - super(scopeId); - } -} diff --git a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/step/internal/JobStepServiceImpl.java b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/step/internal/JobStepServiceImpl.java index ead07713317..e5606f66bd8 100644 --- a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/step/internal/JobStepServiceImpl.java +++ b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/step/internal/JobStepServiceImpl.java @@ -14,10 +14,10 @@ import java.util.List; import java.util.regex.Pattern; + import javax.inject.Singleton; import javax.xml.bind.DatatypeConverter; -import com.google.common.base.Strings; import org.eclipse.kapua.KapuaDuplicateNameException; import org.eclipse.kapua.KapuaEntityNotFoundException; import org.eclipse.kapua.KapuaException; @@ -33,10 +33,9 @@ import org.eclipse.kapua.model.query.SortOrder; import org.eclipse.kapua.model.query.predicate.AttributePredicate.Operator; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; +import org.eclipse.kapua.service.authorization.permission.Permission; import org.eclipse.kapua.service.job.exception.CannotModifyJobStepsException; import org.eclipse.kapua.service.job.execution.JobExecutionAttributes; -import org.eclipse.kapua.service.job.execution.JobExecutionFactory; import org.eclipse.kapua.service.job.execution.JobExecutionQuery; import org.eclipse.kapua.service.job.execution.JobExecutionService; import org.eclipse.kapua.service.job.internal.settings.JobServiceSettingKeys; @@ -47,7 +46,6 @@ import org.eclipse.kapua.service.job.step.JobStepFactory; import org.eclipse.kapua.service.job.step.JobStepIndex; import org.eclipse.kapua.service.job.step.JobStepListResult; -import org.eclipse.kapua.service.job.step.JobStepQuery; import org.eclipse.kapua.service.job.step.JobStepRepository; import org.eclipse.kapua.service.job.step.JobStepService; import org.eclipse.kapua.service.job.step.definition.JobStepDefinition; @@ -57,6 +55,8 @@ import org.eclipse.kapua.storage.TxManager; import org.slf4j.LoggerFactory; +import com.google.common.base.Strings; + /** * {@link JobStepService} implementation. * @@ -66,32 +66,26 @@ public class JobStepServiceImpl implements JobStepService { private final AuthorizationService authorizationService; - private final PermissionFactory permissionFactory; private final TxManager txManager; private final JobStepRepository jobStepRepository; private final JobStepFactory jobStepFactory; private final JobExecutionService jobExecutionService; - private final JobExecutionFactory jobExecutionFactory; private final JobStepDefinitionRepository jobStepDefinitionRepository; private final XmlUtil xmlUtil; public JobStepServiceImpl( AuthorizationService authorizationService, - PermissionFactory permissionFactory, TxManager txManager, JobStepRepository jobStepRepository, JobStepFactory jobStepFactory, JobExecutionService jobExecutionService, - JobExecutionFactory jobExecutionFactory, JobStepDefinitionRepository jobStepDefinitionRepository, XmlUtil xmlUtil) { this.authorizationService = authorizationService; - this.permissionFactory = permissionFactory; this.txManager = txManager; this.jobStepRepository = jobStepRepository; this.jobStepFactory = jobStepFactory; this.jobExecutionService = jobExecutionService; - this.jobExecutionFactory = jobExecutionFactory; this.jobStepDefinitionRepository = jobStepDefinitionRepository; this.xmlUtil = xmlUtil; } @@ -124,7 +118,7 @@ public JobStep create(JobStepCreator jobStepCreator) throws KapuaException { ArgumentValidator.numRange(jobStepCreator.getDescription().length(), 0, 8192, "jobStepCreator.description"); } // Check access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.write, jobStepCreator.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.JOB, Actions.write, jobStepCreator.getScopeId())); return txManager.execute(tx -> { // Check job step definition @@ -143,7 +137,7 @@ public JobStep create(JobStepCreator jobStepCreator) throws KapuaException { throw new CannotModifyJobStepsException(jobStepCreator.getJobId()); } // Populate JobStepCreator.stepIndex if not specified - final JobStepQuery query = new JobStepQueryImpl(jobStepCreator.getScopeId()); + final KapuaQuery query = new KapuaQuery(jobStepCreator.getScopeId()); if (jobStepCreator.getStepIndex() == null) { query.setPredicate(query.attributePredicate(JobStepAttributes.JOB_ID, jobStepCreator.getJobId())); query.setSortCriteria(query.fieldSortCriteria(JobStepAttributes.STEP_INDEX, SortOrder.DESCENDING)); @@ -155,7 +149,7 @@ public JobStep create(JobStepCreator jobStepCreator) throws KapuaException { jobStepCreator.setStepIndex(lastJobStep != null ? lastJobStep.getStepIndex() + 1 : JobStepIndex.FIRST); } // Check if JobStep.stepIndex is duplicate. - JobStepQuery jobStepQuery = new JobStepQueryImpl(jobStepCreator.getScopeId()); + KapuaQuery jobStepQuery = new KapuaQuery(jobStepCreator.getScopeId()); jobStepQuery.setPredicate( jobStepQuery.andPredicate( jobStepQuery.attributePredicate(JobStepAttributes.JOB_ID, jobStepCreator.getJobId()), @@ -168,15 +162,15 @@ public JobStep create(JobStepCreator jobStepCreator) throws KapuaException { if (jobStepAtIndex != null) { // JobStepCreator inserted between existing JobSteps. // Moving existing JobSteps + 1 - JobStepQuery selectorJobStepQuery = new JobStepQueryImpl(jobStepAtIndex.getScopeId()); - selectorJobStepQuery.setPredicate( - selectorJobStepQuery.andPredicate( - selectorJobStepQuery.attributePredicate(JobStepAttributes.JOB_ID, jobStepAtIndex.getJobId()), - selectorJobStepQuery.attributePredicate(JobStepAttributes.STEP_INDEX, jobStepAtIndex.getStepIndex(), Operator.GREATER_THAN_OR_EQUAL) + KapuaQuery selectorKapuaQuery = new KapuaQuery(jobStepAtIndex.getScopeId()); + selectorKapuaQuery.setPredicate( + selectorKapuaQuery.andPredicate( + selectorKapuaQuery.attributePredicate(JobStepAttributes.JOB_ID, jobStepAtIndex.getJobId()), + selectorKapuaQuery.attributePredicate(JobStepAttributes.STEP_INDEX, jobStepAtIndex.getStepIndex(), Operator.GREATER_THAN_OR_EQUAL) ) ); - shiftJobStepPosition(tx, selectorJobStepQuery, +1); + shiftJobStepPosition(tx, selectorKapuaQuery, +1); } // Create JobStep JobStep jobStep = jobStepFactory.newEntity(jobStepCreator.getScopeId()); @@ -210,7 +204,7 @@ public JobStep update(JobStep jobStep) throws KapuaException { ArgumentValidator.numRange(jobStep.getDescription().length(), 0, 8192, "jobStep.description"); } // Check access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.write, jobStep.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.JOB, Actions.write, jobStep.getScopeId())); return txManager.execute(tx -> { // Check existence @@ -240,29 +234,29 @@ public JobStep update(JobStep jobStep) throws KapuaException { if (jobStep.getStepIndex() < currentJobStep.getStepIndex()) { // Moved before current position. // Shift JobSteps +1 - JobStepQuery selectorJobStepQuery = new JobStepQueryImpl(jobStep.getScopeId()); - selectorJobStepQuery.setPredicate( - selectorJobStepQuery.andPredicate( - selectorJobStepQuery.attributePredicate(JobStepAttributes.JOB_ID, jobStep.getJobId()), - selectorJobStepQuery.attributePredicate(JobStepAttributes.STEP_INDEX, jobStep.getStepIndex(), Operator.GREATER_THAN_OR_EQUAL), - selectorJobStepQuery.attributePredicate(JobStepAttributes.STEP_INDEX, currentJobStep.getStepIndex(), Operator.LESS_THAN) + KapuaQuery selectorKapuaQuery = new KapuaQuery(jobStep.getScopeId()); + selectorKapuaQuery.setPredicate( + selectorKapuaQuery.andPredicate( + selectorKapuaQuery.attributePredicate(JobStepAttributes.JOB_ID, jobStep.getJobId()), + selectorKapuaQuery.attributePredicate(JobStepAttributes.STEP_INDEX, jobStep.getStepIndex(), Operator.GREATER_THAN_OR_EQUAL), + selectorKapuaQuery.attributePredicate(JobStepAttributes.STEP_INDEX, currentJobStep.getStepIndex(), Operator.LESS_THAN) ) ); - shiftJobStepPosition(tx, selectorJobStepQuery, +1); + shiftJobStepPosition(tx, selectorKapuaQuery, +1); } else { // Moved after current position. // Shift JobSteps -1 - JobStepQuery selectorJobStepQuery = new JobStepQueryImpl(jobStep.getScopeId()); - selectorJobStepQuery.setPredicate( - selectorJobStepQuery.andPredicate( - selectorJobStepQuery.attributePredicate(JobStepAttributes.JOB_ID, jobStep.getJobId()), - selectorJobStepQuery.attributePredicate(JobStepAttributes.STEP_INDEX, currentJobStep.getStepIndex(), Operator.GREATER_THAN), - selectorJobStepQuery.attributePredicate(JobStepAttributes.STEP_INDEX, jobStep.getStepIndex(), Operator.LESS_THAN_OR_EQUAL) + KapuaQuery selectorKapuaQuery = new KapuaQuery(jobStep.getScopeId()); + selectorKapuaQuery.setPredicate( + selectorKapuaQuery.andPredicate( + selectorKapuaQuery.attributePredicate(JobStepAttributes.JOB_ID, jobStep.getJobId()), + selectorKapuaQuery.attributePredicate(JobStepAttributes.STEP_INDEX, currentJobStep.getStepIndex(), Operator.GREATER_THAN), + selectorKapuaQuery.attributePredicate(JobStepAttributes.STEP_INDEX, jobStep.getStepIndex(), Operator.LESS_THAN_OR_EQUAL) ) ); - shiftJobStepPosition(tx, selectorJobStepQuery, -1); + shiftJobStepPosition(tx, selectorKapuaQuery, -1); } } @@ -277,7 +271,7 @@ public JobStep find(KapuaId scopeId, KapuaId jobStepId) throws KapuaException { ArgumentValidator.notNull(scopeId, "scopeId"); ArgumentValidator.notNull(jobStepId, "jobStepId"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.write, scopeId)); + authorizationService.checkPermission(new Permission(Domains.JOB, Actions.write, scopeId)); // Do find return txManager.execute(tx -> jobStepRepository.find(tx, scopeId, jobStepId)) .orElse(null); @@ -288,7 +282,7 @@ public JobStepListResult query(KapuaQuery query) throws KapuaException { // Argument Validation ArgumentValidator.notNull(query, "query"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.read, query.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.JOB, Actions.read, query.getScopeId())); // Do query return txManager.execute(tx -> jobStepRepository.query(tx, query)); } @@ -298,7 +292,7 @@ public long count(KapuaQuery query) throws KapuaException { // Argument Validation ArgumentValidator.notNull(query, "query"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.read, query.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.JOB, Actions.read, query.getScopeId())); // Do query return txManager.execute(tx -> jobStepRepository.count(tx, query)); } @@ -309,14 +303,14 @@ public void delete(KapuaId scopeId, KapuaId jobStepId) throws KapuaException { ArgumentValidator.notNull(scopeId, "scopeId"); ArgumentValidator.notNull(jobStepId, "jobStepId"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.delete, scopeId)); + authorizationService.checkPermission(new Permission(Domains.JOB, Actions.delete, scopeId)); txManager.execute(tx -> { // Check existence final JobStep jobStep = jobStepRepository.find(tx, scopeId, jobStepId) .orElseThrow(() -> new KapuaEntityNotFoundException(JobStep.TYPE, jobStepId)); // Check Job Executions - final JobExecutionQuery jobExecutionQuery = jobExecutionFactory.newQuery(scopeId); + final JobExecutionQuery jobExecutionQuery = new JobExecutionQuery(scopeId); jobExecutionQuery.setPredicate( jobExecutionQuery.attributePredicate(JobExecutionAttributes.JOB_ID, jobStep.getJobId()) ); @@ -330,7 +324,7 @@ public void delete(KapuaId scopeId, KapuaId jobStepId) throws KapuaException { jobStepRepository.delete(tx, scopeId, jobStepId); // Shift following steps of one position in the step index - JobStepQuery query = new JobStepQueryImpl(scopeId); + KapuaQuery query = new KapuaQuery(scopeId); query.setPredicate( query.andPredicate( @@ -353,7 +347,7 @@ public void delete(KapuaId scopeId, KapuaId jobStepId) throws KapuaException { @Override public int getJobStepPropertyMaxLength() throws KapuaException { // Check access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.read, KapuaId.ANY)); + authorizationService.checkPermission(new Permission(Domains.JOB, Actions.read, KapuaId.ANY)); // Return the value return jobStepPropertyValueLengthMax; @@ -362,18 +356,18 @@ public int getJobStepPropertyMaxLength() throws KapuaException { // Private methods /** - * Shifts {@link JobStep} matched by the given {@link JobStepQuery} according to the given increment. + * Shifts {@link JobStep} matched by the given {@link KapuaQuery} according to the given increment. * * @param tx * The {@link TxContext} which is owning the transaction. * @param selectorQuery - * The selector {@link JobStepQuery}. + * The selector {@link KapuaQuery}. * @param increment * The increment o apply to the matched {@link JobStep}s * @throws KapuaException * @since 2.0.0 */ - private void shiftJobStepPosition(TxContext tx, JobStepQuery selectorQuery, int increment) throws KapuaException { + private void shiftJobStepPosition(TxContext tx, KapuaQuery selectorQuery, int increment) throws KapuaException { selectorQuery.setSortCriteria(selectorQuery.fieldSortCriteria(JobStepAttributes.STEP_INDEX, SortOrder.ASCENDING)); JobStepListResult followingJobStepListResult = jobStepRepository.query(tx, selectorQuery); diff --git a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/targets/internal/JobTargetCreatorImpl.java b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/targets/internal/JobTargetCreatorImpl.java deleted file mode 100644 index 88bfe3d09bd..00000000000 --- a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/targets/internal/JobTargetCreatorImpl.java +++ /dev/null @@ -1,51 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2017, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.job.targets.internal; - -import org.eclipse.kapua.commons.model.AbstractKapuaUpdatableEntityCreator; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.job.targets.JobTarget; -import org.eclipse.kapua.service.job.targets.JobTargetCreator; - -public class JobTargetCreatorImpl extends AbstractKapuaUpdatableEntityCreator implements JobTargetCreator { - - private static final long serialVersionUID = 3119071638220738358L; - - private KapuaId jobId; - private KapuaId jobTargetId; - - public JobTargetCreatorImpl(KapuaId scopeId) { - super(scopeId); - } - - @Override - public KapuaId getJobId() { - return jobId; - } - - @Override - public void setJobId(KapuaId jobId) { - this.jobId = jobId; - } - - @Override - public KapuaId getJobTargetId() { - return jobTargetId; - } - - @Override - public void setJobTargetId(KapuaId jobTargetId) { - this.jobTargetId = jobTargetId; - } - -} diff --git a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/targets/internal/JobTargetFactoryImpl.java b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/targets/internal/JobTargetFactoryImpl.java index f7827b78da1..e06831ff942 100644 --- a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/targets/internal/JobTargetFactoryImpl.java +++ b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/targets/internal/JobTargetFactoryImpl.java @@ -12,15 +12,12 @@ *******************************************************************************/ package org.eclipse.kapua.service.job.targets.internal; +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaEntityCloneException; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.job.targets.JobTarget; -import org.eclipse.kapua.service.job.targets.JobTargetCreator; import org.eclipse.kapua.service.job.targets.JobTargetFactory; -import org.eclipse.kapua.service.job.targets.JobTargetListResult; -import org.eclipse.kapua.service.job.targets.JobTargetQuery; - -import javax.inject.Singleton; /** * {@link JobTargetFactory} implementation. @@ -35,21 +32,6 @@ public JobTarget newEntity(KapuaId scopeId) { return new JobTargetImpl(scopeId); } - @Override - public JobTargetCreator newCreator(KapuaId scopeId) { - return new JobTargetCreatorImpl(scopeId); - } - - @Override - public JobTargetQuery newQuery(KapuaId scopeId) { - return new JobTargetQueryImpl(scopeId); - } - - @Override - public JobTargetListResult newListResult() { - return new JobTargetListResultImpl(); - } - @Override public JobTarget clone(JobTarget jobTarget) { try { diff --git a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/targets/internal/JobTargetImplJpaRepository.java b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/targets/internal/JobTargetImplJpaRepository.java index 3cee4ad8f3a..d91afb19d0e 100644 --- a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/targets/internal/JobTargetImplJpaRepository.java +++ b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/targets/internal/JobTargetImplJpaRepository.java @@ -23,7 +23,7 @@ public class JobTargetImplJpaRepository implements JobTargetRepository { public JobTargetImplJpaRepository(KapuaJpaRepositoryConfiguration jpaRepoConfig) { - super(JobTargetImpl.class, JobTarget.TYPE, () -> new JobTargetListResultImpl(), jpaRepoConfig); + super(JobTargetImpl.class, JobTarget.TYPE, () -> new JobTargetListResult(), jpaRepoConfig); } } diff --git a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/targets/internal/JobTargetListResultImpl.java b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/targets/internal/JobTargetListResultImpl.java deleted file mode 100644 index 8c3f98a494c..00000000000 --- a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/targets/internal/JobTargetListResultImpl.java +++ /dev/null @@ -1,26 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2017, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.job.targets.internal; - -import org.eclipse.kapua.commons.model.query.KapuaListResultImpl; -import org.eclipse.kapua.service.job.targets.JobTarget; -import org.eclipse.kapua.service.job.targets.JobTargetListResult; - -/** - * {@link JobTargetListResult} implementation. - * - * @since 1.0.0 - */ -public class JobTargetListResultImpl extends KapuaListResultImpl implements JobTargetListResult { - -} diff --git a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/targets/internal/JobTargetQueryImpl.java b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/targets/internal/JobTargetQueryImpl.java deleted file mode 100644 index 4c8892c829e..00000000000 --- a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/targets/internal/JobTargetQueryImpl.java +++ /dev/null @@ -1,35 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2017, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.job.targets.internal; - -import org.eclipse.kapua.commons.model.query.AbstractKapuaQuery; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.job.targets.JobTargetQuery; - -/** - * {@link JobTargetQuery} implementation. - * - * @since 1.0.0 - */ -public class JobTargetQueryImpl extends AbstractKapuaQuery implements JobTargetQuery { - - /** - * Constructor. - * - * @param scopeId The {@link #getScopeId()}. - * @since 1.0.0 - */ - public JobTargetQueryImpl(KapuaId scopeId) { - super(scopeId); - } -} diff --git a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/targets/internal/JobTargetServiceImpl.java b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/targets/internal/JobTargetServiceImpl.java index 001df696bd9..22a43e02bd1 100644 --- a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/targets/internal/JobTargetServiceImpl.java +++ b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/targets/internal/JobTargetServiceImpl.java @@ -12,6 +12,13 @@ *******************************************************************************/ package org.eclipse.kapua.service.job.targets.internal; +import java.util.AbstractMap; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaEntityNotFoundException; import org.eclipse.kapua.KapuaEntityUniquenessException; import org.eclipse.kapua.KapuaException; @@ -21,7 +28,7 @@ import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; +import org.eclipse.kapua.service.authorization.permission.Permission; import org.eclipse.kapua.service.job.Job; import org.eclipse.kapua.service.job.JobRepository; import org.eclipse.kapua.service.job.targets.JobTarget; @@ -29,18 +36,11 @@ import org.eclipse.kapua.service.job.targets.JobTargetCreator; import org.eclipse.kapua.service.job.targets.JobTargetFactory; import org.eclipse.kapua.service.job.targets.JobTargetListResult; -import org.eclipse.kapua.service.job.targets.JobTargetQuery; import org.eclipse.kapua.service.job.targets.JobTargetRepository; import org.eclipse.kapua.service.job.targets.JobTargetService; import org.eclipse.kapua.service.job.targets.JobTargetStatus; import org.eclipse.kapua.storage.TxManager; -import javax.inject.Singleton; -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - /** * {@link JobTargetService} implementation. * @@ -50,7 +50,6 @@ public class JobTargetServiceImpl implements JobTargetService { private final AuthorizationService authorizationService; - private final PermissionFactory permissionFactory; private final TxManager txManager; private final JobTargetRepository jobTargetRepository; private final JobTargetFactory jobTargetFactory; @@ -58,12 +57,10 @@ public class JobTargetServiceImpl implements JobTargetService { public JobTargetServiceImpl( AuthorizationService authorizationService, - PermissionFactory permissionFactory, TxManager txManager, JobTargetRepository jobTargetRepository, JobTargetFactory jobTargetFactory, JobRepository jobRepository) { this.authorizationService = authorizationService; - this.permissionFactory = permissionFactory; this.txManager = txManager; this.jobTargetRepository = jobTargetRepository; this.jobTargetFactory = jobTargetFactory; @@ -78,13 +75,13 @@ public JobTarget create(JobTargetCreator jobTargetCreator) throws KapuaException ArgumentValidator.notNull(jobTargetCreator.getJobId(), "jobTargetCreator.jobId"); ArgumentValidator.notNull(jobTargetCreator.getJobTargetId(), "jobTargetCreator.jobTargetId"); // Check access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.write, jobTargetCreator.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.JOB, Actions.write, jobTargetCreator.getScopeId())); return txManager.execute(tx -> { // Check Job Existing final Job job = jobRepository.find(tx, jobTargetCreator.getScopeId(), jobTargetCreator.getJobId()) .orElseThrow(() -> new KapuaEntityNotFoundException(Job.TYPE, jobTargetCreator.getJobId())); // Check duplicate - JobTargetQuery jobTargetQuery = new JobTargetQueryImpl(jobTargetCreator.getScopeId()); + KapuaQuery jobTargetQuery = new KapuaQuery(jobTargetCreator.getScopeId()); jobTargetQuery.setPredicate( jobTargetQuery.andPredicate( jobTargetQuery.attributePredicate(JobTargetAttributes.JOB_ID, jobTargetCreator.getJobId()), @@ -118,7 +115,7 @@ public JobTarget find(KapuaId scopeId, KapuaId jobTargetId) throws KapuaExceptio ArgumentValidator.notNull(scopeId, "scopeId"); ArgumentValidator.notNull(jobTargetId, "jobTargetId"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.write, scopeId)); + authorizationService.checkPermission(new Permission(Domains.JOB, Actions.write, scopeId)); // Do find return txManager.execute(tx -> jobTargetRepository.find(tx, scopeId, jobTargetId)) .orElse(null); @@ -129,7 +126,7 @@ public JobTargetListResult query(KapuaQuery query) throws KapuaException { // Argument Validation ArgumentValidator.notNull(query, "query"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.read, query.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.JOB, Actions.read, query.getScopeId())); // Do query return txManager.execute(tx -> jobTargetRepository.query(tx, query)); } @@ -139,7 +136,7 @@ public long count(KapuaQuery query) throws KapuaException { // Argument Validation ArgumentValidator.notNull(query, "query"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.read, query.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.JOB, Actions.read, query.getScopeId())); // Do query return txManager.execute(tx -> jobTargetRepository.count(tx, query)); } @@ -153,7 +150,7 @@ public JobTarget update(JobTarget jobTarget) throws KapuaException { ArgumentValidator.notNull(jobTarget.getStepIndex(), "jobTarget.stepIndex"); ArgumentValidator.notNull(jobTarget.getStatus(), "jobTarget.status"); // Check access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.write, jobTarget.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.JOB, Actions.write, jobTarget.getScopeId())); // Check existence return txManager.execute(tx -> { if (!jobTargetRepository.find(tx, jobTarget.getScopeId(), jobTarget.getId()).isPresent()) { @@ -170,7 +167,7 @@ public void delete(KapuaId scopeId, KapuaId jobTargetId) throws KapuaException { ArgumentValidator.notNull(scopeId, "scopeId"); ArgumentValidator.notNull(jobTargetId, "jobTargetId"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.delete, scopeId)); + authorizationService.checkPermission(new Permission(Domains.JOB, Actions.delete, scopeId)); // Do delete txManager.execute(tx -> jobTargetRepository.delete(tx, scopeId, jobTargetId)); } diff --git a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/targets/internal/JobTargetsModule.java b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/targets/internal/JobTargetsModule.java index 34613223746..1edd6681ac4 100644 --- a/service/job/internal/src/main/java/org/eclipse/kapua/service/job/targets/internal/JobTargetsModule.java +++ b/service/job/internal/src/main/java/org/eclipse/kapua/service/job/targets/internal/JobTargetsModule.java @@ -12,21 +12,22 @@ *******************************************************************************/ package org.eclipse.kapua.service.job.targets.internal; -import com.google.inject.Provides; +import javax.inject.Named; +import javax.inject.Singleton; + import org.eclipse.kapua.commons.core.AbstractKapuaModule; import org.eclipse.kapua.commons.jpa.KapuaJpaRepositoryConfiguration; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; import org.eclipse.kapua.service.job.JobRepository; import org.eclipse.kapua.service.job.targets.JobTargetFactory; import org.eclipse.kapua.service.job.targets.JobTargetRepository; import org.eclipse.kapua.service.job.targets.JobTargetService; import org.eclipse.kapua.storage.TxManager; -import javax.inject.Named; -import javax.inject.Singleton; +import com.google.inject.Provides; public class JobTargetsModule extends AbstractKapuaModule { + @Override protected void configureModule() { bind(JobTargetFactory.class).to(JobTargetFactoryImpl.class); @@ -35,14 +36,12 @@ protected void configureModule() { @Provides @Singleton JobTargetService jobTargetService(AuthorizationService authorizationService, - PermissionFactory permissionFactory, - @Named("jobTxManager") TxManager txManager, - JobTargetRepository jobTargetRepository, - JobTargetFactory jobTargetFactory, - JobRepository jobRepository) { + @Named("jobTxManager") TxManager txManager, + JobTargetRepository jobTargetRepository, + JobTargetFactory jobTargetFactory, + JobRepository jobRepository) { return new JobTargetServiceImpl( authorizationService, - permissionFactory, txManager, jobTargetRepository, jobTargetFactory, diff --git a/service/job/pom.xml b/service/job/pom.xml index d57f667e03e..1c9c7c891ba 100644 --- a/service/job/pom.xml +++ b/service/job/pom.xml @@ -19,7 +19,7 @@ org.eclipse.kapua kapua-service - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT pom diff --git a/service/job/test-steps/pom.xml b/service/job/test-steps/pom.xml index f78eb382223..f81eaaa3f22 100644 --- a/service/job/test-steps/pom.xml +++ b/service/job/test-steps/pom.xml @@ -20,7 +20,7 @@ org.eclipse.kapua kapua-job - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-job-test-steps diff --git a/service/job/test-steps/src/main/java/org/eclipse/kapua/service/job/steps/JobEngineSteps.java b/service/job/test-steps/src/main/java/org/eclipse/kapua/service/job/steps/JobEngineSteps.java index 9bca2aade32..6b050d37ff3 100644 --- a/service/job/test-steps/src/main/java/org/eclipse/kapua/service/job/steps/JobEngineSteps.java +++ b/service/job/test-steps/src/main/java/org/eclipse/kapua/service/job/steps/JobEngineSteps.java @@ -12,14 +12,11 @@ *******************************************************************************/ package org.eclipse.kapua.service.job.steps; -import com.google.inject.Singleton; -import io.cucumber.java.After; -import io.cucumber.java.Before; -import io.cucumber.java.Scenario; -import io.cucumber.java.en.And; -import io.cucumber.java.en.When; +import java.util.concurrent.TimeUnit; + +import javax.inject.Inject; + import org.eclipse.kapua.KapuaException; -import org.eclipse.kapua.job.engine.JobEngineFactory; import org.eclipse.kapua.job.engine.JobEngineService; import org.eclipse.kapua.job.engine.JobStartOptions; import org.eclipse.kapua.locator.KapuaLocator; @@ -30,8 +27,13 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.inject.Inject; -import java.util.concurrent.TimeUnit; +import com.google.inject.Singleton; + +import io.cucumber.java.After; +import io.cucumber.java.Before; +import io.cucumber.java.Scenario; +import io.cucumber.java.en.And; +import io.cucumber.java.en.When; @Singleton public class JobEngineSteps extends JobServiceTestBase { @@ -39,7 +41,6 @@ public class JobEngineSteps extends JobServiceTestBase { private static final Logger LOG = LoggerFactory.getLogger(JobEngineSteps.class); private JobEngineService jobEngineService; - private JobEngineFactory jobEngineFactory; @Inject public JobEngineSteps(StepData stepData) { @@ -56,7 +57,6 @@ public void setServices() { KapuaLocator locator = KapuaLocator.getInstance(); jobEngineService = locator.getService(JobEngineService.class); - jobEngineFactory = locator.getFactory(JobEngineFactory.class); } @When("I start a job") @@ -64,7 +64,7 @@ public void startJob() throws Exception { primeException(); KapuaId currentJobId = (KapuaId) stepData.get(CURRENT_JOB_ID); try { - JobStartOptions jobStartOptions = jobEngineFactory.newJobStartOptions(); + JobStartOptions jobStartOptions = new JobStartOptions(); jobStartOptions.setEnqueue(true); jobEngineService.startJob(getCurrentScopeId(), currentJobId, jobStartOptions); } catch (KapuaException ke) { @@ -77,7 +77,8 @@ public void startJob() throws Exception { /** * Waits the {@link Job} in context to start. * - * @param waitSeconds The max time to wait + * @param waitSeconds + * The max time to wait * @throws Exception * @since 2.1.0 */ @@ -91,8 +92,7 @@ public void waitJobInContextToStart(int waitSeconds) throws Exception { if (jobEngineService.isRunning(job.getScopeId(), job.getId())) { return; } - } - catch (Exception e){ + } catch (Exception e) { LOG.warn("Error while checking running status for Job {}. Ignoring... Error: {}", job.getName(), e.getMessage()); } @@ -108,7 +108,8 @@ public void waitJobInContextToStart(int waitSeconds) throws Exception { /** * Waits the last {@link Job} in context to finish it execution up the given wait time * - * @param waitSeconds The max time to wait + * @param waitSeconds + * The max time to wait * @throws Exception * @since 2.1.0 */ @@ -122,8 +123,10 @@ public void waitJobInContextUpTo(int waitSeconds) throws Exception { /** * Looks for a {@link Job} by its {@link Job#getName()} and waits to finish it execution up the given wait time * - * @param jobName The {@link Job#getName()} to look for - * @param waitSeconds The max time to wait + * @param jobName + * The {@link Job#getName()} to look for + * @param waitSeconds + * The max time to wait * @throws Exception * @since 2.1.0 */ @@ -137,8 +140,10 @@ public void waitJobByNameUpTo(String jobName, int waitSeconds) throws Exception /** * Wait the given {@link Job} to finish its execution up the given wait time * - * @param job The {@link Job} to monitor - * @param waitSeconds The max time to wait + * @param job + * The {@link Job} to monitor + * @param waitSeconds + * The max time to wait * @throws Exception * @since 2.1.0 */ @@ -146,11 +151,10 @@ private void waitJobUpTo(Job job, int waitSeconds) throws Exception { long now = System.currentTimeMillis(); while ((System.currentTimeMillis() - now) < (waitSeconds * 1000L)) { try { - if (!jobEngineService.isRunning(job.getScopeId(), job.getId())) { + if (!jobEngineService.isRunning(job.getScopeId(), job.getId())) { return; } - } - catch (Exception e){ + } catch (Exception e) { LOG.warn("Error while checking running status for Job {}. Ignoring... Error: {}", job.getName(), e.getMessage()); } @@ -178,7 +182,8 @@ public void checkJobInContextIsRunning() throws Exception { /** * Looks for a {@link Job} by its {@link Job#getName()} and checks that is running * - * @param jobName The {@link Job#getName()} to look for + * @param jobName + * The {@link Job#getName()} to look for * @throws Exception * @since 2.1.0 */ @@ -205,7 +210,8 @@ public void checkJobInContextIsNotRunning() throws Exception { /** * Looks for a {@link Job} by its {@link Job#getName()} and checks that is not running * - * @param jobName The {@link Job#getName()} to look for + * @param jobName + * The {@link Job#getName()} to look for * @throws Exception * @since 2.1.0 */ @@ -219,8 +225,10 @@ public void checkJobByNameIsNotRunning(String jobName) throws Exception { /** * Checks the running status of the given {@link Job} * - * @param job The {@link Job} to check - * @param expectedRunning Whether expecting running or not + * @param job + * The {@link Job} to check + * @param expectedRunning + * Whether expecting running or not * @throws Exception * @since 2.1.0 */ @@ -233,7 +241,7 @@ public void restartJob() throws Exception { primeException(); KapuaId currentJobId = (KapuaId) stepData.get(CURRENT_JOB_ID); try { - JobStartOptions jobStartOptions = jobEngineFactory.newJobStartOptions(); + JobStartOptions jobStartOptions = new JobStartOptions(); jobStartOptions.setResetStepIndex(true); jobStartOptions.setFromStepIndex(0); jobStartOptions.setEnqueue(true); diff --git a/service/job/test-steps/src/main/java/org/eclipse/kapua/service/job/steps/JobExecutionServiceSteps.java b/service/job/test-steps/src/main/java/org/eclipse/kapua/service/job/steps/JobExecutionServiceSteps.java index acb57217905..f0b6a29e7f3 100644 --- a/service/job/test-steps/src/main/java/org/eclipse/kapua/service/job/steps/JobExecutionServiceSteps.java +++ b/service/job/test-steps/src/main/java/org/eclipse/kapua/service/job/steps/JobExecutionServiceSteps.java @@ -14,16 +14,9 @@ import java.util.Calendar; import java.util.Date; + import javax.inject.Inject; -import com.google.inject.Singleton; -import io.cucumber.java.After; -import io.cucumber.java.Before; -import io.cucumber.java.Scenario; -import io.cucumber.java.en.And; -import io.cucumber.java.en.Given; -import io.cucumber.java.en.Then; -import io.cucumber.java.en.When; import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.locator.KapuaLocator; import org.eclipse.kapua.model.id.KapuaId; @@ -32,7 +25,6 @@ import org.eclipse.kapua.qa.common.StepData; import org.eclipse.kapua.service.job.Job; import org.eclipse.kapua.service.job.JobAttributes; -import org.eclipse.kapua.service.job.JobFactory; import org.eclipse.kapua.service.job.JobQuery; import org.eclipse.kapua.service.job.JobService; import org.eclipse.kapua.service.job.execution.JobExecution; @@ -47,13 +39,22 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import com.google.inject.Singleton; + +import io.cucumber.java.After; +import io.cucumber.java.Before; +import io.cucumber.java.Scenario; +import io.cucumber.java.en.And; +import io.cucumber.java.en.Given; +import io.cucumber.java.en.Then; +import io.cucumber.java.en.When; + @Singleton public class JobExecutionServiceSteps extends JobServiceTestBase { private static final Logger LOG = LoggerFactory.getLogger(JobExecutionServiceSteps.class); private JobService jobService; - private JobFactory jobFactory; private JobExecutionService jobExecutionService; private JobExecutionFactory jobExecutionFactory; @@ -73,7 +74,6 @@ public void setServices() { KapuaLocator locator = KapuaLocator.getInstance(); jobService = locator.getService(JobService.class); - jobFactory = locator.getFactory(JobFactory.class); jobExecutionService = locator.getService(JobExecutionService.class); jobExecutionFactory = locator.getFactory(JobExecutionFactory.class); @@ -149,7 +149,8 @@ public void deleteLastJobExecution() throws Exception { /** * Checks that the last {@link Job} in context has the given number of {@link JobExecution}s * - * @param expectedNumberOfExecution Expected number of {@link JobExecution}s + * @param expectedNumberOfExecution + * Expected number of {@link JobExecution}s * @throws Exception * @since 2.1.0 */ @@ -163,8 +164,10 @@ public void checkJobInContextHasExecution(int expectedNumberOfExecution) throws /** * Looks for a {@link Job} by its {@link Job#getName()} and checks that has the given number of {@link JobExecution}s * - * @param jobName The {@link Job#getName()} to look for - * @param expectedNumberOfExecution Expected number of {@link JobExecution}s + * @param jobName + * The {@link Job#getName()} to look for + * @param expectedNumberOfExecution + * Expected number of {@link JobExecution}s * @throws Exception * @since 2.1.0 */ @@ -178,8 +181,10 @@ public void checkJobByNameHasExecution(String jobName, int expectedNumberOfExecu /** * Checks that the given {@link Job} has the given number of {@link JobExecution}s * - * @param job The {@link Job} to check - * @param expectedNumberOfExecution Expected number of {@link JobExecution}s + * @param job + * The {@link Job} to check + * @param expectedNumberOfExecution + * Expected number of {@link JobExecution}s * @throws Exception * @since 2.1.0 */ @@ -192,7 +197,7 @@ private void checkJobHasExecution(Job job, int expectedNumberOfExecution) throws @When("I count the execution items for the current job") public void countExecutionsForJob() throws Exception { Job job = (Job) stepData.get("Job"); - JobExecutionQuery tmpQuery = jobExecutionFactory.newQuery(getCurrentScopeId()); + JobExecutionQuery tmpQuery = new JobExecutionQuery(getCurrentScopeId()); tmpQuery.setPredicate(tmpQuery.attributePredicate(JobExecutionAttributes.JOB_ID, job.getId(), AttributePredicate.Operator.EQUAL)); updateCount(() -> (int) jobExecutionService.count(tmpQuery)); } @@ -200,7 +205,7 @@ public void countExecutionsForJob() throws Exception { @Then("I query for the execution items for the current job") public void queryExecutionsForJobWithPackages() throws Exception { Job job = (Job) stepData.get("Job"); - JobExecutionQuery tmpQuery = jobExecutionFactory.newQuery(getCurrentScopeId()); + JobExecutionQuery tmpQuery = new JobExecutionQuery(getCurrentScopeId()); tmpQuery.setPredicate(tmpQuery.attributePredicate(JobExecutionAttributes.JOB_ID, job.getId(), AttributePredicate.Operator.EQUAL)); primeException(); try { @@ -213,24 +218,21 @@ public void queryExecutionsForJobWithPackages() throws Exception { } } - @Then("I query for the execution items for the current job starting from date in the future") public void queryExecutionsForJobWithStartDateInFuture() throws Exception { final Date startDate = createDateInFuture(); queryExecutionsForJobWithStartDate(startDate); } - @Then("I query for the execution items for the current job starting from date in the past") public void queryExecutionsForJobWithStartDateInPast() throws Exception { final Date startDate = createDateInPast(); queryExecutionsForJobWithStartDate(startDate); } - private void queryExecutionsForJobWithStartDate(Date startDate) throws Exception { final Job job = (Job) stepData.get("Job"); - final JobExecutionQuery tmpQuery = jobExecutionFactory.newQuery(getCurrentScopeId()); + final JobExecutionQuery tmpQuery = new JobExecutionQuery(getCurrentScopeId()); final AndPredicate andPredicate = tmpQuery.andPredicate(tmpQuery.attributePredicate(JobExecutionAttributes.JOB_ID, job.getId())); andPredicate.and(tmpQuery.attributePredicate(JobExecutionAttributes.STARTED_ON, startDate, AttributePredicate.Operator.GREATER_THAN_OR_EQUAL)); tmpQuery.setPredicate(andPredicate); @@ -245,14 +247,12 @@ private void queryExecutionsForJobWithStartDate(Date startDate) throws Exception } } - private Date createDateInFuture() { final Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.DAY_OF_MONTH, 7); return calendar.getTime(); } - private Date createDateInPast() { final Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.DAY_OF_MONTH, -7); @@ -302,7 +302,7 @@ private void iQueryForTheExecutionItemsForTheCurrentJobAndICountOrMoreInternal(i } private JobExecutionListResult getExecutionsForJob(Job job) throws Exception { - JobExecutionQuery tmpQuery = jobExecutionFactory.newQuery(getCurrentScopeId()); + JobExecutionQuery tmpQuery = new JobExecutionQuery(getCurrentScopeId()); tmpQuery.setPredicate(tmpQuery.attributePredicate(JobExecutionAttributes.JOB_ID, job.getId(), AttributePredicate.Operator.EQUAL)); return jobExecutionService.query(tmpQuery); } @@ -367,7 +367,7 @@ private void iQueryForTheJobWithTheNameAndJobExecutionCountInternal(String jobNa } private Job getJobAndUpdateStepData(String jobName) throws Exception { - JobQuery tmpQuery = jobFactory.newQuery(getCurrentScopeId()); + JobQuery tmpQuery = new JobQuery(getCurrentScopeId()); tmpQuery.setPredicate(tmpQuery.attributePredicate(JobAttributes.NAME, jobName)); stepData.remove("Job"); @@ -419,7 +419,6 @@ private void logJobInfo(JobExecutionListResult jobExecutionList, Job job, int ex } } - @Then("The job execution matches the creator") public void checkJobExecutionItemAgainstCreator() { JobExecutionCreator executionCreator = (JobExecutionCreator) stepData.get("JobExecutionCreator"); @@ -446,16 +445,14 @@ public void checkThatNoExecutionWasFound() { @When("I test the sanity of the job execution factory") public void testTheJobExecutionFactory() { - Assert.assertNotNull(jobExecutionFactory.newCreator(SYS_SCOPE_ID)); + Assert.assertNotNull(new JobExecutionCreator(SYS_SCOPE_ID)); Assert.assertNotNull(jobExecutionFactory.newEntity(SYS_SCOPE_ID)); - Assert.assertNotNull(jobExecutionFactory.newListResult()); - Assert.assertNotNull(jobExecutionFactory.newQuery(SYS_SCOPE_ID)); } // Private methods private JobExecutionCreator prepareDefaultJobExecutionCreator() { KapuaId currentJobId = (KapuaId) stepData.get(CURRENT_JOB_ID); - JobExecutionCreator tmpCr = jobExecutionFactory.newCreator(getCurrentScopeId()); + JobExecutionCreator tmpCr = new JobExecutionCreator(getCurrentScopeId()); tmpCr.setJobId(currentJobId); tmpCr.setStartedOn(DateTime.now().toDate()); return tmpCr; diff --git a/service/job/test-steps/src/main/java/org/eclipse/kapua/service/job/steps/JobServiceSteps.java b/service/job/test-steps/src/main/java/org/eclipse/kapua/service/job/steps/JobServiceSteps.java index c46794eefcd..01b12b58083 100644 --- a/service/job/test-steps/src/main/java/org/eclipse/kapua/service/job/steps/JobServiceSteps.java +++ b/service/job/test-steps/src/main/java/org/eclipse/kapua/service/job/steps/JobServiceSteps.java @@ -13,14 +13,12 @@ *******************************************************************************/ package org.eclipse.kapua.service.job.steps; -import com.google.inject.Singleton; -import io.cucumber.java.After; -import io.cucumber.java.Before; -import io.cucumber.java.Scenario; -import io.cucumber.java.en.And; -import io.cucumber.java.en.Given; -import io.cucumber.java.en.Then; -import io.cucumber.java.en.When; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.inject.Inject; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.locator.KapuaLocator; import org.eclipse.kapua.model.id.KapuaId; @@ -37,10 +35,15 @@ import org.eclipse.kapua.service.job.step.JobStep; import org.junit.Assert; -import javax.inject.Inject; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import com.google.inject.Singleton; + +import io.cucumber.java.After; +import io.cucumber.java.Before; +import io.cucumber.java.Scenario; +import io.cucumber.java.en.And; +import io.cucumber.java.en.Given; +import io.cucumber.java.en.Then; +import io.cucumber.java.en.When; @Singleton public class JobServiceSteps extends JobServiceTestBase { @@ -92,7 +95,7 @@ public void setJobServiceConfigurationValue(List cucConfigs) throws E @Given("A regular job creator with the name {string}") public void prepareARegularJobCreator(String name) { - JobCreator jobCreator = jobFactory.newCreator(getCurrentScopeId()); + JobCreator jobCreator = new JobCreator(getCurrentScopeId()); jobCreator.setName(name); jobCreator.setDescription(TEST_JOB); stepData.put(JOB_CREATOR, jobCreator); @@ -100,7 +103,7 @@ public void prepareARegularJobCreator(String name) { @Given("A job creator with a null name") public void prepareAJobCreatorWithNullName() { - JobCreator jobCreator = jobFactory.newCreator(getCurrentScopeId()); + JobCreator jobCreator = new JobCreator(getCurrentScopeId()); jobCreator.setName(null); jobCreator.setDescription(TEST_JOB); stepData.put(JOB_CREATOR, jobCreator); @@ -108,7 +111,7 @@ public void prepareAJobCreatorWithNullName() { @Given("A job creator with an empty name") public void prepareAJobCreatorWithAnEmptyName() { - JobCreator jobCreator = jobFactory.newCreator(getCurrentScopeId()); + JobCreator jobCreator = new JobCreator(getCurrentScopeId()); jobCreator.setName(""); jobCreator.setDescription(TEST_JOB); stepData.put(JOB_CREATOR, jobCreator); @@ -135,7 +138,7 @@ public void createANumberOfJobs(int num) throws Exception { primeException(); try { for (int i = 0; i < num; i++) { - JobCreator tmpCreator = jobFactory.newCreator(getCurrentScopeId()); + JobCreator tmpCreator = new JobCreator(getCurrentScopeId()); tmpCreator.setName(String.format("TestJobNum%d", i)); tmpCreator.setDescription("TestJobDescription"); jobService.create(tmpCreator); @@ -147,7 +150,7 @@ public void createANumberOfJobs(int num) throws Exception { @Given("I create {int} job items with the name {string}") public void createANumberOfJobsWithName(int num, String name) throws Exception { - JobCreator tmpCreator = jobFactory.newCreator(getCurrentScopeId()); + JobCreator tmpCreator = new JobCreator(getCurrentScopeId()); tmpCreator.setDescription("TestJobDescription"); primeException(); try { @@ -260,24 +263,24 @@ public void findJobInDatabase() throws Exception { @When("I count the jobs in the database") public void countJobsInDatabase() throws Exception { - updateCount(() -> (int) jobService.count(jobFactory.newQuery(getCurrentScopeId()))); + updateCount(() -> (int) jobService.count(new JobQuery(getCurrentScopeId()))); } @When("I query for jobs in scope {int}") public void countJobsInScope(int id) throws Exception { - updateCount(() -> jobService.query(jobFactory.newQuery(getKapuaId(id))).getSize()); + updateCount(() -> jobService.query(new JobQuery(getKapuaId(id))).getSize()); } @When("I count the jobs with the name starting with {string}") public void countJobsWithName(String name) throws Exception { - JobQuery tmpQuery = jobFactory.newQuery(getCurrentScopeId()); + JobQuery tmpQuery = new JobQuery(getCurrentScopeId()); tmpQuery.setPredicate(tmpQuery.attributePredicate(JobAttributes.NAME, name, Operator.STARTS_WITH)); updateCount(() -> jobService.query(tmpQuery).getSize()); } @When("I query for the job with the name {string}") public void queryForJobWithName(String name) throws Exception { - JobQuery tmpQuery = jobFactory.newQuery(getCurrentScopeId()); + JobQuery tmpQuery = new JobQuery(getCurrentScopeId()); tmpQuery.setPredicate(tmpQuery.attributePredicate(JobAttributes.NAME, name)); primeException(); try { @@ -336,10 +339,9 @@ public void checkJobItemXMLDefinition(String definition) { @When("I test the sanity of the job factory") public void testJobFactorySanity() { primeException(); - Assert.assertNotNull("The job factory returned a null creator!", jobFactory.newCreator(SYS_SCOPE_ID)); + Assert.assertNotNull("The job factory returned a null creator!", new JobCreator(SYS_SCOPE_ID)); Assert.assertNotNull("The job factory returned a null job object!", jobFactory.newEntity(SYS_SCOPE_ID)); - Assert.assertNotNull("The job factory returned a null job query!", jobFactory.newQuery(SYS_SCOPE_ID)); - Assert.assertNotNull("The job factory returned a null job list result!", jobFactory.newListResult()); + Assert.assertNotNull("The job factory returned a null job query!", new JobQuery(SYS_SCOPE_ID)); } @Then("I find a job with name {string}") @@ -374,10 +376,9 @@ public void iTryToEditJobToName(String jobName) throws Throwable { } } - @When("I query for the job with the name {string} and I find it") public void iQueryForTheJobWithTheNameAndIFoundIt(String jobName) throws Exception { - JobQuery tmpQuery = jobFactory.newQuery(getCurrentScopeId()); + JobQuery tmpQuery = new JobQuery(getCurrentScopeId()); tmpQuery.setPredicate(tmpQuery.attributePredicate(JobAttributes.NAME, jobName)); primeException(); try { @@ -392,7 +393,7 @@ public void iQueryForTheJobWithTheNameAndIFoundIt(String jobName) throws Excepti @When("I query for the job with term match {string}") public void iQueryForTheJobMatchTerm(String matchTerm) throws Exception { - JobQuery tmpQuery = jobFactory.newQuery(getCurrentScopeId()); + JobQuery tmpQuery = new JobQuery(getCurrentScopeId()); tmpQuery.setPredicate(tmpQuery.matchPredicate(matchTerm)); @@ -401,7 +402,7 @@ public void iQueryForTheJobMatchTerm(String matchTerm) throws Exception { @Given("I prepare a job with name {string} and description {string}") public void iPrepareAJobWithNameAndDescription(String name, String description) { - JobCreator jobCreator = jobFactory.newCreator(SYS_SCOPE_ID); + JobCreator jobCreator = new JobCreator(SYS_SCOPE_ID); jobCreator.setName(name); jobCreator.setDescription(description); stepData.put(JOB_CREATOR, jobCreator); @@ -436,7 +437,7 @@ public void iTryToUpdateJobNameWithInvalidSymbolsInName(String invalidCharacters @Then("I change name of job from {string} to {string}") public void iChangeNameOfJobFromTo(String oldName, String newName) throws Throwable { try { - JobQuery query = jobFactory.newQuery(getCurrentScopeId()); + JobQuery query = new JobQuery(getCurrentScopeId()); query.setPredicate(query.attributePredicate(JobAttributes.NAME, oldName, Operator.EQUAL)); JobListResult queryResult = jobService.query(query); Job job = queryResult.getFirstItem(); @@ -457,7 +458,7 @@ public void thereIsNoJobWithNameInDatabase(String jobName) { @When("I change the job description from {string} to {string}") public void iChangeTheJobDescriptionFromTo(String oldDescription, String newDescription) throws Throwable { try { - JobQuery query = jobFactory.newQuery(getCurrentScopeId()); + JobQuery query = new JobQuery(getCurrentScopeId()); query.setPredicate(query.attributePredicate(JobAttributes.DESCRIPTION, oldDescription, Operator.EQUAL)); JobListResult queryResult = jobService.query(query); Job job = queryResult.getFirstItem(); @@ -471,7 +472,7 @@ public void iChangeTheJobDescriptionFromTo(String oldDescription, String newDesc // Private methods private void tryToCreateJob(String characters) throws Exception { - JobCreator jobCreator = jobFactory.newCreator(getCurrentScopeId()); + JobCreator jobCreator = new JobCreator(getCurrentScopeId()); for (int i = 0; i < characters.length(); i++) { String jobName = JOB_NAME + characters.charAt(i); jobCreator.setName(jobName); @@ -487,7 +488,7 @@ private void tryToCreateJob(String characters) throws Exception { } private void tryToUpdateJobName(String characters) throws Exception { - JobCreator jobCreator = jobFactory.newCreator(getCurrentScopeId()); + JobCreator jobCreator = new JobCreator(getCurrentScopeId()); //are we sure works as expected with invalid characters? for (int i = 0; i < characters.length(); i++) { String jobName = JOB_NAME + characters.charAt(i); diff --git a/service/job/test-steps/src/main/java/org/eclipse/kapua/service/job/steps/JobServiceTestBase.java b/service/job/test-steps/src/main/java/org/eclipse/kapua/service/job/steps/JobServiceTestBase.java index c6c75a0cce8..f6ee4aed645 100644 --- a/service/job/test-steps/src/main/java/org/eclipse/kapua/service/job/steps/JobServiceTestBase.java +++ b/service/job/test-steps/src/main/java/org/eclipse/kapua/service/job/steps/JobServiceTestBase.java @@ -18,7 +18,6 @@ import org.eclipse.kapua.qa.common.TestBase; import org.eclipse.kapua.service.job.Job; import org.eclipse.kapua.service.job.JobAttributes; -import org.eclipse.kapua.service.job.JobFactory; import org.eclipse.kapua.service.job.JobQuery; import org.eclipse.kapua.service.job.JobService; @@ -55,19 +54,16 @@ public class JobServiceTestBase extends TestBase { private JobService jobService; - private JobFactory jobFactory; - protected JobServiceTestBase(StepData stepData) { super(stepData); KapuaLocator locator = KapuaLocator.getInstance(); jobService = locator.getService(JobService.class); - jobFactory = locator.getFactory(JobFactory.class); } public Job findJob(String jobName) throws Exception { - JobQuery jobQuery = jobFactory.newQuery(getCurrentScopeId()); + JobQuery jobQuery = new JobQuery(getCurrentScopeId()); jobQuery.setPredicate( jobQuery.attributePredicate(JobAttributes.NAME, jobName) ); diff --git a/service/job/test-steps/src/main/java/org/eclipse/kapua/service/job/steps/JobStepDefinitionServiceSteps.java b/service/job/test-steps/src/main/java/org/eclipse/kapua/service/job/steps/JobStepDefinitionServiceSteps.java index a8952780e54..2dcbf642376 100644 --- a/service/job/test-steps/src/main/java/org/eclipse/kapua/service/job/steps/JobStepDefinitionServiceSteps.java +++ b/service/job/test-steps/src/main/java/org/eclipse/kapua/service/job/steps/JobStepDefinitionServiceSteps.java @@ -12,14 +12,11 @@ *******************************************************************************/ package org.eclipse.kapua.service.job.steps; -import com.google.inject.Singleton; -import io.cucumber.java.After; -import io.cucumber.java.Before; -import io.cucumber.java.Scenario; -import io.cucumber.java.en.And; -import io.cucumber.java.en.Given; -import io.cucumber.java.en.Then; -import io.cucumber.java.en.When; +import java.util.ArrayList; +import java.util.List; + +import javax.inject.Inject; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.locator.KapuaLocator; import org.eclipse.kapua.model.id.KapuaId; @@ -28,15 +25,22 @@ import org.eclipse.kapua.service.job.step.definition.JobStepDefinition; import org.eclipse.kapua.service.job.step.definition.JobStepDefinitionCreator; import org.eclipse.kapua.service.job.step.definition.JobStepDefinitionFactory; +import org.eclipse.kapua.service.job.step.definition.JobStepDefinitionQuery; import org.eclipse.kapua.service.job.step.definition.JobStepDefinitionService; import org.eclipse.kapua.service.job.step.definition.JobStepProperty; import org.eclipse.kapua.service.job.step.definition.JobStepType; import org.eclipse.kapua.service.job.steps.model.TestJobStepProcessor; import org.junit.Assert; -import javax.inject.Inject; -import java.util.ArrayList; -import java.util.List; +import com.google.inject.Singleton; + +import io.cucumber.java.After; +import io.cucumber.java.Before; +import io.cucumber.java.Scenario; +import io.cucumber.java.en.And; +import io.cucumber.java.en.Given; +import io.cucumber.java.en.Then; +import io.cucumber.java.en.When; @Singleton public class JobStepDefinitionServiceSteps extends JobServiceTestBase { @@ -154,7 +158,7 @@ public void createANumberOfStepDefinitions(Integer num) throws Exception { primeException(); try { for (int i = 0; i < num; i++) { - tmpCreator = jobStepDefinitionFactory.newCreator(getCurrentScopeId()); + tmpCreator = new JobStepDefinitionCreator(getCurrentScopeId()); tmpCreator.setName(String.format("TestStepDefinitionNum%d", random.nextLong())); tmpCreator.setProcessorName("TestStepProcessor"); tmpCreator.setStepType(JobStepType.TARGET); @@ -215,12 +219,12 @@ public void searchForStepDefinitionWithTheName(List list) throws Excepti @When("I count the step definition in the database") public void countStepDefinitionInDatabase() throws Exception { - updateCount(() -> (int) jobStepDefinitionService.count(jobStepDefinitionFactory.newQuery(KapuaId.ANY))); + updateCount(() -> (int) jobStepDefinitionService.count(new JobStepDefinitionQuery(KapuaId.ANY))); } @When("I query for step definitions in scope {int}") public void countStepDefinitijonsInScope(Integer id) throws Exception { - updateCount(() -> jobStepDefinitionService.query(jobStepDefinitionFactory.newQuery(KapuaId.ANY)).getSize()); + updateCount(() -> jobStepDefinitionService.query(new JobStepDefinitionQuery(KapuaId.ANY)).getSize()); } @When("I delete the step definition") @@ -322,14 +326,11 @@ public void checkStepDefinitionProcessorName(String name) { @When("I test the sanity of the step definition factory") public void testTheStepDefinitionFactory() { - Assert.assertNotNull(jobStepDefinitionFactory.newCreator(SYS_SCOPE_ID)); + Assert.assertNotNull(new JobStepDefinitionCreator(SYS_SCOPE_ID)); Assert.assertNotNull(jobStepDefinitionFactory.newEntity(SYS_SCOPE_ID)); - Assert.assertNotNull(jobStepDefinitionFactory.newListResult()); - Assert.assertNotNull(jobStepDefinitionFactory.newQuery(SYS_SCOPE_ID)); Assert.assertNotNull(jobStepDefinitionFactory.newStepProperty("TestName", "TestType", "TestValue", "TestExampleValue")); } - private JobStepType getTypeFromString(String type) { if (type.trim().toUpperCase().equals("TARGET")) { return JobStepType.TARGET; @@ -339,7 +340,7 @@ private JobStepType getTypeFromString(String type) { } private JobStepDefinitionCreator prepareDefaultJobStepDefinitionCreator() { - JobStepDefinitionCreator tmpCr = jobStepDefinitionFactory.newCreator(getCurrentScopeId()); + JobStepDefinitionCreator tmpCr = new JobStepDefinitionCreator(getCurrentScopeId()); tmpCr.setName(String.format("DefinitionName_%d", random.nextInt())); tmpCr.setDescription("DefinitionDescription"); tmpCr.setReaderName(null); diff --git a/service/job/test-steps/src/main/java/org/eclipse/kapua/service/job/steps/JobStepServiceSteps.java b/service/job/test-steps/src/main/java/org/eclipse/kapua/service/job/steps/JobStepServiceSteps.java index b2f2f218968..4ab97d4dc54 100644 --- a/service/job/test-steps/src/main/java/org/eclipse/kapua/service/job/steps/JobStepServiceSteps.java +++ b/service/job/test-steps/src/main/java/org/eclipse/kapua/service/job/steps/JobStepServiceSteps.java @@ -12,17 +12,18 @@ *******************************************************************************/ package org.eclipse.kapua.service.job.steps; -import com.google.inject.Singleton; -import io.cucumber.java.After; -import io.cucumber.java.Before; -import io.cucumber.java.Scenario; -import io.cucumber.java.en.And; -import io.cucumber.java.en.Given; -import io.cucumber.java.en.Then; -import io.cucumber.java.en.When; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; + +import javax.inject.Inject; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.locator.KapuaLocator; import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.model.query.predicate.AttributePredicate; import org.eclipse.kapua.qa.common.StepData; import org.eclipse.kapua.qa.common.cucumber.CucJobStepProperty; @@ -32,7 +33,6 @@ import org.eclipse.kapua.service.job.step.JobStepCreator; import org.eclipse.kapua.service.job.step.JobStepFactory; import org.eclipse.kapua.service.job.step.JobStepListResult; -import org.eclipse.kapua.service.job.step.JobStepQuery; import org.eclipse.kapua.service.job.step.JobStepService; import org.eclipse.kapua.service.job.step.definition.JobStepDefinition; import org.eclipse.kapua.service.job.step.definition.JobStepProperty; @@ -40,12 +40,15 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.inject.Inject; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.stream.Collectors; +import com.google.inject.Singleton; + +import io.cucumber.java.After; +import io.cucumber.java.Before; +import io.cucumber.java.Scenario; +import io.cucumber.java.en.And; +import io.cucumber.java.en.Given; +import io.cucumber.java.en.Then; +import io.cucumber.java.en.When; @Singleton public class JobStepServiceSteps extends JobServiceTestBase { @@ -106,28 +109,30 @@ public void iPrepareAJobStepCreatorWithPropertyList(String name, List cucJobStepProperties) throws Exception{ + public void iAddJobStepToJobWithSelectedJobStepDefinitionAndFollowingJobStepProperties(String jobStepName, List cucJobStepProperties) throws Exception { Job job = (Job) stepData.get(JOB); JobStepDefinition jobStepDefinition = (JobStepDefinition) stepData.get(JOB_STEP_DEFINITION); - JobStepCreator jobStepCreator = jobStepFactory.newCreator(job.getScopeId()); + JobStepCreator jobStepCreator = new JobStepCreator(job.getScopeId()); jobStepCreator.setJobId(job.getId()); jobStepCreator.setName(jobStepName); jobStepCreator.setJobStepDefinitionId(jobStepDefinition.getId()); jobStepCreator.setStepProperties( cucJobStepProperties.stream() .map( - (cucJobStepProperty) -> jobStepFactory.newStepProperty( - cucJobStepProperty.getName(), - cucJobStepProperty.getType(), - cucJobStepProperty.getValue() - ) + (cucJobStepProperty) -> jobStepFactory.newStepProperty( + cucJobStepProperty.getName(), + cucJobStepProperty.getType(), + cucJobStepProperty.getValue() + ) ) .collect(Collectors.toList()) ); @@ -266,7 +271,7 @@ public void iLookForLastJobStep() throws Exception { @When("I look for the JobStep with name {string}") public void iLookForJobStepWithName(String name) throws Exception { - JobStepQuery tmpQuery = jobStepFactory.newQuery(getCurrentScopeId()); + KapuaQuery tmpQuery = new KapuaQuery(getCurrentScopeId()); tmpQuery.setPredicate(tmpQuery.attributePredicate(JobStepAttributes.NAME, name)); primeException(); @@ -281,7 +286,7 @@ public void iLookForJobStepWithName(String name) throws Exception { @When("I query for a JobStep with the name {string}") public void iQueryForJobStepWithName(String name) throws Exception { - JobStepQuery tmpQuery = jobStepFactory.newQuery(getCurrentScopeId()); + KapuaQuery tmpQuery = new KapuaQuery(getCurrentScopeId()); tmpQuery.setPredicate(tmpQuery.attributePredicate(JobStepAttributes.NAME, name)); primeException(); @@ -320,7 +325,7 @@ public void iCountJobStepAndCheck(int count, int timeout) throws Exception { } private JobStepListResult getJobStepListResult(KapuaId currentJobId) throws KapuaException { - JobStepQuery jobStepQuery = jobStepFactory.newQuery(getCurrentScopeId()); + KapuaQuery jobStepQuery = new KapuaQuery(getCurrentScopeId()); jobStepQuery.setPredicate(jobStepQuery.attributePredicate(JobStepAttributes.JOB_ID, currentJobId, AttributePredicate.Operator.EQUAL)); return jobStepService.query(jobStepQuery); @@ -328,7 +333,7 @@ private JobStepListResult getJobStepListResult(KapuaId currentJobId) throws Kapu @When("I count the JobSteps in the current scope") public void iCountJobStepInCurrentScope() throws Exception { - updateCount(() -> (int) jobStepService.count(jobStepFactory.newQuery(getCurrentScopeId()))); + updateCount(() -> (int) jobStepService.count(new KapuaQuery(getCurrentScopeId()))); } // Delete @@ -373,16 +378,15 @@ public void checkJobStepNotFound() { @When("I test the JobStepFactory") public void testTheStepFactory() { - Assert.assertNotNull(jobStepFactory.newCreator(SYS_SCOPE_ID)); + Assert.assertNotNull(new JobStepCreator(SYS_SCOPE_ID)); Assert.assertNotNull(jobStepFactory.newEntity(SYS_SCOPE_ID)); - Assert.assertNotNull(jobStepFactory.newListResult()); - Assert.assertNotNull(jobStepFactory.newQuery(SYS_SCOPE_ID)); + Assert.assertNotNull(new KapuaQuery(SYS_SCOPE_ID)); Assert.assertNotNull(jobStepFactory.newStepProperty("TestName", "TestType", "TestValue")); } // Private methods private JobStepCreator prepareDefaultJobStepCreator() { - JobStepCreator tmpCr = jobStepFactory.newCreator(getCurrentScopeId()); + JobStepCreator tmpCr = new JobStepCreator(getCurrentScopeId()); tmpCr.setName(String.format("StepName_%d", random.nextInt())); tmpCr.setDescription("StepDescription"); return tmpCr; diff --git a/service/job/test-steps/src/main/java/org/eclipse/kapua/service/job/steps/JobTargetServiceSteps.java b/service/job/test-steps/src/main/java/org/eclipse/kapua/service/job/steps/JobTargetServiceSteps.java index 9921b83de09..68617d82789 100644 --- a/service/job/test-steps/src/main/java/org/eclipse/kapua/service/job/steps/JobTargetServiceSteps.java +++ b/service/job/test-steps/src/main/java/org/eclipse/kapua/service/job/steps/JobTargetServiceSteps.java @@ -12,25 +12,24 @@ *******************************************************************************/ package org.eclipse.kapua.service.job.steps; -import com.google.inject.Singleton; -import io.cucumber.java.After; -import io.cucumber.java.Before; -import io.cucumber.java.Scenario; -import io.cucumber.java.en.And; -import io.cucumber.java.en.Given; -import io.cucumber.java.en.Then; -import io.cucumber.java.en.When; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; + +import javax.inject.Inject; + import org.eclipse.kapua.KapuaEntityNotFoundException; import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.locator.KapuaLocator; import org.eclipse.kapua.model.KapuaEntity; import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.model.query.predicate.AttributePredicate; import org.eclipse.kapua.qa.common.StepData; import org.eclipse.kapua.service.device.management.registry.operation.notification.ManagementOperationNotification; import org.eclipse.kapua.service.device.registry.Device; import org.eclipse.kapua.service.device.registry.DeviceAttributes; -import org.eclipse.kapua.service.device.registry.DeviceFactory; import org.eclipse.kapua.service.device.registry.DeviceListResult; import org.eclipse.kapua.service.device.registry.DeviceQuery; import org.eclipse.kapua.service.device.registry.DeviceRegistryService; @@ -40,18 +39,21 @@ import org.eclipse.kapua.service.job.targets.JobTargetCreator; import org.eclipse.kapua.service.job.targets.JobTargetFactory; import org.eclipse.kapua.service.job.targets.JobTargetListResult; -import org.eclipse.kapua.service.job.targets.JobTargetQuery; import org.eclipse.kapua.service.job.targets.JobTargetService; import org.eclipse.kapua.service.job.targets.JobTargetStatus; import org.junit.Assert; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.inject.Inject; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; +import com.google.inject.Singleton; + +import io.cucumber.java.After; +import io.cucumber.java.Before; +import io.cucumber.java.Scenario; +import io.cucumber.java.en.And; +import io.cucumber.java.en.Given; +import io.cucumber.java.en.Then; +import io.cucumber.java.en.When; @Singleton public class JobTargetServiceSteps extends JobServiceTestBase { @@ -60,7 +62,6 @@ public class JobTargetServiceSteps extends JobServiceTestBase { private static final String DEVICE = "Device"; - private DeviceFactory deviceFactory; private DeviceRegistryService deviceRegistryService; private JobTargetService jobTargetService; @@ -80,7 +81,6 @@ public void beforeScenarioNone(Scenario scenario) { public void setServices() { KapuaLocator locator = KapuaLocator.getInstance(); - deviceFactory= locator.getFactory(DeviceFactory.class); deviceRegistryService = locator.getService(DeviceRegistryService.class); jobTargetService = locator.getService(JobTargetService.class); @@ -129,7 +129,6 @@ public void iCreateANewJobTargetItem() throws Exception { } } - @And("I confirm the step index is different than {int} and status is {string}") public void iConfirmTheStepIndexIsDifferentThanAndStatusIs(int stepIndex, String status) { JobTarget jobTarget = (JobTarget) stepData.get(JOB_TARGET); @@ -137,7 +136,6 @@ public void iConfirmTheStepIndexIsDifferentThanAndStatusIs(int stepIndex, String Assert.assertEquals(status, jobTarget.getStatus().toString()); } - @And("I search for the job targets in database") public void iSearchForTheJobTargetsInDatabase() { ArrayList jobTargets = (ArrayList) stepData.get(JOB_TARGET_LIST); @@ -147,13 +145,14 @@ public void iSearchForTheJobTargetsInDatabase() { /** * Adds {@link Device}s with the given {@link Device#getClientId()}s as a {@link JobTarget} of the {@link Job} in context. * - * @param clientIds The {@link Device#getClientId()}s to add + * @param clientIds + * The {@link Device#getClientId()}s to add * @throws Exception * @since 2.1.0 */ @And("I add device target(s) to job") public void addDeviceTargetsToJob(List clientIds) throws Exception { - DeviceQuery deviceQuery = deviceFactory.newQuery(getCurrentScopeId()); + DeviceQuery deviceQuery = new DeviceQuery(getCurrentScopeId()); deviceQuery.setPredicate( deviceQuery.attributePredicate(DeviceAttributes.CLIENT_ID, clientIds) ); @@ -167,7 +166,7 @@ public void addDeviceTargetsToJob(List clientIds) throws Exception { Job job = (Job) stepData.get("Job"); - JobTargetCreator jobTargetCreator = jobTargetFactory.newCreator(getCurrentScopeId()); + JobTargetCreator jobTargetCreator = new JobTargetCreator(getCurrentScopeId()); jobTargetCreator.setJobId(job.getId()); List jobTargets = new ArrayList<>(); @@ -181,7 +180,7 @@ public void addDeviceTargetsToJob(List clientIds) throws Exception { @And("I add target(s) to job") public void addTargetsToJob() throws Exception { - JobTargetCreator jobTargetCreator = jobTargetFactory.newCreator(getCurrentScopeId()); + JobTargetCreator jobTargetCreator = new JobTargetCreator(getCurrentScopeId()); Job job = (Job) stepData.get("Job"); ArrayList devices = (ArrayList) stepData.get("DeviceList"); ArrayList jobTargetList = new ArrayList<>(); @@ -291,13 +290,13 @@ public void setTargetStepExceptionMessage(String text) throws Exception { @When("I count the targets in the current scope") public void countTargetsForJob() throws Exception { - updateCount(() -> (int) jobTargetService.count(jobTargetFactory.newQuery(getCurrentScopeId()))); + updateCount(() -> (int) jobTargetService.count(new KapuaQuery(getCurrentScopeId()))); } @When("I query the targets for the current job") public void queryTargetsForJob() throws Exception { Job job = (Job) stepData.get("Job"); - JobTargetQuery tmpQuery = jobTargetFactory.newQuery(getCurrentScopeId()); + KapuaQuery tmpQuery = new KapuaQuery(getCurrentScopeId()); tmpQuery.setPredicate(tmpQuery.attributePredicate(JobTargetAttributes.JOB_ID, job.getId(), AttributePredicate.Operator.EQUAL)); primeException(); try { @@ -335,7 +334,7 @@ public void iConfirmJobTargetHasStatus(int stepIndex, String jobStatus, int time @When("I count the targets in the current scope and I count {int}") public void iCountTheTargetsInTheCurrentScopeAndICount(int targetNum) throws Exception { - updateCountAndCheck(() -> (int) jobTargetService.count(jobTargetFactory.newQuery(getCurrentScopeId())), targetNum); + updateCountAndCheck(() -> (int) jobTargetService.count(new KapuaQuery(getCurrentScopeId())), targetNum); } @Then("The target step index is indeed {int}") @@ -370,23 +369,21 @@ public void checkThatNoTargetWasFound() { Assert.assertNull("Unexpected job target item found!", stepData.get(JOB_TARGET)); } - @When("I test the sanity of the job target factory") public void testTheJobTargetFactory() { - Assert.assertNotNull(jobTargetFactory.newCreator(SYS_SCOPE_ID)); + Assert.assertNotNull(new JobTargetCreator(SYS_SCOPE_ID)); Assert.assertNotNull(jobTargetFactory.newEntity(SYS_SCOPE_ID)); - Assert.assertNotNull(jobTargetFactory.newListResult()); - Assert.assertNotNull(jobTargetFactory.newQuery(SYS_SCOPE_ID)); } - // Check Job Targets /** * Checks that the {@link JobTarget} in context for the {@link Job} in context has the expected {@link JobTarget#getStepIndex()} and {@link JobTarget#getStatus()} * - * @param expectedStepIndex The expected {@link JobTarget#getStepIndex()} - * @param expectedJobTargetStatus The expected {@link JobTarget#getStatus()} + * @param expectedStepIndex + * The expected {@link JobTarget#getStepIndex()} + * @param expectedJobTargetStatus + * The expected {@link JobTarget#getStatus()} * @throws Exception * @since 2.1.0 */ @@ -399,11 +396,15 @@ public void checkJobTargetForJobInContextHas(int expectedStepIndex, String expec } /** - * Checks that the {@link JobTarget} that matches the {@link Device} with the given {@link Device#getClientId()} for the {@link Job} in context has the expected {@link JobTarget#getStepIndex()} and {@link JobTarget#getStatus()} + * Checks that the {@link JobTarget} that matches the {@link Device} with the given {@link Device#getClientId()} for the {@link Job} in context has the expected {@link JobTarget#getStepIndex()} + * and {@link JobTarget#getStatus()} * - * @param clientId The {@link Device#getClientId()} to look for - * @param expectedStepIndex The expected {@link JobTarget#getStepIndex()} - * @param expectedJobTargetStatus The expected {@link JobTarget#getStatus()} + * @param clientId + * The {@link Device#getClientId()} to look for + * @param expectedStepIndex + * The expected {@link JobTarget#getStepIndex()} + * @param expectedJobTargetStatus + * The expected {@link JobTarget#getStatus()} * @throws Exception * @since 2.1.0 */ @@ -417,12 +418,12 @@ public void checkJobTargetByNameForJobHas(String clientId, int expectedStepIndex Job job = (Job) stepData.get(JOB); - JobTargetQuery jobTargetQuery = jobTargetFactory.newQuery(job.getScopeId()); + KapuaQuery jobTargetQuery = new KapuaQuery(job.getScopeId()); jobTargetQuery.setPredicate( - jobTargetQuery.andPredicate( - jobTargetQuery.attributePredicate(JobTargetAttributes.JOB_ID, job.getId()), - jobTargetQuery.attributePredicate(JobTargetAttributes.JOB_TARGET_ID, device.getId()) - ) + jobTargetQuery.andPredicate( + jobTargetQuery.attributePredicate(JobTargetAttributes.JOB_ID, job.getId()), + jobTargetQuery.attributePredicate(JobTargetAttributes.JOB_TARGET_ID, device.getId()) + ) ); JobTarget jobTarget = jobTargetService.query(jobTargetQuery).getFirstItem(); @@ -437,8 +438,10 @@ public void checkJobTargetByNameForJobHas(String clientId, int expectedStepIndex /** * Checks that given {@link JobTarget} has the expected {@link JobTarget#getStepIndex()} and {@link JobTarget#getStatus()} * - * @param expectedStepIndex The expected {@link JobTarget#getStepIndex()} - * @param expectedJobTargetStatus The expected {@link JobTarget#getStatus()} + * @param expectedStepIndex + * The expected {@link JobTarget#getStepIndex()} + * @param expectedJobTargetStatus + * The expected {@link JobTarget#getStatus()} * @throws Exception * @since 2.1.0 */ @@ -454,10 +457,11 @@ private void checkJobTargetForJobHas(JobTarget jobTarget, int expectedStepIndex, /** * Waits the {@link JobTarget} in context to finish its processing and to have {@link JobTarget#getStatus()} set to {@link JobTargetStatus#NOTIFIED_COMPLETION} *

        - * It also takes as a valid {@link JobTarget#getStatus()} {@link JobTargetStatus#PROCESS_OK} because the {@link ManagementOperationNotification} can be processed fast and - * {@link JobTarget} can switch from {@link JobTargetStatus#NOTIFIED_COMPLETION} to {@link JobTargetStatus#PROCESS_OK} while waiting for the next check. + * It also takes as a valid {@link JobTarget#getStatus()} {@link JobTargetStatus#PROCESS_OK} because the {@link ManagementOperationNotification} can be processed fast and {@link JobTarget} can + * switch from {@link JobTargetStatus#NOTIFIED_COMPLETION} to {@link JobTargetStatus#PROCESS_OK} while waiting for the next check. * - * @param waitSeconds The max time to wait + * @param waitSeconds + * The max time to wait * @throws Exception * @since 2.1.0 */ @@ -486,7 +490,7 @@ public void waitJobTargetInContextToNotifyCompletion(int waitSeconds) throws Exc private JobTargetCreator prepareJobTargetCreator() { KapuaId currentJobId = (KapuaId) stepData.get(CURRENT_JOB_ID); Device device = (Device) stepData.get(DEVICE); - JobTargetCreator tmpCr = jobTargetFactory.newCreator(getCurrentScopeId()); + JobTargetCreator tmpCr = new JobTargetCreator(getCurrentScopeId()); tmpCr.setJobId(currentJobId); tmpCr.setJobTargetId(device.getId()); return tmpCr; @@ -494,7 +498,7 @@ private JobTargetCreator prepareJobTargetCreator() { private JobTargetCreator prepareDefaultJobTargetCreator() { KapuaId currentJobId = (KapuaId) stepData.get(CURRENT_JOB_ID); - JobTargetCreator tmpCr = jobTargetFactory.newCreator(getCurrentScopeId()); + JobTargetCreator tmpCr = new JobTargetCreator(getCurrentScopeId()); tmpCr.setJobId(currentJobId); tmpCr.setJobTargetId(getKapuaId()); return tmpCr; @@ -502,13 +506,13 @@ private JobTargetCreator prepareDefaultJobTargetCreator() { private JobTargetStatus parseJobTargetStatusFromString(String stat) { switch (stat.toUpperCase().trim()) { - case "PROCESS_AWAITING": - return JobTargetStatus.PROCESS_AWAITING; - case "PROCESS_OK": - return JobTargetStatus.PROCESS_OK; - case "PROCESS_FAILED": - default: - return JobTargetStatus.PROCESS_FAILED; + case "PROCESS_AWAITING": + return JobTargetStatus.PROCESS_AWAITING; + case "PROCESS_OK": + return JobTargetStatus.PROCESS_OK; + case "PROCESS_FAILED": + default: + return JobTargetStatus.PROCESS_FAILED; } } } diff --git a/service/job/test/pom.xml b/service/job/test/pom.xml index 52325ef6660..05eb601b22b 100644 --- a/service/job/test/pom.xml +++ b/service/job/test/pom.xml @@ -19,7 +19,7 @@ org.eclipse.kapua kapua-job - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-job-test diff --git a/service/job/test/src/test/java/org/eclipse/kapua/service/job/test/JobLocatorConfiguration.java b/service/job/test/src/test/java/org/eclipse/kapua/service/job/test/JobLocatorConfiguration.java index 665fc6d35d7..57000fe63ab 100644 --- a/service/job/test/src/test/java/org/eclipse/kapua/service/job/test/JobLocatorConfiguration.java +++ b/service/job/test/src/test/java/org/eclipse/kapua/service/job/test/JobLocatorConfiguration.java @@ -23,13 +23,11 @@ import org.eclipse.kapua.commons.metric.CommonsMetric; import org.eclipse.kapua.commons.metric.MetricsService; import org.eclipse.kapua.commons.metric.MetricsServiceImpl; -import org.eclipse.kapua.commons.model.query.QueryFactoryImpl; import org.eclipse.kapua.commons.service.internal.cache.CacheManagerProvider; import org.eclipse.kapua.commons.setting.system.SystemSetting; import org.eclipse.kapua.commons.util.xml.XmlUtil; import org.eclipse.kapua.job.engine.JobEngineService; import org.eclipse.kapua.locator.KapuaLocator; -import org.eclipse.kapua.model.query.QueryFactory; import org.eclipse.kapua.qa.common.MockedLocator; import org.eclipse.kapua.qa.common.TestJAXBContextProvider; import org.eclipse.kapua.service.account.AccountFactory; @@ -41,7 +39,6 @@ import org.eclipse.kapua.service.authorization.AuthorizationService; import org.eclipse.kapua.service.authorization.domain.DomainRegistryService; import org.eclipse.kapua.service.authorization.permission.Permission; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; import org.eclipse.kapua.service.job.JobFactory; import org.eclipse.kapua.service.job.JobService; import org.eclipse.kapua.service.job.execution.JobExecutionFactory; @@ -118,9 +115,6 @@ protected void configure() { bind(MetricRegistry.class).toInstance(new MetricRegistry()); bind(MetricsService.class).to(MetricsServiceImpl.class).in(Singleton.class); - // Commons - bind(QueryFactory.class).toInstance(new QueryFactoryImpl()); - // Account bind(AccountRelativeFinder.class).toInstance(Mockito.mock(AccountRelativeFinder.class)); bind(AccountService.class).toInstance(Mockito.mock(AccountService.class)); @@ -139,8 +133,6 @@ protected void configure() { } catch (Exception e) { LOG.warn("Error while setting mock AuthorizationService. This may lead to failures...", e); } - final PermissionFactory mockedPermissionFactory = Mockito.mock(PermissionFactory.class); - bind(PermissionFactory.class).toInstance(mockedPermissionFactory); // Job bind(JobFactory.class).toInstance(new JobFactoryImpl()); @@ -149,39 +141,34 @@ protected void configure() { bind(JobService.class).toInstance(new JobServiceImpl( Mockito.mock(ServiceConfigurationManager.class), Mockito.mock(JobEngineService.class), - mockedPermissionFactory, mockedAuthorization, txManager, new JobImplJpaRepository(jpaRepoConfig), - new TriggerServiceImpl(mockedAuthorization, mockedPermissionFactory, + new TriggerServiceImpl(mockedAuthorization, txManager, triggerImplJpaRepository, new TriggerFactoryImpl(), new TriggerDefinitionImplJpaRepository(jpaRepoConfig), new TriggerDefinitionFactoryImpl() ))); bind(JobStepDefinitionService.class).toInstance(new JobStepDefinitionServiceImpl( mockedAuthorization, - mockedPermissionFactory, txManager, new JobStepDefinitionImplJpaRepository(jpaRepoConfig) )); bind(JobStepDefinitionFactory.class).toInstance(new JobStepDefinitionFactoryImpl()); final JobExecutionImplJpaRepository jobExecutionRepository = new JobExecutionImplJpaRepository(jpaRepoConfig); - final JobExecutionService jobExecutionService = new JobExecutionServiceImpl(mockedAuthorization, mockedPermissionFactory, txManager, jobExecutionRepository); + final JobExecutionService jobExecutionService = new JobExecutionServiceImpl(mockedAuthorization, txManager, jobExecutionRepository); bind(JobStepService.class).toInstance(new JobStepServiceImpl( mockedAuthorization, - mockedPermissionFactory, txManager, new JobStepImplJpaRepository(jpaRepoConfig), new JobStepFactoryImpl(), jobExecutionService, - new JobExecutionFactoryImpl(), new JobStepDefinitionImplJpaRepository(jpaRepoConfig), new XmlUtil(new TestJAXBContextProvider()) )); bind(JobStepFactory.class).toInstance(new JobStepFactoryImpl()); bind(JobTargetService.class).toInstance(new JobTargetServiceImpl( mockedAuthorization, - mockedPermissionFactory, txManager, new JobTargetImplJpaRepository(jpaRepoConfig), new JobTargetFactoryImpl(), @@ -190,7 +177,6 @@ txManager, triggerImplJpaRepository, new TriggerFactoryImpl(), bind(JobTargetFactory.class).toInstance(new JobTargetFactoryImpl()); bind(JobExecutionService.class).toInstance(new JobExecutionServiceImpl( mockedAuthorization, - mockedPermissionFactory, txManager, jobExecutionRepository )); @@ -202,7 +188,6 @@ txManager, triggerImplJpaRepository, new TriggerFactoryImpl(), final TriggerFactoryImpl triggerFactory = new TriggerFactoryImpl(); bind(TriggerService.class).toInstance(new TriggerServiceImpl( mockedAuthorization, - mockedPermissionFactory, txManager, triggerImplJpaRepository, triggerFactory, @@ -212,7 +197,6 @@ txManager, triggerImplJpaRepository, new TriggerFactoryImpl(), bind(TriggerFactory.class).toInstance(triggerFactory); bind(TriggerDefinitionService.class).toInstance(new TriggerDefinitionServiceImpl( mockedAuthorization, - mockedPermissionFactory, txManager, triggerDefinitionRepository, triggerDefinitionFactory diff --git a/service/pom.xml b/service/pom.xml index add024cb096..002ed19ff8f 100644 --- a/service/pom.xml +++ b/service/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-service diff --git a/service/scheduler/api/pom.xml b/service/scheduler/api/pom.xml index 80fba1fe7ce..397ce99ef3a 100644 --- a/service/scheduler/api/pom.xml +++ b/service/scheduler/api/pom.xml @@ -17,7 +17,7 @@ org.eclipse.kapua kapua-scheduler - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-scheduler-api diff --git a/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/TriggerCreator.java b/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/TriggerCreator.java index 51c08681b52..933a035d7cd 100644 --- a/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/TriggerCreator.java +++ b/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/TriggerCreator.java @@ -12,18 +12,20 @@ *******************************************************************************/ package org.eclipse.kapua.service.scheduler.trigger; -import org.eclipse.kapua.model.KapuaNamedEntityCreator; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.model.id.KapuaIdAdapter; -import org.eclipse.kapua.service.scheduler.trigger.definition.TriggerProperty; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; -import java.util.Date; -import java.util.List; + +import org.eclipse.kapua.model.KapuaNamedEntityCreator; +import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.id.KapuaIdAdapter; +import org.eclipse.kapua.service.scheduler.trigger.definition.TriggerProperty; /** * {@link Trigger} {@link KapuaNamedEntityCreator} definition. @@ -33,8 +35,28 @@ */ @XmlRootElement(name = "triggerCreator") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = TriggerXmlRegistry.class, factoryMethod = "newCreator") -public interface TriggerCreator extends KapuaNamedEntityCreator { +@XmlType +public class TriggerCreator extends KapuaNamedEntityCreator { + + private static final long serialVersionUID = -2460883485294616032L; + + private Date startsOn; + private Date endsOn; + private String cronScheduling; + private Long retryInterval; + private KapuaId triggerDefinitionId; + private List triggerProperties; + + public TriggerCreator() { + } + + public TriggerCreator(KapuaId scopeId) { + super(scopeId); + } + + public TriggerCreator(KapuaId scopeId, String name) { + super(scopeId, name); + } /** * Gets the start {@link Date} from which this {@link Trigger} will be valid. @@ -42,15 +64,20 @@ public interface TriggerCreator extends KapuaNamedEntityCreator { * @return The start {@link Date} from which this {@link Trigger} will be valid. * @since 1.0.0 */ - Date getStartsOn(); + public Date getStartsOn() { + return startsOn; + } /** * Sets the start {@link Date} from which this {@link Trigger} will be valid. * - * @param starstOn The start {@link Date} from which this {@link Trigger} will be valid. + * @param startsOn + * The start {@link Date} from which this {@link Trigger} will be valid. * @since 1.0.0 */ - void setStartsOn(Date starstOn); + public void setStartsOn(Date startsOn) { + this.startsOn = startsOn; + } /** * Gets the end {@link Date} until which this {@link Trigger} will be valid. @@ -60,17 +87,22 @@ public interface TriggerCreator extends KapuaNamedEntityCreator { * @return The start {@link Date} from which this {@link Trigger} will be valid. * @since 1.0.0 */ - Date getEndsOn(); + public Date getEndsOn() { + return endsOn; + } /** * Gets the end {@link Date} until which this {@link Trigger} will be valid. *

        * {@code null} means that never expires. * - * @param endsOn The end {@link Date} until which this {@link Trigger} will be valid. + * @param endsOn + * The end {@link Date} until which this {@link Trigger} will be valid. * @since 1.0.0 */ - void setEndsOn(Date endsOn); + public void setEndsOn(Date endsOn) { + this.endsOn = endsOn; + } /** * Gets the CRON scheduling. @@ -82,19 +114,24 @@ public interface TriggerCreator extends KapuaNamedEntityCreator { * @deprecated since 1.1.0 */ @Deprecated - String getCronScheduling(); + public String getCronScheduling() { + return cronScheduling; + } /** * Sets the CRON scheduling. *

        * This field is {@code deprecated}. Please make use of {@link org.eclipse.kapua.service.scheduler.trigger.definition.TriggerDefinition} and {@link TriggerProperty}es. * - * @param cronScheduling The CRON scheduling. + * @param cronScheduling + * The CRON scheduling. * @since 1.0.0 * @deprecated since 1.1.0 */ @Deprecated - void setCronScheduling(String cronScheduling); + public void setCronScheduling(String cronScheduling) { + this.cronScheduling = cronScheduling; + } /** * Gets the retry interval. @@ -106,19 +143,24 @@ public interface TriggerCreator extends KapuaNamedEntityCreator { * @deprecated since 1.1.0 */ @Deprecated - Long getRetryInterval(); + public Long getRetryInterval() { + return retryInterval; + } /** * Sets the retry interval. *

        * This field is {@code deprecated}. Please make use of {@link org.eclipse.kapua.service.scheduler.trigger.definition.TriggerDefinition} and {@link TriggerProperty}es. * - * @param retryInterval The retry interval. + * @param retryInterval + * The retry interval. * @since 1.0.0 * @deprecated since 1.1.0 */ @Deprecated - void setRetryInterval(Long retryInterval); + public void setRetryInterval(Long retryInterval) { + this.retryInterval = retryInterval; + } /** * Gets the {@link org.eclipse.kapua.service.scheduler.trigger.definition.TriggerDefinition} {@link KapuaId} which this {@link TriggerCreator} refers to. @@ -127,15 +169,20 @@ public interface TriggerCreator extends KapuaNamedEntityCreator { * @since 1.1.0 */ @XmlJavaTypeAdapter(KapuaIdAdapter.class) - KapuaId getTriggerDefinitionId(); + public KapuaId getTriggerDefinitionId() { + return triggerDefinitionId; + } /** * Sets the {@link org.eclipse.kapua.service.scheduler.trigger.definition.TriggerDefinition} {@link KapuaId} which this {@link TriggerCreator} refers to. * - * @param triggerDefinitionId The {@link org.eclipse.kapua.service.scheduler.trigger.definition.TriggerDefinition} {@link KapuaId} which this {@link TriggerCreator} refers to. + * @param triggerDefinitionId + * The {@link org.eclipse.kapua.service.scheduler.trigger.definition.TriggerDefinition} {@link KapuaId} which this {@link TriggerCreator} refers to. * @since 1.1.0 */ - void setTriggerDefinitionId(KapuaId triggerDefinitionId); + public void setTriggerDefinitionId(KapuaId triggerDefinitionId) { + this.triggerDefinitionId = triggerDefinitionId; + } /** * Gets the {@link List} of {@link TriggerProperty}es associated with this {@link TriggerCreator} @@ -143,22 +190,35 @@ public interface TriggerCreator extends KapuaNamedEntityCreator { * @return The {@link List} of {@link TriggerProperty}es associated with this {@link TriggerCreator} * @since 1.0.0 */ - List getTriggerProperties(); + public List getTriggerProperties() { + if (triggerProperties == null) { + triggerProperties = new ArrayList<>(); + } + + return triggerProperties; + } /** * Gets the {@link TriggerProperty} by the name. * - * @param name The {@link TriggerProperty#getName()} to look for. + * @param name + * The {@link TriggerProperty#getName()} to look for. * @return The found {@link TriggerProperty} or {@code null}. * @since 1.5.0 */ - TriggerProperty getTriggerProperty(String name); + public TriggerProperty getTriggerProperty(String name) { + return getTriggerProperties().stream().filter(tp -> tp.getName().equals(name)).findAny().orElse(null); + } /** * Sets the {@link List} of {@link TriggerProperty}es associated with this {@link TriggerCreator} * - * @param triggerProperties The {@link List} of {@link TriggerProperty}es associated with this {@link TriggerCreator} + * @param triggerProperties + * The {@link List} of {@link TriggerProperty}es associated with this {@link TriggerCreator} * @since 1.0.0 */ - void setTriggerProperties(List triggerProperties); + public void setTriggerProperties(List triggerProperties) { + this.triggerProperties = triggerProperties; + } + } diff --git a/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/TriggerFactory.java b/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/TriggerFactory.java index cbf4d65b3af..ff843fa3eaf 100644 --- a/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/TriggerFactory.java +++ b/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/TriggerFactory.java @@ -21,14 +21,17 @@ * @see KapuaEntityFactory * @since 1.0.0 */ -public interface TriggerFactory extends KapuaEntityFactory { +public interface TriggerFactory extends KapuaEntityFactory { /** * Instantiates a new {@link TriggerProperty} * - * @param name The name to set into the {@link TriggerProperty}. - * @param type The type to set into the {@link TriggerProperty}. - * @param value The value to set into the {@link TriggerProperty}. + * @param name + * The name to set into the {@link TriggerProperty}. + * @param type + * The type to set into the {@link TriggerProperty}. + * @param value + * The value to set into the {@link TriggerProperty}. * @return The newly instatiated {@link TriggerProperty}. * @since 1.0.0 */ diff --git a/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/TriggerListResult.java b/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/TriggerListResult.java index 13d9269bb76..b66c2033051 100644 --- a/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/TriggerListResult.java +++ b/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/TriggerListResult.java @@ -12,13 +12,13 @@ *******************************************************************************/ package org.eclipse.kapua.service.scheduler.trigger; -import org.eclipse.kapua.model.query.KapuaListResult; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; +import org.eclipse.kapua.model.query.KapuaListResult; + /** * {@link Trigger} {@link KapuaListResult} definition. * @@ -27,6 +27,9 @@ */ @XmlRootElement(name = "scheduleListResult") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = TriggerXmlRegistry.class, factoryMethod = "newListResult") -public interface TriggerListResult extends KapuaListResult { +@XmlType +public class TriggerListResult extends KapuaListResult { + + private static final long serialVersionUID = -5118004898345748297L; + } diff --git a/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/TriggerQuery.java b/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/TriggerQuery.java deleted file mode 100644 index e07a98ba0be..00000000000 --- a/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/TriggerQuery.java +++ /dev/null @@ -1,32 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2017, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.scheduler.trigger; - -import org.eclipse.kapua.model.query.KapuaQuery; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlType; - -/** - * {@link Trigger} {@link KapuaQuery} definition. - * - * @see KapuaQuery - * @since 1.0.0 - */ -@XmlRootElement(name = "query") -@XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = TriggerXmlRegistry.class, factoryMethod = "newQuery") -public interface TriggerQuery extends KapuaQuery { -} diff --git a/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/TriggerService.java b/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/TriggerService.java index 18be0ccb49d..75e305a6a4f 100644 --- a/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/TriggerService.java +++ b/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/TriggerService.java @@ -31,7 +31,8 @@ public interface TriggerService extends KapuaEntityService { +@XmlType +public class TriggerDefinitionCreator extends KapuaNamedEntityCreator { + + private static final long serialVersionUID = 4602067255120049746L; + + private TriggerType triggerType; + private String processorName; + private List triggerProperties; + + public TriggerDefinitionCreator() { + } + + public TriggerDefinitionCreator(KapuaId scopeId) { + super(scopeId); + } + + public TriggerDefinitionCreator(KapuaId scopeId, String name) { + super(scopeId, name); + } /** * Gets the {@link TriggerType}. @@ -36,15 +56,20 @@ public interface TriggerDefinitionCreator extends KapuaNamedEntityCreator getTriggerProperties(); + public List getTriggerProperties() { + if (triggerProperties == null) { + triggerProperties = new ArrayList<>(); + } + + return triggerProperties; + } /** * Gets the {@link TriggerProperty} by the name. * - * @param name The {@link TriggerProperty#getName()} to look for. + * @param name + * The {@link TriggerProperty#getName()} to look for. * @return The found {@link TriggerProperty} or {@code null}. * @since 1.5.0 */ - TriggerProperty getTriggerProperty(String name); + public TriggerProperty getTriggerProperty(String name) { + return getTriggerProperties().stream().filter(tp -> tp.getName().equals(name)).findAny().orElse(null); + } /** * Sets the {@link TriggerProperty}s. * - * @param triggerProperties The {@link TriggerProperty}s. + * @param triggerProperties + * The {@link TriggerProperty}s. * @since 1.1.0 */ - void setTriggerProperties(List triggerProperties); + public void setTriggerProperties(List triggerProperties) { + this.triggerProperties = triggerProperties; + } } diff --git a/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/definition/TriggerDefinitionFactory.java b/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/definition/TriggerDefinitionFactory.java index fac9db3f880..008d7b4d29b 100644 --- a/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/definition/TriggerDefinitionFactory.java +++ b/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/definition/TriggerDefinitionFactory.java @@ -20,14 +20,17 @@ * @see KapuaEntityFactory * @since 1.1.0 */ -public interface TriggerDefinitionFactory extends KapuaEntityFactory { +public interface TriggerDefinitionFactory extends KapuaEntityFactory { /** * Instantiates a new {@link TriggerProperty}. * - * @param name The name to set into the {@link TriggerProperty}. - * @param type The type to set into the {@link TriggerProperty}. - * @param value The value to set into the {@link TriggerProperty}. + * @param name + * The name to set into the {@link TriggerProperty}. + * @param type + * The type to set into the {@link TriggerProperty}. + * @param value + * The value to set into the {@link TriggerProperty}. * @return The newly instantiated {@link TriggerProperty}. * @since 1.1.0 */ diff --git a/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/definition/TriggerDefinitionListResult.java b/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/definition/TriggerDefinitionListResult.java index 82e707bc26b..b7aa84a052f 100644 --- a/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/definition/TriggerDefinitionListResult.java +++ b/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/definition/TriggerDefinitionListResult.java @@ -12,13 +12,13 @@ *******************************************************************************/ package org.eclipse.kapua.service.scheduler.trigger.definition; -import org.eclipse.kapua.model.query.KapuaListResult; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; +import org.eclipse.kapua.model.query.KapuaListResult; + /** * {@link TriggerDefinition} {@link KapuaListResult} definition. * @@ -27,7 +27,9 @@ */ @XmlRootElement(name = "triggerDefinitionListResult") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = TriggerDefinitionXmlRegistry.class, factoryMethod = "newListResult") -public interface TriggerDefinitionListResult extends KapuaListResult { +@XmlType +public class TriggerDefinitionListResult extends KapuaListResult { + + private static final long serialVersionUID = 977813250632719295L; } diff --git a/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/definition/TriggerDefinitionQuery.java b/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/definition/TriggerDefinitionQuery.java index 1d7b2c6dea7..d6ff5d7e069 100644 --- a/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/definition/TriggerDefinitionQuery.java +++ b/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/definition/TriggerDefinitionQuery.java @@ -12,13 +12,15 @@ *******************************************************************************/ package org.eclipse.kapua.service.scheduler.trigger.definition; -import org.eclipse.kapua.model.query.KapuaQuery; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; +import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.query.AbstractKapuaNamedQuery; +import org.eclipse.kapua.model.query.KapuaQuery; + /** * {@link TriggerDefinition} {@link KapuaQuery} definition. * @@ -27,6 +29,17 @@ */ @XmlRootElement(name = "query") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = TriggerDefinitionXmlRegistry.class, factoryMethod = "newQuery") -public interface TriggerDefinitionQuery extends KapuaQuery { +@XmlType +public class TriggerDefinitionQuery extends AbstractKapuaNamedQuery { + + public TriggerDefinitionQuery() { + } + + public TriggerDefinitionQuery(KapuaId scopeId) { + super(scopeId); + } + + public TriggerDefinitionQuery(KapuaQuery query) { + super(query); + } } diff --git a/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/definition/TriggerDefinitionRecord.java b/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/definition/TriggerDefinitionRecord.java index 4a5fe4ac9f4..d249da96409 100644 --- a/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/definition/TriggerDefinitionRecord.java +++ b/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/definition/TriggerDefinitionRecord.java @@ -12,14 +12,14 @@ *******************************************************************************/ package org.eclipse.kapua.service.scheduler.trigger.definition; -import org.eclipse.kapua.entity.EntityPropertiesReadException; -import org.eclipse.kapua.entity.EntityPropertiesWriteException; -import org.eclipse.kapua.model.id.KapuaId; - import java.util.Date; import java.util.List; import java.util.Properties; +import org.eclipse.kapua.entity.EntityPropertiesReadException; +import org.eclipse.kapua.entity.EntityPropertiesWriteException; +import org.eclipse.kapua.model.id.KapuaId; + public class TriggerDefinitionRecord implements TriggerDefinition { private KapuaId scopeId; @@ -33,11 +33,11 @@ public class TriggerDefinitionRecord implements TriggerDefinition { private List triggerProperties; public TriggerDefinitionRecord(KapuaId scopeId, - String name, - String description, - TriggerType triggerType, - String processorName, - List triggerProperties) { + String name, + String description, + TriggerType triggerType, + String processorName, + List triggerProperties) { this.scopeId = scopeId; this.name = name; this.description = description; diff --git a/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/definition/TriggerDefinitionXmlRegistry.java b/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/definition/TriggerDefinitionXmlRegistry.java index 6303d16a524..c363543b701 100644 --- a/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/definition/TriggerDefinitionXmlRegistry.java +++ b/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/definition/TriggerDefinitionXmlRegistry.java @@ -12,10 +12,10 @@ *******************************************************************************/ package org.eclipse.kapua.service.scheduler.trigger.definition; -import org.eclipse.kapua.locator.KapuaLocator; - import javax.xml.bind.annotation.XmlRegistry; +import org.eclipse.kapua.locator.KapuaLocator; + /** * {@link TriggerDefinition} xml factory class * @@ -30,15 +30,4 @@ public TriggerDefinition newEntity() { return triggerDefinitionFactory.newEntity(null); } - public TriggerDefinitionCreator newCreator() { - return triggerDefinitionFactory.newCreator(null); - } - - public TriggerDefinitionListResult newListResult() { - return triggerDefinitionFactory.newListResult(); - } - - public TriggerDefinitionQuery newQuery() { - return triggerDefinitionFactory.newQuery(null); - } } diff --git a/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/fired/FiredTriggerCreator.java b/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/fired/FiredTriggerCreator.java index 56a707972fe..1ab7ca1c101 100644 --- a/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/fired/FiredTriggerCreator.java +++ b/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/fired/FiredTriggerCreator.java @@ -12,10 +12,7 @@ *******************************************************************************/ package org.eclipse.kapua.service.scheduler.trigger.fired; -import org.eclipse.kapua.model.KapuaEntityCreator; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.model.id.KapuaIdAdapter; -import org.eclipse.kapua.service.scheduler.trigger.Trigger; +import java.util.Date; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; @@ -23,7 +20,11 @@ import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; -import java.util.Date; + +import org.eclipse.kapua.model.KapuaEntityCreator; +import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.id.KapuaIdAdapter; +import org.eclipse.kapua.service.scheduler.trigger.Trigger; /** * {@link FiredTrigger} {@link org.eclipse.kapua.model.KapuaEntityCreator} definition. @@ -32,8 +33,24 @@ */ @XmlRootElement(name = "firedTriggerCreator") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = FiredTriggerXmlRegistry.class, factoryMethod = "newCreator") -public interface FiredTriggerCreator extends KapuaEntityCreator { +@XmlType +public class FiredTriggerCreator extends KapuaEntityCreator { + + private KapuaId triggerId; + private Date firedOn; + private FiredTriggerStatus status; + private String message; + + public FiredTriggerCreator() { + } + + public FiredTriggerCreator(KapuaId scopeId) { + super(scopeId); + } + + public FiredTriggerCreator(KapuaEntityCreator entityCreator) { + super(entityCreator); + } /** * Gets the {@link Trigger#getId()} @@ -43,15 +60,20 @@ public interface FiredTriggerCreator extends KapuaEntityCreator { */ @XmlElement(name = "triggerId") @XmlJavaTypeAdapter(KapuaIdAdapter.class) - KapuaId getTriggerId(); + public KapuaId getTriggerId() { + return triggerId; + } /** * Sets the {@link Trigger#getId()}. * - * @param triggerId The {@link Trigger#getId()}. + * @param triggerId + * The {@link Trigger#getId()}. * @since 1.5.0 */ - void setTriggerId(KapuaId triggerId); + public void setTriggerId(KapuaId triggerId) { + this.triggerId = triggerId; + } /** * Gets the actual fire {@link Date}. @@ -60,15 +82,20 @@ public interface FiredTriggerCreator extends KapuaEntityCreator { * @since 1.5.0 */ @XmlElement(name = "firedOn") - Date getFiredOn(); + public Date getFiredOn() { + return firedOn; + } /** * Sets the actual fire {@link Date}. * - * @param firedOn The actual fire {@link Date}. + * @param firedOn + * The actual fire {@link Date}. * @since 1.5.0 */ - void setFiredOn(Date firedOn); + public void setFiredOn(Date firedOn) { + this.firedOn = firedOn; + } /** * Gets the {@link FiredTriggerStatus} of the processing. @@ -77,15 +104,20 @@ public interface FiredTriggerCreator extends KapuaEntityCreator { * @since 1.5.0 */ @XmlElement(name = "status") - FiredTriggerStatus getStatus(); + public FiredTriggerStatus getStatus() { + return status; + } /** * Sets the {@link FiredTriggerStatus} of the processing. * - * @param status The {@link FiredTriggerStatus} of the processing. + * @param status + * The {@link FiredTriggerStatus} of the processing. * @since 1.5.0 */ - void setStatus(FiredTriggerStatus status); + public void setStatus(FiredTriggerStatus status) { + this.status = status; + } /** * Gets the {@link Exception#getMessage()} if there are errors in the processing. @@ -94,13 +126,19 @@ public interface FiredTriggerCreator extends KapuaEntityCreator { * @since 1.5.0 */ @XmlElement(name = "message") - String getMessage(); + public String getMessage() { + return message; + } /** * Sets the {@link Exception#getMessage()} if there are errors in the processing. * - * @param message The {@link Exception#getMessage()} if there are errors in the processing. + * @param message + * The {@link Exception#getMessage()} if there are errors in the processing. * @since 1.5.0 */ - void setMessage(String message); + public void setMessage(String message) { + this.message = message; + } + } diff --git a/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/fired/FiredTriggerFactory.java b/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/fired/FiredTriggerFactory.java index 01a68558f16..526d3c5f344 100644 --- a/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/fired/FiredTriggerFactory.java +++ b/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/fired/FiredTriggerFactory.java @@ -20,5 +20,6 @@ * @see KapuaEntityFactory * @since 1.5.0 */ -public interface FiredTriggerFactory extends KapuaEntityFactory { +public interface FiredTriggerFactory extends KapuaEntityFactory { + } diff --git a/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/fired/FiredTriggerListResult.java b/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/fired/FiredTriggerListResult.java index 4f0a10bbfe0..e58137f685b 100644 --- a/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/fired/FiredTriggerListResult.java +++ b/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/fired/FiredTriggerListResult.java @@ -12,13 +12,13 @@ *******************************************************************************/ package org.eclipse.kapua.service.scheduler.trigger.fired; -import org.eclipse.kapua.model.query.KapuaListResult; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; +import org.eclipse.kapua.model.query.KapuaListResult; + /** * {@link FiredTrigger} {@link KapuaListResult} definition. * @@ -26,7 +26,7 @@ */ @XmlRootElement(name = "firedTriggerListResult") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = FiredTriggerXmlRegistry.class, factoryMethod = "newListResult") -public interface FiredTriggerListResult extends KapuaListResult { +@XmlType +public class FiredTriggerListResult extends KapuaListResult { } diff --git a/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/fired/FiredTriggerQuery.java b/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/fired/FiredTriggerQuery.java deleted file mode 100644 index 931f70d3a7c..00000000000 --- a/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/fired/FiredTriggerQuery.java +++ /dev/null @@ -1,32 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.scheduler.trigger.fired; - -import org.eclipse.kapua.model.query.KapuaQuery; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlType; - -/** - * {@link FiredTrigger} {@link KapuaQuery} definition. - * - * @see KapuaQuery - * @since 1.5.0 - */ -@XmlRootElement(name = "query") -@XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = FiredTriggerXmlRegistry.class, factoryMethod = "newQuery") -public interface FiredTriggerQuery extends KapuaQuery { -} diff --git a/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/fired/FiredTriggerService.java b/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/fired/FiredTriggerService.java index 4b1b46d6db9..c0f7684b0aa 100644 --- a/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/fired/FiredTriggerService.java +++ b/service/scheduler/api/src/main/java/org/eclipse/kapua/service/scheduler/trigger/fired/FiredTriggerService.java @@ -27,7 +27,8 @@ public interface FiredTriggerService extends KapuaEntityService org.eclipse.kapua kapua-service - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT pom diff --git a/service/scheduler/quartz/pom.xml b/service/scheduler/quartz/pom.xml index ca1128d8d78..759f9e0d5e3 100644 --- a/service/scheduler/quartz/pom.xml +++ b/service/scheduler/quartz/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-scheduler - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-scheduler-quartz diff --git a/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/quartz/job/KapuaJobLauncher.java b/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/quartz/job/KapuaJobLauncher.java index ff2ae6d1f96..ac1d0e8b06d 100644 --- a/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/quartz/job/KapuaJobLauncher.java +++ b/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/quartz/job/KapuaJobLauncher.java @@ -12,6 +12,11 @@ *******************************************************************************/ package org.eclipse.kapua.service.scheduler.quartz.job; +import java.util.Date; + +import javax.validation.constraints.NotNull; + +import org.checkerframework.checker.nullness.qual.Nullable; import org.eclipse.kapua.KapuaEntityNotFoundException; import org.eclipse.kapua.commons.security.KapuaSecurityUtils; import org.eclipse.kapua.job.engine.JobEngineService; @@ -23,28 +28,21 @@ import org.eclipse.kapua.service.scheduler.trigger.Trigger; import org.eclipse.kapua.service.scheduler.trigger.fired.FiredTrigger; import org.eclipse.kapua.service.scheduler.trigger.fired.FiredTriggerCreator; -import org.eclipse.kapua.service.scheduler.trigger.fired.FiredTriggerFactory; import org.eclipse.kapua.service.scheduler.trigger.fired.FiredTriggerService; import org.eclipse.kapua.service.scheduler.trigger.fired.FiredTriggerStatus; - -import org.checkerframework.checker.nullness.qual.Nullable; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.validation.constraints.NotNull; -import java.util.Date; - /** * Ths is the {@link Job} that triggers the {@link JobEngineService#startJob(KapuaId, KapuaId)}. *

        - * In case of successful start it creates a {@link FiredTrigger} to track that {@link JobEngineService#startJob(KapuaId, KapuaId)} - * was successful + * In case of successful start it creates a {@link FiredTrigger} to track that {@link JobEngineService#startJob(KapuaId, KapuaId)} was successful *

        - * In case of {@link Exception} from {@link JobEngineService#startJob(KapuaId, KapuaId)} it saves the {@link Exception#getMessage()} - * into the {@link FiredTrigger#getMessage()} to let the user be able to solve the issue. + * In case of {@link Exception} from {@link JobEngineService#startJob(KapuaId, KapuaId)} it saves the {@link Exception#getMessage()} into the {@link FiredTrigger#getMessage()} to let the user be able + * to solve the issue. * * @since 1.0.0 */ @@ -60,7 +58,6 @@ public class KapuaJobLauncher implements Job { JobEngineService jobEngineService = locator.getService(JobEngineService.class); FiredTriggerService firedTriggerService = locator.getService(FiredTriggerService.class); - FiredTriggerFactory firedTriggerFactory = locator.getFactory(FiredTriggerFactory.class); private KapuaId scopeId; private KapuaId jobId; @@ -123,7 +120,8 @@ public KapuaId getScopeId() { /** * Sets the {@link org.eclipse.kapua.service.job.Job#getScopeId()}. * - * @param scopeId The {@link org.eclipse.kapua.service.job.Job#getScopeId()}. + * @param scopeId + * The {@link org.eclipse.kapua.service.job.Job#getScopeId()}. * @since 1.0.0 */ public void setScopeId(KapuaId scopeId) { @@ -143,7 +141,8 @@ public KapuaId getJobId() { /** * Sets the {@link org.eclipse.kapua.service.job.Job#getId()}. * - * @param jobId The {@link org.eclipse.kapua.service.job.Job#getId()}. + * @param jobId + * The {@link org.eclipse.kapua.service.job.Job#getId()}. * @since 1.0.0 */ public void setJobId(KapuaId jobId) { @@ -163,7 +162,8 @@ public JobStartOptions getJobStartOptions() { /** * Sets the {@link org.eclipse.kapua.service.job.Job}'s {@link JobStartOptions}. * - * @param jobStartOptions The {@link org.eclipse.kapua.service.job.Job}'s {@link JobStartOptions}. + * @param jobStartOptions + * The {@link org.eclipse.kapua.service.job.Job}'s {@link JobStartOptions}. * @since 1.0.0 */ public void setJobStartOptions(JobStartOptions jobStartOptions) { @@ -173,9 +173,12 @@ public void setJobStartOptions(JobStartOptions jobStartOptions) { /** * Creates a {@link FiredTrigger} with {@link FiredTriggerStatus#FIRED}. * - * @param scopeId The {@link Trigger#getScopeId()}. - * @param triggerId The {@link Trigger#getId()}. - * @param fireTime The actual {@link Trigger} fire time. Sourced from {@link JobExecutionContext#getFireTime()}. + * @param scopeId + * The {@link Trigger#getScopeId()}. + * @param triggerId + * The {@link Trigger#getId()}. + * @param fireTime + * The actual {@link Trigger} fire time. Sourced from {@link JobExecutionContext#getFireTime()}. * @since 1.5.0 */ public void createSuccessfulFiredTrigger(@NotNull KapuaId scopeId, @NotNull KapuaId triggerId, @NotNull Date fireTime) { @@ -185,10 +188,14 @@ public void createSuccessfulFiredTrigger(@NotNull KapuaId scopeId, @NotNull Kapu /** * Creates a {@link FiredTrigger} with {@link FiredTriggerStatus#FAILED}. * - * @param scopeId The {@link Trigger#getScopeId()}. - * @param triggerId The {@link Trigger#getId()}. - * @param fireTime The actual {@link Trigger} fire time. Sourced from {@link JobExecutionContext#getFireTime()}. - * @param exception The {@link Exception} occurred while processing. + * @param scopeId + * The {@link Trigger#getScopeId()}. + * @param triggerId + * The {@link Trigger#getId()}. + * @param fireTime + * The actual {@link Trigger} fire time. Sourced from {@link JobExecutionContext#getFireTime()}. + * @param exception + * The {@link Exception} occurred while processing. * @since 1.5.0 */ public void createdUnsuccessfulFiredTrigger(@NotNull KapuaId scopeId, @NotNull KapuaId triggerId, @NotNull Date fireTime, @NotNull Exception exception) { @@ -198,16 +205,21 @@ public void createdUnsuccessfulFiredTrigger(@NotNull KapuaId scopeId, @NotNull K /** * Creates a {@link FiredTrigger} with the given parameters. * - * @param scopeId The {@link Trigger#getScopeId()}. - * @param triggerId The {@link Trigger#getId()}. - * @param fireTime The actual {@link Trigger} fire time. Sourced from {@link JobExecutionContext#getFireTime()}. - * @param status The {@link FiredTriggerStatus} of the processing. - * @param exception The {@link Exception} occurred while processing, if any. + * @param scopeId + * The {@link Trigger#getScopeId()}. + * @param triggerId + * The {@link Trigger#getId()}. + * @param fireTime + * The actual {@link Trigger} fire time. Sourced from {@link JobExecutionContext#getFireTime()}. + * @param status + * The {@link FiredTriggerStatus} of the processing. + * @param exception + * The {@link Exception} occurred while processing, if any. * @since 1.5.0 */ public void createFiredTrigger(@NotNull KapuaId scopeId, @NotNull KapuaId triggerId, @NotNull Date fireTime, @NotNull FiredTriggerStatus status, @Nullable Exception exception) { try { - FiredTriggerCreator firedTriggerCreator = firedTriggerFactory.newCreator(scopeId); + FiredTriggerCreator firedTriggerCreator = new FiredTriggerCreator(scopeId); firedTriggerCreator.setTriggerId(triggerId); firedTriggerCreator.setFiredOn(fireTime); firedTriggerCreator.setStatus(status); diff --git a/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/definition/quartz/SchedulerTriggerDefinitionModule.java b/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/definition/quartz/SchedulerTriggerDefinitionModule.java index dc359876a66..20819c62ae0 100644 --- a/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/definition/quartz/SchedulerTriggerDefinitionModule.java +++ b/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/definition/quartz/SchedulerTriggerDefinitionModule.java @@ -12,23 +12,23 @@ *******************************************************************************/ package org.eclipse.kapua.service.scheduler.trigger.definition.quartz; -import com.google.inject.Provides; -import com.google.inject.multibindings.ProvidesIntoSet; +import javax.inject.Named; +import javax.inject.Singleton; + import org.eclipse.kapua.commons.core.AbstractKapuaModule; import org.eclipse.kapua.commons.jpa.KapuaJpaRepositoryConfiguration; -import org.eclipse.kapua.commons.jpa.KapuaJpaTxManagerFactory; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; import org.eclipse.kapua.service.scheduler.trigger.definition.TriggerDefinition; import org.eclipse.kapua.service.scheduler.trigger.definition.TriggerDefinitionFactory; import org.eclipse.kapua.service.scheduler.trigger.definition.TriggerDefinitionRepository; import org.eclipse.kapua.service.scheduler.trigger.definition.TriggerDefinitionService; import org.eclipse.kapua.storage.TxManager; -import javax.inject.Named; -import javax.inject.Singleton; +import com.google.inject.Provides; +import com.google.inject.multibindings.ProvidesIntoSet; public class SchedulerTriggerDefinitionModule extends AbstractKapuaModule { + @Override protected void configureModule() { bind(TriggerDefinitionFactory.class).to(TriggerDefinitionFactoryImpl.class); @@ -38,14 +38,11 @@ protected void configureModule() { @Singleton TriggerDefinitionService triggerDefinitionService( AuthorizationService authorizationService, - PermissionFactory permissionFactory, @Named("schedulerTxManager") TxManager txManager, TriggerDefinitionRepository triggerDefinitionRepository, - TriggerDefinitionFactory triggerDefinitionFactory, - KapuaJpaTxManagerFactory jpaTxManagerFactory) { + TriggerDefinitionFactory triggerDefinitionFactory) { return new TriggerDefinitionServiceImpl( authorizationService, - permissionFactory, txManager, triggerDefinitionRepository, triggerDefinitionFactory); @@ -57,7 +54,6 @@ TriggerDefinitionRepository triggerDefinitionRepository(KapuaJpaRepositoryConfig return new TriggerDefinitionImplJpaRepository(jpaRepoConfig); } - @ProvidesIntoSet public TriggerDefinition cronJobTriggerDefinition() { return new CronJobTriggerDefinition(); diff --git a/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/definition/quartz/TriggerDefinitionAligner.java b/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/definition/quartz/TriggerDefinitionAligner.java index 06c6e87850b..f8569ceed4d 100644 --- a/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/definition/quartz/TriggerDefinitionAligner.java +++ b/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/definition/quartz/TriggerDefinitionAligner.java @@ -12,12 +12,25 @@ *******************************************************************************/ package org.eclipse.kapua.service.scheduler.trigger.definition.quartz; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; + +import javax.inject.Inject; +import javax.inject.Named; +import javax.persistence.EntityManager; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.commons.jpa.JpaAwareTxContext; import org.eclipse.kapua.commons.security.KapuaSecurityUtils; import org.eclipse.kapua.locator.initializers.KapuaInitializingMethod; import org.eclipse.kapua.model.KapuaNamedEntity; import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.service.scheduler.trigger.definition.TriggerDefinition; import org.eclipse.kapua.service.scheduler.trigger.definition.TriggerDefinitionRepository; import org.eclipse.kapua.service.scheduler.trigger.definition.TriggerProperty; @@ -26,17 +39,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.inject.Inject; -import javax.inject.Named; -import javax.persistence.EntityManager; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import java.util.stream.Collectors; - /** * This aligner aligns the declared {@link TriggerDefinition}s in each module with the database. * @@ -90,7 +92,7 @@ public void populate() { KapuaSecurityUtils.doPrivileged(() -> { txManager.execute(tx -> { // Retrieve all TriggerDefinition from the database - List dbTriggerDefinitions = triggerDefinitionRepository.query(tx, new TriggerDefinitionQueryImpl(null)).getItems() + List dbTriggerDefinitions = triggerDefinitionRepository.query(tx, new KapuaQuery((KapuaId) null)).getItems() .stream() .map(dbTriggrDefinition -> (TriggerDefinitionImpl) dbTriggrDefinition) .collect(Collectors.toList()); @@ -242,8 +244,7 @@ private void alignTriggerDefinitions(TxContext txContext, TriggerDefinitionImpl if (triggerProperty == null) { LOG.info("Database TriggerProperty '{}' is not wired... Removing from database", dbTriggerPropertyEntity.getTriggerProperty().getName()); return true; - } - else { + } else { return false; } }); diff --git a/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/definition/quartz/TriggerDefinitionCreatorImpl.java b/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/definition/quartz/TriggerDefinitionCreatorImpl.java deleted file mode 100644 index 65a9fa2bc2f..00000000000 --- a/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/definition/quartz/TriggerDefinitionCreatorImpl.java +++ /dev/null @@ -1,87 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2019, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.scheduler.trigger.definition.quartz; - -import org.eclipse.kapua.commons.model.AbstractKapuaNamedEntityCreator; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.scheduler.trigger.definition.TriggerDefinition; -import org.eclipse.kapua.service.scheduler.trigger.definition.TriggerDefinitionCreator; -import org.eclipse.kapua.service.scheduler.trigger.definition.TriggerProperty; -import org.eclipse.kapua.service.scheduler.trigger.definition.TriggerType; - -import java.util.ArrayList; -import java.util.List; - -/** - * {@link TriggerDefinitionCreator} implementation. - * - * @since 1.1.0 - */ -public class TriggerDefinitionCreatorImpl extends AbstractKapuaNamedEntityCreator implements TriggerDefinitionCreator { - - private static final long serialVersionUID = 4602067255120049746L; - - private TriggerType triggerType; - private String processorName; - private List triggerProperties; - - /** - * Constructor. - * - * @param scopeId The scope {@link KapuaId} for the Trigger. - * @since 1.1.0 - */ - public TriggerDefinitionCreatorImpl(KapuaId scopeId) { - super(scopeId); - } - - @Override - public TriggerType getTriggerType() { - return triggerType; - } - - @Override - public void setTriggerType(TriggerType triggerType) { - this.triggerType = triggerType; - } - - @Override - public String getProcessorName() { - return processorName; - } - - @Override - public void setProcessorName(String processorName) { - this.processorName = processorName; - } - - @Override - public List getTriggerProperties() { - if (triggerProperties == null) { - triggerProperties = new ArrayList<>(); - } - - return triggerProperties; - } - - @Override - public TriggerProperty getTriggerProperty(String name) { - return getTriggerProperties().stream().filter(tp -> tp.getName().equals(name)).findAny().orElse(null); - } - - @Override - public void setTriggerProperties(List triggerProperties) { - this.triggerProperties = triggerProperties; - } - -} diff --git a/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/definition/quartz/TriggerDefinitionFactoryImpl.java b/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/definition/quartz/TriggerDefinitionFactoryImpl.java index f69c6742196..5559e0d8380 100644 --- a/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/definition/quartz/TriggerDefinitionFactoryImpl.java +++ b/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/definition/quartz/TriggerDefinitionFactoryImpl.java @@ -12,17 +12,14 @@ *******************************************************************************/ package org.eclipse.kapua.service.scheduler.trigger.definition.quartz; +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaEntityCloneException; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.scheduler.trigger.definition.TriggerDefinition; -import org.eclipse.kapua.service.scheduler.trigger.definition.TriggerDefinitionCreator; import org.eclipse.kapua.service.scheduler.trigger.definition.TriggerDefinitionFactory; -import org.eclipse.kapua.service.scheduler.trigger.definition.TriggerDefinitionListResult; -import org.eclipse.kapua.service.scheduler.trigger.definition.TriggerDefinitionQuery; import org.eclipse.kapua.service.scheduler.trigger.definition.TriggerProperty; -import javax.inject.Singleton; - /** * {@link TriggerDefinitionFactory} implementation. * @@ -36,21 +33,6 @@ public TriggerDefinition newEntity(KapuaId scopeId) { return new TriggerDefinitionImpl(scopeId); } - @Override - public TriggerDefinitionCreator newCreator(KapuaId scopeId) { - return new TriggerDefinitionCreatorImpl(scopeId); - } - - @Override - public TriggerDefinitionQuery newQuery(KapuaId scopeId) { - return new TriggerDefinitionQueryImpl(scopeId); - } - - @Override - public TriggerDefinitionListResult newListResult() { - return new TriggerDefinitionListResultImpl(); - } - @Override public TriggerProperty newTriggerProperty(String name, String type, String value) { return new TriggerPropertyImpl(name, type, value); diff --git a/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/definition/quartz/TriggerDefinitionImplJpaRepository.java b/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/definition/quartz/TriggerDefinitionImplJpaRepository.java index 5d1ab2ce348..224fc38e96e 100644 --- a/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/definition/quartz/TriggerDefinitionImplJpaRepository.java +++ b/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/definition/quartz/TriggerDefinitionImplJpaRepository.java @@ -21,7 +21,8 @@ public class TriggerDefinitionImplJpaRepository extends KapuaNamedEntityJpaRepository implements TriggerDefinitionRepository { + public TriggerDefinitionImplJpaRepository(KapuaJpaRepositoryConfiguration jpaRepoConfig) { - super(TriggerDefinitionImpl.class, TriggerDefinition.TYPE, () -> new TriggerDefinitionListResultImpl(), jpaRepoConfig); + super(TriggerDefinitionImpl.class, TriggerDefinition.TYPE, () -> new TriggerDefinitionListResult(), jpaRepoConfig); } } diff --git a/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/definition/quartz/TriggerDefinitionListResultImpl.java b/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/definition/quartz/TriggerDefinitionListResultImpl.java deleted file mode 100644 index 978cd775cc6..00000000000 --- a/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/definition/quartz/TriggerDefinitionListResultImpl.java +++ /dev/null @@ -1,28 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2019, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.scheduler.trigger.definition.quartz; - -import org.eclipse.kapua.commons.model.query.KapuaListResultImpl; -import org.eclipse.kapua.service.scheduler.trigger.definition.TriggerDefinition; -import org.eclipse.kapua.service.scheduler.trigger.definition.TriggerDefinitionListResult; - -/** - * {@link TriggerDefinitionListResult} definition. - * - * @since 1.1.0 - */ -public class TriggerDefinitionListResultImpl extends KapuaListResultImpl implements TriggerDefinitionListResult { - - private static final long serialVersionUID = 977813250632719295L; - -} diff --git a/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/definition/quartz/TriggerDefinitionQueryImpl.java b/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/definition/quartz/TriggerDefinitionQueryImpl.java deleted file mode 100644 index 75167dee26e..00000000000 --- a/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/definition/quartz/TriggerDefinitionQueryImpl.java +++ /dev/null @@ -1,35 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2019, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.scheduler.trigger.definition.quartz; - -import org.eclipse.kapua.commons.model.query.AbstractKapuaNamedQuery; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.scheduler.trigger.definition.TriggerDefinitionQuery; - -/** - * {@link TriggerDefinitionQuery} implementation. - * - * @since 1.1.0 - */ -public class TriggerDefinitionQueryImpl extends AbstractKapuaNamedQuery implements TriggerDefinitionQuery { - - /** - * Constructor. - * - * @param scopeId The {@link #getScopeId()}. - * @since 1.1.0 - */ - public TriggerDefinitionQueryImpl(KapuaId scopeId) { - super(scopeId); - } -} diff --git a/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/definition/quartz/TriggerDefinitionServiceImpl.java b/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/definition/quartz/TriggerDefinitionServiceImpl.java index d1f3e0b3538..a9bbb19ad21 100755 --- a/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/definition/quartz/TriggerDefinitionServiceImpl.java +++ b/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/definition/quartz/TriggerDefinitionServiceImpl.java @@ -12,6 +12,10 @@ *******************************************************************************/ package org.eclipse.kapua.service.scheduler.trigger.definition.quartz; +import java.util.Optional; + +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaEntityNotFoundException; import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.commons.model.domains.Domains; @@ -21,7 +25,7 @@ import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; +import org.eclipse.kapua.service.authorization.permission.Permission; import org.eclipse.kapua.service.scheduler.trigger.definition.TriggerDefinition; import org.eclipse.kapua.service.scheduler.trigger.definition.TriggerDefinitionCreator; import org.eclipse.kapua.service.scheduler.trigger.definition.TriggerDefinitionFactory; @@ -30,9 +34,6 @@ import org.eclipse.kapua.service.scheduler.trigger.definition.TriggerDefinitionService; import org.eclipse.kapua.storage.TxManager; -import javax.inject.Singleton; -import java.util.Optional; - /** * {@link TriggerDefinitionService} implementation. * @@ -42,19 +43,16 @@ public class TriggerDefinitionServiceImpl implements TriggerDefinitionService { private final AuthorizationService authorizationService; - private final PermissionFactory permissionFactory; private final TxManager txManager; private final TriggerDefinitionRepository triggerDefinitionRepository; private final TriggerDefinitionFactory triggerDefinitionFactory; public TriggerDefinitionServiceImpl( AuthorizationService authorizationService, - PermissionFactory permissionFactory, TxManager txManager, TriggerDefinitionRepository triggerDefinitionRepository, TriggerDefinitionFactory triggerDefinitionFactory) { this.authorizationService = authorizationService; - this.permissionFactory = permissionFactory; this.txManager = txManager; this.triggerDefinitionRepository = triggerDefinitionRepository; this.triggerDefinitionFactory = triggerDefinitionFactory; @@ -69,7 +67,7 @@ public TriggerDefinition create(TriggerDefinitionCreator triggerDefinitionCreato ArgumentValidator.validateEntityName(triggerDefinitionCreator.getName(), "triggerDefinitionCreator.name"); // Check access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.write, null)); + authorizationService.checkPermission(new Permission(Domains.JOB, Actions.write, null)); // Do create TriggerDefinition toBeCreated = triggerDefinitionFactory.newEntity(triggerDefinitionCreator.getScopeId()); @@ -89,7 +87,7 @@ public TriggerDefinition update(TriggerDefinition triggerDefinition) throws Kapu ArgumentValidator.validateEntityName(triggerDefinition.getName(), "triggerDefinition.name"); // Check access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.write, null)); + authorizationService.checkPermission(new Permission(Domains.JOB, Actions.write, null)); return txManager.execute(tx -> triggerDefinitionRepository.update(tx, triggerDefinition)); } @@ -99,7 +97,7 @@ public TriggerDefinition find(KapuaId stepDefinitionId) throws KapuaException { // Argument Validation ArgumentValidator.notNull(stepDefinitionId, KapuaEntityAttributes.ENTITY_ID); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.read, KapuaId.ANY)); + authorizationService.checkPermission(new Permission(Domains.JOB, Actions.read, KapuaId.ANY)); // Do find return txManager.execute(tx -> triggerDefinitionRepository.find(tx, KapuaId.ANY, stepDefinitionId)) .orElse(null); @@ -110,7 +108,7 @@ public TriggerDefinition find(KapuaId scopeId, KapuaId stepDefinitionId) throws // Argument Validation ArgumentValidator.notNull(stepDefinitionId, KapuaEntityAttributes.ENTITY_ID); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.read, KapuaId.ANY)); + authorizationService.checkPermission(new Permission(Domains.JOB, Actions.read, KapuaId.ANY)); // Do find return txManager.execute(tx -> triggerDefinitionRepository.find(tx, scopeId, stepDefinitionId)) .orElse(null); @@ -125,7 +123,7 @@ public TriggerDefinition findByName(String name) throws KapuaException { final Optional triggerDefinition = triggerDefinitionRepository.findByName(tx, name); if (triggerDefinition.isPresent()) { // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.read, KapuaId.ANY)); + authorizationService.checkPermission(new Permission(Domains.JOB, Actions.read, KapuaId.ANY)); } return triggerDefinition; }) @@ -137,7 +135,7 @@ public TriggerDefinitionListResult query(KapuaQuery query) throws KapuaException // Argument Validation ArgumentValidator.notNull(query, "query"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.read, KapuaId.ANY)); + authorizationService.checkPermission(new Permission(Domains.JOB, Actions.read, KapuaId.ANY)); // Do query return txManager.execute(tx -> triggerDefinitionRepository.query(tx, query)); } @@ -147,7 +145,7 @@ public long count(KapuaQuery query) throws KapuaException { // Argument Validation ArgumentValidator.notNull(query, "query"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.read, KapuaId.ANY)); + authorizationService.checkPermission(new Permission(Domains.JOB, Actions.read, KapuaId.ANY)); // Do query return txManager.execute(tx -> triggerDefinitionRepository.count(tx, query)); } @@ -158,7 +156,7 @@ public void delete(KapuaId scopeId, KapuaId stepDefinitionId) throws KapuaExcept ArgumentValidator.notNull(scopeId, "scopeId"); ArgumentValidator.notNull(stepDefinitionId, KapuaEntityAttributes.ENTITY_ID); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.delete, null)); + authorizationService.checkPermission(new Permission(Domains.JOB, Actions.delete, null)); // Do delete txManager.execute(tx -> { final Optional toBeDeleted = triggerDefinitionRepository.find(tx, scopeId, stepDefinitionId); diff --git a/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/fired/quartz/FiredTriggerCreatorImpl.java b/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/fired/quartz/FiredTriggerCreatorImpl.java deleted file mode 100644 index 7a2970bd570..00000000000 --- a/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/fired/quartz/FiredTriggerCreatorImpl.java +++ /dev/null @@ -1,84 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.scheduler.trigger.fired.quartz; - -import org.eclipse.kapua.commons.model.AbstractKapuaEntityCreator; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.scheduler.trigger.fired.FiredTrigger; -import org.eclipse.kapua.service.scheduler.trigger.fired.FiredTriggerCreator; -import org.eclipse.kapua.service.scheduler.trigger.fired.FiredTriggerStatus; - -import java.util.Date; - -/** - * {@link FiredTriggerCreator} implementation. - * - * @since 1.5.0 - */ -public class FiredTriggerCreatorImpl extends AbstractKapuaEntityCreator implements FiredTriggerCreator { - - private KapuaId triggerId; - private Date firedOn; - private FiredTriggerStatus status; - private String message; - - /** - * Constructor. - * - * @param scopeId The scope {@link KapuaId}. - * @since 1.5.0 - */ - public FiredTriggerCreatorImpl(KapuaId scopeId) { - super(scopeId); - } - - @Override - public KapuaId getTriggerId() { - return triggerId; - } - - @Override - public void setTriggerId(KapuaId triggerId) { - this.triggerId = triggerId; - } - - @Override - public Date getFiredOn() { - return firedOn; - } - - @Override - public void setFiredOn(Date firedOn) { - this.firedOn = firedOn; - } - - @Override - public FiredTriggerStatus getStatus() { - return status; - } - - @Override - public void setStatus(FiredTriggerStatus status) { - this.status = status; - } - - @Override - public String getMessage() { - return message; - } - - @Override - public void setMessage(String message) { - this.message = message; - } -} diff --git a/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/fired/quartz/FiredTriggerFactoryImpl.java b/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/fired/quartz/FiredTriggerFactoryImpl.java index 991f69b1603..d373879920b 100644 --- a/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/fired/quartz/FiredTriggerFactoryImpl.java +++ b/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/fired/quartz/FiredTriggerFactoryImpl.java @@ -12,15 +12,12 @@ *******************************************************************************/ package org.eclipse.kapua.service.scheduler.trigger.fired.quartz; +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaEntityCloneException; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.scheduler.trigger.fired.FiredTrigger; -import org.eclipse.kapua.service.scheduler.trigger.fired.FiredTriggerCreator; import org.eclipse.kapua.service.scheduler.trigger.fired.FiredTriggerFactory; -import org.eclipse.kapua.service.scheduler.trigger.fired.FiredTriggerListResult; -import org.eclipse.kapua.service.scheduler.trigger.fired.FiredTriggerQuery; - -import javax.inject.Singleton; /** * {@link FiredTriggerFactory} implementation. @@ -35,21 +32,6 @@ public FiredTrigger newEntity(KapuaId scopeId) { return new FiredTriggerImpl(scopeId); } - @Override - public FiredTriggerCreator newCreator(KapuaId scopeId) { - return new FiredTriggerCreatorImpl(scopeId); - } - - @Override - public FiredTriggerQuery newQuery(KapuaId scopeId) { - return new FiredTriggerQueryImpl(scopeId); - } - - @Override - public FiredTriggerListResult newListResult() { - return new FiredTriggerListResultImpl(); - } - @Override public FiredTrigger clone(FiredTrigger firedTrigger) { try { diff --git a/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/fired/quartz/FiredTriggerImplJpaRepository.java b/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/fired/quartz/FiredTriggerImplJpaRepository.java index 99f95315d1a..39af73e1fff 100644 --- a/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/fired/quartz/FiredTriggerImplJpaRepository.java +++ b/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/fired/quartz/FiredTriggerImplJpaRepository.java @@ -21,8 +21,9 @@ public class FiredTriggerImplJpaRepository extends KapuaEntityJpaRepository implements FiredTriggerRepository { + public FiredTriggerImplJpaRepository(KapuaJpaRepositoryConfiguration configuration) { - super(FiredTriggerImpl.class, FiredTrigger.TYPE, () -> new FiredTriggerListResultImpl(), configuration); + super(FiredTriggerImpl.class, FiredTrigger.TYPE, () -> new FiredTriggerListResult(), configuration); } } diff --git a/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/fired/quartz/FiredTriggerListResultImpl.java b/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/fired/quartz/FiredTriggerListResultImpl.java deleted file mode 100644 index 7f0a93c0f41..00000000000 --- a/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/fired/quartz/FiredTriggerListResultImpl.java +++ /dev/null @@ -1,25 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.scheduler.trigger.fired.quartz; - -import org.eclipse.kapua.commons.model.query.KapuaListResultImpl; -import org.eclipse.kapua.service.scheduler.trigger.fired.FiredTrigger; -import org.eclipse.kapua.service.scheduler.trigger.fired.FiredTriggerListResult; - -/** - * {@link FiredTriggerListResult} implementation. - * - * @since 1.5.0 - */ -public class FiredTriggerListResultImpl extends KapuaListResultImpl implements FiredTriggerListResult { -} diff --git a/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/fired/quartz/FiredTriggerQueryImpl.java b/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/fired/quartz/FiredTriggerQueryImpl.java deleted file mode 100644 index 001948044d0..00000000000 --- a/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/fired/quartz/FiredTriggerQueryImpl.java +++ /dev/null @@ -1,35 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.scheduler.trigger.fired.quartz; - -import org.eclipse.kapua.commons.model.query.AbstractKapuaQuery; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.scheduler.trigger.fired.FiredTriggerQuery; - -/** - * {@link FiredTriggerQuery} implementation. - * - * @since 1.5.0 - */ -public class FiredTriggerQueryImpl extends AbstractKapuaQuery implements FiredTriggerQuery { - - /** - * Constructor. - * - * @param scopeId The scope {@link KapuaId}. - * @since 1.5.0 - */ - public FiredTriggerQueryImpl(KapuaId scopeId) { - super(scopeId); - } -} diff --git a/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/fired/quartz/FiredTriggerServiceImpl.java b/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/fired/quartz/FiredTriggerServiceImpl.java index 9de940d7afb..d38fef27efb 100755 --- a/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/fired/quartz/FiredTriggerServiceImpl.java +++ b/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/fired/quartz/FiredTriggerServiceImpl.java @@ -12,6 +12,8 @@ *******************************************************************************/ package org.eclipse.kapua.service.scheduler.trigger.fired.quartz; +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaEntityNotFoundException; import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.commons.model.domains.Domains; @@ -21,7 +23,7 @@ import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; +import org.eclipse.kapua.service.authorization.permission.Permission; import org.eclipse.kapua.service.scheduler.trigger.Trigger; import org.eclipse.kapua.service.scheduler.trigger.TriggerRepository; import org.eclipse.kapua.service.scheduler.trigger.fired.FiredTrigger; @@ -32,8 +34,6 @@ import org.eclipse.kapua.service.scheduler.trigger.fired.FiredTriggerService; import org.eclipse.kapua.storage.TxManager; -import javax.inject.Singleton; - /** * {@link FiredTriggerService} implementation. * @@ -43,7 +43,6 @@ public class FiredTriggerServiceImpl implements FiredTriggerService { private final AuthorizationService authorizationService; - private final PermissionFactory permissionFactory; private final TxManager txManager; private final FiredTriggerRepository firedTriggerRepository; private final FiredTriggerFactory firedTriggerFactory; @@ -51,13 +50,11 @@ public class FiredTriggerServiceImpl implements FiredTriggerService { public FiredTriggerServiceImpl( AuthorizationService authorizationService, - PermissionFactory permissionFactory, TxManager txManager, FiredTriggerRepository firedTriggerRepository, FiredTriggerFactory firedTriggerFactory, TriggerRepository triggerRepository) { this.authorizationService = authorizationService; - this.permissionFactory = permissionFactory; this.txManager = txManager; this.firedTriggerRepository = firedTriggerRepository; this.firedTriggerFactory = firedTriggerFactory; @@ -74,7 +71,7 @@ public FiredTrigger create(FiredTriggerCreator firedTriggerCreator) throws Kapua ArgumentValidator.notNull(firedTriggerCreator.getStatus(), "firedTriggerCreator.status"); // Check access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.write, null)); + authorizationService.checkPermission(new Permission(Domains.JOB, Actions.write, null)); return txManager.execute(tx -> { // Check existence of Trigger @@ -97,7 +94,7 @@ public FiredTrigger find(KapuaId scopeId, KapuaId firedTriggerId) throws KapuaEx // Argument Validation ArgumentValidator.notNull(firedTriggerId, KapuaEntityAttributes.ENTITY_ID); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.read, scopeId)); + authorizationService.checkPermission(new Permission(Domains.JOB, Actions.read, scopeId)); // Do find return txManager.execute(tx -> firedTriggerRepository.find(tx, scopeId, firedTriggerId)) .orElse(null); @@ -108,7 +105,7 @@ public FiredTriggerListResult query(KapuaQuery query) throws KapuaException { // Argument Validation ArgumentValidator.notNull(query, "query"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.read, query.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.JOB, Actions.read, query.getScopeId())); // Do query return txManager.execute(tx -> firedTriggerRepository.query(tx, query)); } @@ -118,7 +115,7 @@ public long count(KapuaQuery query) throws KapuaException { // Argument Validation ArgumentValidator.notNull(query, "query"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.read, query.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.JOB, Actions.read, query.getScopeId())); // Do query return txManager.execute(tx -> firedTriggerRepository.count(tx, query)); } @@ -129,7 +126,7 @@ public void delete(KapuaId scopeId, KapuaId firedTriggerId) throws KapuaExceptio ArgumentValidator.notNull(scopeId, "scopeId"); ArgumentValidator.notNull(firedTriggerId, KapuaEntityAttributes.ENTITY_ID); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.JOB, Actions.delete, null)); + authorizationService.checkPermission(new Permission(Domains.JOB, Actions.delete, null)); // Do delete txManager.execute(tx -> firedTriggerRepository.delete(tx, scopeId, firedTriggerId)); diff --git a/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/fired/quartz/SchedulerTriggerFiredModule.java b/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/fired/quartz/SchedulerTriggerFiredModule.java index 2a775022f14..4bff09a7622 100644 --- a/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/fired/quartz/SchedulerTriggerFiredModule.java +++ b/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/fired/quartz/SchedulerTriggerFiredModule.java @@ -12,22 +12,22 @@ *******************************************************************************/ package org.eclipse.kapua.service.scheduler.trigger.fired.quartz; -import com.google.inject.Provides; +import javax.inject.Named; +import javax.inject.Singleton; + import org.eclipse.kapua.commons.core.AbstractKapuaModule; import org.eclipse.kapua.commons.jpa.KapuaJpaRepositoryConfiguration; -import org.eclipse.kapua.commons.jpa.KapuaJpaTxManagerFactory; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; import org.eclipse.kapua.service.scheduler.trigger.TriggerRepository; import org.eclipse.kapua.service.scheduler.trigger.fired.FiredTriggerFactory; import org.eclipse.kapua.service.scheduler.trigger.fired.FiredTriggerRepository; import org.eclipse.kapua.service.scheduler.trigger.fired.FiredTriggerService; import org.eclipse.kapua.storage.TxManager; -import javax.inject.Named; -import javax.inject.Singleton; +import com.google.inject.Provides; public class SchedulerTriggerFiredModule extends AbstractKapuaModule { + @Override protected void configureModule() { bind(FiredTriggerFactory.class).to(FiredTriggerFactoryImpl.class); @@ -37,15 +37,12 @@ protected void configureModule() { @Singleton FiredTriggerService firedTriggerService( AuthorizationService authorizationService, - PermissionFactory permissionFactory, @Named("schedulerTxManager") TxManager txManager, FiredTriggerRepository firedTriggerRepository, FiredTriggerFactory firedTriggerFactory, - TriggerRepository triggerRepository, - KapuaJpaTxManagerFactory jpaTxManagerFactory) { + TriggerRepository triggerRepository) { return new FiredTriggerServiceImpl( authorizationService, - permissionFactory, txManager, firedTriggerRepository, firedTriggerFactory, diff --git a/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/quartz/SchedulerQuartzModule.java b/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/quartz/SchedulerQuartzModule.java index dc2ae84111f..ba22d5619cd 100644 --- a/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/quartz/SchedulerQuartzModule.java +++ b/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/quartz/SchedulerQuartzModule.java @@ -12,8 +12,9 @@ *******************************************************************************/ package org.eclipse.kapua.service.scheduler.trigger.quartz; -import com.google.inject.Provides; -import com.google.inject.multibindings.ProvidesIntoSet; +import javax.inject.Named; +import javax.inject.Singleton; + import org.eclipse.kapua.commons.core.AbstractKapuaModule; import org.eclipse.kapua.commons.jpa.KapuaJpaRepositoryConfiguration; import org.eclipse.kapua.commons.jpa.KapuaJpaTxManagerFactory; @@ -22,7 +23,6 @@ import org.eclipse.kapua.model.domain.Domain; import org.eclipse.kapua.model.domain.DomainEntry; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; import org.eclipse.kapua.service.scheduler.trigger.TriggerFactory; import org.eclipse.kapua.service.scheduler.trigger.TriggerRepository; import org.eclipse.kapua.service.scheduler.trigger.TriggerService; @@ -30,10 +30,11 @@ import org.eclipse.kapua.service.scheduler.trigger.definition.TriggerDefinitionRepository; import org.eclipse.kapua.storage.TxManager; -import javax.inject.Named; -import javax.inject.Singleton; +import com.google.inject.Provides; +import com.google.inject.multibindings.ProvidesIntoSet; public class SchedulerQuartzModule extends AbstractKapuaModule { + @Override protected void configureModule() { bind(TriggerFactory.class).to(TriggerFactoryImpl.class); @@ -57,16 +58,13 @@ TxManager jobTxManager( @Singleton TriggerService triggerService( AuthorizationService authorizationService, - PermissionFactory permissionFactory, @Named("schedulerTxManager") TxManager txManager, TriggerRepository triggerRepository, TriggerFactory triggerFactory, TriggerDefinitionRepository triggerDefinitionRepository, - TriggerDefinitionFactory triggerDefinitionFactory, - KapuaJpaTxManagerFactory jpaTxManagerFactory) { + TriggerDefinitionFactory triggerDefinitionFactory) { return new TriggerServiceImpl( authorizationService, - permissionFactory, txManager, triggerRepository, triggerFactory, diff --git a/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/quartz/TriggerCreatorImpl.java b/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/quartz/TriggerCreatorImpl.java deleted file mode 100644 index 3b04c026011..00000000000 --- a/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/quartz/TriggerCreatorImpl.java +++ /dev/null @@ -1,121 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2017, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.scheduler.trigger.quartz; - -import org.eclipse.kapua.commons.model.AbstractKapuaNamedEntityCreator; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.scheduler.trigger.Trigger; -import org.eclipse.kapua.service.scheduler.trigger.TriggerCreator; -import org.eclipse.kapua.service.scheduler.trigger.definition.TriggerProperty; - -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -/** - * {@link TriggerCreator} implementation. - * - * @since 1.0.0 - */ -public class TriggerCreatorImpl extends AbstractKapuaNamedEntityCreator implements TriggerCreator { - - private static final long serialVersionUID = -2460883485294616032L; - - private Date startsOn; - private Date endsOn; - private String cronScheduling; - private Long retryInterval; - private KapuaId triggerDefinitionId; - private List triggerProperties; - - /** - * Constructor. - * - * @param scopeId The scope {@link KapuaId}. - * @param name The name. - * @since 1.0.0 - */ - public TriggerCreatorImpl(KapuaId scopeId, String name) { - super(scopeId, name); - } - - @Override - public Date getStartsOn() { - return startsOn; - } - - @Override - public void setStartsOn(Date startsOn) { - this.startsOn = startsOn; - } - - @Override - public Date getEndsOn() { - return endsOn; - } - - @Override - public void setEndsOn(Date endsOn) { - this.endsOn = endsOn; - } - - @Override - public String getCronScheduling() { - return cronScheduling; - } - - @Override - public void setCronScheduling(String cronScheduling) { - this.cronScheduling = cronScheduling; - } - - @Override - public Long getRetryInterval() { - return retryInterval; - } - - @Override - public void setRetryInterval(Long retryInterval) { - this.retryInterval = retryInterval; - } - - @Override - public KapuaId getTriggerDefinitionId() { - return triggerDefinitionId; - } - - @Override - public void setTriggerDefinitionId(KapuaId triggerDefinitionId) { - this.triggerDefinitionId = triggerDefinitionId; - } - - @Override - public List getTriggerProperties() { - if (triggerProperties == null) { - triggerProperties = new ArrayList<>(); - } - - return triggerProperties; - } - - @Override - public TriggerProperty getTriggerProperty(String name) { - return getTriggerProperties().stream().filter(tp -> tp.getName().equals(name)).findAny().orElse(null); - } - - @Override - public void setTriggerProperties(List triggerProperties) { - this.triggerProperties = triggerProperties; - } - -} diff --git a/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/quartz/TriggerFactoryImpl.java b/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/quartz/TriggerFactoryImpl.java index 2b924c6e397..b095607a903 100644 --- a/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/quartz/TriggerFactoryImpl.java +++ b/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/quartz/TriggerFactoryImpl.java @@ -12,18 +12,15 @@ *******************************************************************************/ package org.eclipse.kapua.service.scheduler.trigger.quartz; +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaEntityCloneException; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.scheduler.trigger.Trigger; -import org.eclipse.kapua.service.scheduler.trigger.TriggerCreator; import org.eclipse.kapua.service.scheduler.trigger.TriggerFactory; -import org.eclipse.kapua.service.scheduler.trigger.TriggerListResult; -import org.eclipse.kapua.service.scheduler.trigger.TriggerQuery; import org.eclipse.kapua.service.scheduler.trigger.definition.TriggerProperty; import org.eclipse.kapua.service.scheduler.trigger.definition.quartz.TriggerPropertyImpl; -import javax.inject.Singleton; - /** * {@link TriggerFactory} implementation. * @@ -32,26 +29,11 @@ @Singleton public class TriggerFactoryImpl implements TriggerFactory { - @Override - public TriggerCreator newCreator(KapuaId scopeId) { - return new TriggerCreatorImpl(scopeId, null); - } - @Override public Trigger newEntity(KapuaId scopeId) { return new TriggerImpl(scopeId); } - @Override - public TriggerQuery newQuery(KapuaId scopeId) { - return new TriggerQueryImpl(scopeId); - } - - @Override - public TriggerListResult newListResult() { - return new TriggerListResultImpl(); - } - @Override public TriggerProperty newTriggerProperty(String name, String type, String value) { return new TriggerPropertyImpl(name, type, value); diff --git a/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/quartz/TriggerImplJpaRepository.java b/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/quartz/TriggerImplJpaRepository.java index 5e4e056cc2f..d95e4f48a88 100644 --- a/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/quartz/TriggerImplJpaRepository.java +++ b/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/quartz/TriggerImplJpaRepository.java @@ -12,6 +12,12 @@ *******************************************************************************/ package org.eclipse.kapua.service.scheduler.trigger.quartz; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaDelete; +import javax.persistence.criteria.JoinType; +import javax.persistence.criteria.ListJoin; +import javax.persistence.criteria.Root; + import org.eclipse.kapua.commons.jpa.JpaAwareTxContext; import org.eclipse.kapua.commons.jpa.KapuaJpaRepositoryConfiguration; import org.eclipse.kapua.commons.jpa.KapuaNamedEntityJpaRepository; @@ -24,18 +30,12 @@ import org.eclipse.kapua.service.scheduler.trigger.definition.quartz.TriggerPropertyImpl_; import org.eclipse.kapua.storage.TxContext; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaDelete; -import javax.persistence.criteria.JoinType; -import javax.persistence.criteria.ListJoin; -import javax.persistence.criteria.Root; - public class TriggerImplJpaRepository extends KapuaNamedEntityJpaRepository implements TriggerRepository { public TriggerImplJpaRepository(KapuaJpaRepositoryConfiguration jpaRepoConfig) { - super(TriggerImpl.class, Trigger.TYPE, () -> new TriggerListResultImpl(), jpaRepoConfig); + super(TriggerImpl.class, Trigger.TYPE, () -> new TriggerListResult(), jpaRepoConfig); } @Override diff --git a/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/quartz/TriggerListResultImpl.java b/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/quartz/TriggerListResultImpl.java deleted file mode 100644 index 5004338a596..00000000000 --- a/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/quartz/TriggerListResultImpl.java +++ /dev/null @@ -1,27 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2017, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.scheduler.trigger.quartz; - -import org.eclipse.kapua.commons.model.query.KapuaListResultImpl; -import org.eclipse.kapua.service.scheduler.trigger.Trigger; -import org.eclipse.kapua.service.scheduler.trigger.TriggerListResult; - -/** - * {@link TriggerListResult} implementation. - * - * @since 1.0.0 - */ -public class TriggerListResultImpl extends KapuaListResultImpl implements TriggerListResult { - - private static final long serialVersionUID = -5118004898345748297L; -} diff --git a/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/quartz/TriggerQueryImpl.java b/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/quartz/TriggerQueryImpl.java deleted file mode 100644 index 0cc4f03f154..00000000000 --- a/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/quartz/TriggerQueryImpl.java +++ /dev/null @@ -1,45 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2017, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.scheduler.trigger.quartz; - -import org.eclipse.kapua.commons.model.query.AbstractKapuaNamedQuery; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.scheduler.trigger.TriggerQuery; - -/** - * {@link TriggerQuery} implementation. - * - * @since 1.0.0 - */ -public class TriggerQueryImpl extends AbstractKapuaNamedQuery implements TriggerQuery { - - /** - * Constructor. - * - * @since 1.0.0 - */ - private TriggerQueryImpl() { - super(); - } - - /** - * Constructor. - * - * @param scopeId The {@link #getScopeId()}. - * @since 1.0.0 - */ - public TriggerQueryImpl(KapuaId scopeId) { - this(); - setScopeId(scopeId); - } -} diff --git a/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/quartz/TriggerServiceImpl.java b/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/quartz/TriggerServiceImpl.java index 5dbd613e106..4346598b7b5 100755 --- a/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/quartz/TriggerServiceImpl.java +++ b/service/scheduler/quartz/src/main/java/org/eclipse/kapua/service/scheduler/trigger/quartz/TriggerServiceImpl.java @@ -19,6 +19,7 @@ import java.util.Optional; import java.util.function.Function; import java.util.stream.Collectors; + import javax.inject.Singleton; import javax.validation.constraints.NotNull; @@ -31,7 +32,7 @@ import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; +import org.eclipse.kapua.service.authorization.permission.Permission; import org.eclipse.kapua.service.scheduler.exception.TriggerInvalidDatesException; import org.eclipse.kapua.service.scheduler.exception.TriggerInvalidSchedulingException; import org.eclipse.kapua.service.scheduler.quartz.driver.QuartzTriggerDriver; @@ -76,7 +77,6 @@ public class TriggerServiceImpl implements TriggerService { private TriggerDefinition cronJobTriggerDefinition; private final AuthorizationService authorizationService; - private final PermissionFactory permissionFactory; private final TxManager txManager; private final TriggerRepository triggerRepository; private final TriggerFactory triggerFactory; @@ -85,14 +85,12 @@ public class TriggerServiceImpl implements TriggerService { public TriggerServiceImpl( AuthorizationService authorizationService, - PermissionFactory permissionFactory, TxManager txManager, TriggerRepository triggerRepository, TriggerFactory triggerFactory, TriggerDefinitionRepository triggerDefinitionRepository, TriggerDefinitionFactory triggerDefinitionFactory) { this.authorizationService = authorizationService; - this.permissionFactory = permissionFactory; this.txManager = txManager; this.triggerRepository = triggerRepository; this.triggerFactory = triggerFactory; @@ -109,7 +107,7 @@ public Trigger create(TriggerCreator triggerCreator) throws KapuaException { ArgumentValidator.notNull(triggerCreator.getStartsOn(), "triggerCreator.startsOn"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.SCHEDULER, Actions.write, triggerCreator.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.SCHEDULER, Actions.write, triggerCreator.getScopeId())); // Convert creator to new model. // To be removed after removing of TriggerCreator.cronScheduling and TriggerCreator.retryInterval @@ -122,7 +120,8 @@ public Trigger create(TriggerCreator triggerCreator) throws KapuaException { TriggerDefinition triggerDefinition = triggerDefinitionRepository.find(tx, KapuaId.ANY, triggerCreator.getTriggerDefinitionId()) .orElseThrow(() -> new KapuaEntityNotFoundException(TriggerDefinition.TYPE, triggerCreator.getTriggerDefinitionId())); - final Map triggerDefinitionPropertiesByName = triggerDefinition.getTriggerProperties().stream().collect(Collectors.toMap(jsdp -> jsdp.getName(), Function.identity())); + final Map triggerDefinitionPropertiesByName = triggerDefinition.getTriggerProperties().stream() + .collect(Collectors.toMap(jsdp -> jsdp.getName(), Function.identity())); for (TriggerProperty jsp : triggerCreator.getTriggerProperties()) { final TriggerProperty jsdp = triggerDefinitionPropertiesByName.get(jsp.getName()); if (jsdp == null) { @@ -196,7 +195,7 @@ public Trigger update(Trigger trigger) throws KapuaException { ArgumentValidator.validateEntityName(trigger.getName(), "trigger.name"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.SCHEDULER, Actions.write, trigger.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.SCHEDULER, Actions.write, trigger.getScopeId())); return txManager.execute(tx -> { // Check existence @@ -276,7 +275,7 @@ public void delete(KapuaId scopeId, KapuaId triggerId) throws KapuaException { ArgumentValidator.notNull(triggerId, "scopeId"); ArgumentValidator.notNull(scopeId, "triggerId"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.SCHEDULER, Actions.delete, scopeId)); + authorizationService.checkPermission(new Permission(Domains.SCHEDULER, Actions.delete, scopeId)); // Do delete QuartzTriggerDriver.deleteTrigger(txManager.execute(tx -> { @@ -291,7 +290,7 @@ public Trigger find(KapuaId scopeId, KapuaId triggerId) throws KapuaException { ArgumentValidator.notNull(triggerId, "triggerId"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.SCHEDULER, Actions.read, scopeId)); + authorizationService.checkPermission(new Permission(Domains.SCHEDULER, Actions.read, scopeId)); // Do find return txManager.execute(tx -> { @@ -308,11 +307,11 @@ public TriggerListResult query(KapuaQuery query) throws KapuaException { // Argument validation ArgumentValidator.notNull(query, "query"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.SCHEDULER, Actions.read, query.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.SCHEDULER, Actions.read, query.getScopeId())); return txManager.execute(tx -> { // Do query TriggerListResult triggers = triggerRepository.query(tx, query); - final TriggerListResult res = triggerFactory.newListResult(); + final TriggerListResult res = new TriggerListResult(); for (Trigger trigger : triggers.getItems()) { res.addItem(adaptTrigger(tx, trigger)); } @@ -327,7 +326,7 @@ public void deleteAllByJobId(KapuaId scopeId, KapuaId jobId) throws KapuaExcepti ArgumentValidator.notNull(scopeId, "scopeId"); ArgumentValidator.notNull(jobId, "jobId"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.SCHEDULER, Actions.delete, scopeId)); + authorizationService.checkPermission(new Permission(Domains.SCHEDULER, Actions.delete, scopeId)); txManager.execute(tx -> { triggerRepository.deleteAllByJobId(tx, scopeId, jobId); return null; @@ -339,7 +338,7 @@ public long count(KapuaQuery query) throws KapuaException { // Argument validation ArgumentValidator.notNull(query, "query"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.SCHEDULER, Actions.read, query.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.SCHEDULER, Actions.read, query.getScopeId())); // Do count return txManager.execute(tx -> triggerRepository.count(tx, query)); } @@ -349,7 +348,8 @@ public long count(KapuaQuery query) throws KapuaException { * Gets the {@link TriggerDefinition} named 'Interval Job' * * @return he {@link TriggerDefinition} named 'Interval Job' - * @throws KapuaException In case is not found. + * @throws KapuaException + * In case is not found. * @since 1.1.0 */ private synchronized TriggerDefinition getIntervalJobTriggerDefinition() throws KapuaException { @@ -364,7 +364,8 @@ private synchronized TriggerDefinition getIntervalJobTriggerDefinition() throws * Gets the {@link TriggerDefinition} named 'Cron Job' * * @return he {@link TriggerDefinition} named 'Cron Job' - * @throws KapuaException In case is not found. + * @throws KapuaException + * In case is not found. * @since 1.1.0 */ private synchronized TriggerDefinition getCronJobTriggerDefinition() throws KapuaException { @@ -378,9 +379,11 @@ private synchronized TriggerDefinition getCronJobTriggerDefinition() throws Kapu /** * Gets the {@link TriggerDefinition} by the given name. * - * @param triggerDefinitionName The {@link TriggerDefinition#getName()} to look for. + * @param triggerDefinitionName + * The {@link TriggerDefinition#getName()} to look for. * @return The {@link TriggerDefinition} by the given name. - * @throws KapuaException In case nothing is found. + * @throws KapuaException + * In case nothing is found. * @since 1.1.0 */ private synchronized TriggerDefinition getTriggerDefinition(String triggerDefinitionName) throws KapuaException { @@ -390,11 +393,12 @@ private synchronized TriggerDefinition getTriggerDefinition(String triggerDefini } /** - * Adapts {@link TriggerCreator#getRetryInterval()} and {@link TriggerCreator#getCronScheduling()} to the new model - * which make use of {@link TriggerDefinition}s + * Adapts {@link TriggerCreator#getRetryInterval()} and {@link TriggerCreator#getCronScheduling()} to the new model which make use of {@link TriggerDefinition}s * - * @param triggerCreator The {@link TriggerCreator} to adapt. - * @throws KapuaException In case that {@link TriggerDefinition} is not found. + * @param triggerCreator + * The {@link TriggerCreator} to adapt. + * @throws KapuaException + * In case that {@link TriggerDefinition} is not found. * @since 1.1.0 */ private void adaptTriggerCreator(TriggerCreator triggerCreator) throws KapuaException { @@ -408,12 +412,13 @@ private void adaptTriggerCreator(TriggerCreator triggerCreator) throws KapuaExce } /** - * Adapts {@link Trigger#getRetryInterval()} and {@link Trigger#getCronScheduling()} to the new model - * which make use of {@link TriggerDefinition}s + * Adapts {@link Trigger#getRetryInterval()} and {@link Trigger#getCronScheduling()} to the new model which make use of {@link TriggerDefinition}s * - * @param trigger The {@link Trigger} to adapt. + * @param trigger + * The {@link Trigger} to adapt. * @return - * @throws KapuaException In case that {@link TriggerDefinition} is not found. + * @throws KapuaException + * In case that {@link TriggerDefinition} is not found. * @since 1.1.0 */ private @NotNull Trigger adaptTrigger(TxContext tx, @NotNull Trigger trigger) throws KapuaException { diff --git a/service/scheduler/test-steps/pom.xml b/service/scheduler/test-steps/pom.xml index 1042bfc5e8d..4097815ae7f 100644 --- a/service/scheduler/test-steps/pom.xml +++ b/service/scheduler/test-steps/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-scheduler - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-scheduler-test-steps diff --git a/service/scheduler/test-steps/src/main/java/org/eclipse/kapua/service/scheduler/steps/JobScheduleServiceSteps.java b/service/scheduler/test-steps/src/main/java/org/eclipse/kapua/service/scheduler/steps/JobScheduleServiceSteps.java index 97889210fc3..91984822dff 100644 --- a/service/scheduler/test-steps/src/main/java/org/eclipse/kapua/service/scheduler/steps/JobScheduleServiceSteps.java +++ b/service/scheduler/test-steps/src/main/java/org/eclipse/kapua/service/scheduler/steps/JobScheduleServiceSteps.java @@ -12,9 +12,19 @@ *******************************************************************************/ package org.eclipse.kapua.service.scheduler.steps; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.List; + +import javax.inject.Inject; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.locator.KapuaLocator; import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.model.query.predicate.AttributePredicate; import org.eclipse.kapua.qa.common.StepData; import org.eclipse.kapua.qa.common.TestBase; @@ -24,9 +34,14 @@ import org.eclipse.kapua.service.scheduler.trigger.TriggerCreator; import org.eclipse.kapua.service.scheduler.trigger.TriggerFactory; import org.eclipse.kapua.service.scheduler.trigger.TriggerListResult; -import org.eclipse.kapua.service.scheduler.trigger.TriggerQuery; import org.eclipse.kapua.service.scheduler.trigger.TriggerService; import org.eclipse.kapua.service.scheduler.trigger.definition.TriggerDefinition; +import org.eclipse.kapua.service.scheduler.trigger.definition.TriggerDefinitionAttributes; +import org.eclipse.kapua.service.scheduler.trigger.definition.TriggerDefinitionFactory; +import org.eclipse.kapua.service.scheduler.trigger.definition.TriggerDefinitionQuery; +import org.eclipse.kapua.service.scheduler.trigger.definition.TriggerDefinitionService; +import org.eclipse.kapua.service.scheduler.trigger.definition.TriggerProperty; +import org.junit.Assert; import com.google.inject.Singleton; @@ -36,21 +51,6 @@ import io.cucumber.java.en.And; import io.cucumber.java.en.Then; -import org.eclipse.kapua.service.scheduler.trigger.definition.TriggerDefinitionAttributes; -import org.eclipse.kapua.service.scheduler.trigger.definition.TriggerDefinitionFactory; -import org.eclipse.kapua.service.scheduler.trigger.definition.TriggerDefinitionQuery; -import org.eclipse.kapua.service.scheduler.trigger.definition.TriggerDefinitionService; -import org.eclipse.kapua.service.scheduler.trigger.definition.TriggerProperty; -import org.junit.Assert; - -import javax.inject.Inject; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Date; -import java.util.List; - @Singleton public class JobScheduleServiceSteps extends TestBase { @@ -67,13 +67,13 @@ public class JobScheduleServiceSteps extends TestBase { private static final String TRIGGER_START_DATE = "TriggerStartDate"; private static final String TRIGGER_END_DATE = "TriggerEndDate"; -// **************************************************************************************** -// * Implementation of Gherkin steps used in JobService.feature scenarios. * -// * * -// * MockedLocator is used for Location Service. Mockito is used to mock other * -// * services that the Account services dependent on. Dependent services are: * -// * - Authorization Service * -// **************************************************************************************** + // **************************************************************************************** + // * Implementation of Gherkin steps used in JobService.feature scenarios. * + // * * + // * MockedLocator is used for Location Service. Mockito is used to mock other * + // * services that the Account services dependent on. Dependent services are: * + // * - Authorization Service * + // **************************************************************************************** private static final String KAPUA_ID_CLASS_NAME = "org.eclipse.kapua.model.id.KapuaId"; @@ -83,7 +83,7 @@ public JobScheduleServiceSteps(StepData stepData) { super(stepData); } - @After(value="@setup") + @After(value = "@setup") public void setServices() { KapuaLocator locator = KapuaLocator.getInstance(); triggerFactory = locator.getFactory(TriggerFactory.class); @@ -113,7 +113,7 @@ public void beforeScenarioDockerFull(Scenario scenario) { @And("I try to create scheduler with name {string}") public void iTryToCreateSchedulerWithName(String schedulerName) throws Exception { - TriggerCreator triggerCreator = triggerFactory.newCreator(getCurrentScopeId()); + TriggerCreator triggerCreator = new TriggerCreator(getCurrentScopeId()); KapuaId triggerDefinitionId = (KapuaId) stepData.get(TRIGGER_DEFINITION_ID); triggerCreator.setName(schedulerName); triggerCreator.setDescription("A trigger description"); @@ -134,7 +134,7 @@ public void iTryToCreateSchedulerWithName(String schedulerName) throws Exception public void iFindTriggerPropertiesWithName(String triggerDefinitionName) throws Exception { primeException(); try { - TriggerDefinitionQuery triggerDefinitionQuery = triggerDefinitionFactory.newQuery(getCurrentScopeId()); + TriggerDefinitionQuery triggerDefinitionQuery = new TriggerDefinitionQuery(getCurrentScopeId()); triggerDefinitionQuery.setPredicate(triggerDefinitionQuery.attributePredicate(TriggerDefinitionAttributes.NAME, triggerDefinitionName, AttributePredicate.Operator.EQUAL)); TriggerDefinition triggerDefinition = triggerDefinitionService.query(triggerDefinitionQuery).getFirstItem(); stepData.put("TriggerDefinition", triggerDefinition); @@ -146,7 +146,7 @@ public void iFindTriggerPropertiesWithName(String triggerDefinitionName) throws @And("A regular trigger creator with the name {string} is created") public void aRegularTriggerCreatorWithTheName(String triggerName) { - TriggerCreator triggerCreator = triggerFactory.newCreator(getCurrentScopeId()); + TriggerCreator triggerCreator = new TriggerCreator(getCurrentScopeId()); KapuaId currentTriggerDefId = (KapuaId) stepData.get(TRIGGER_DEFINITION_ID); KapuaId jobId = (KapuaId) stepData.get("CurrentJobId"); triggerCreator.setName(triggerName); @@ -160,7 +160,7 @@ public void aRegularTriggerCreatorWithTheName(String triggerName) { @And("A trigger creator without a name") public void aTriggerCreatorWithoutAName() { - TriggerCreator triggerCreator = triggerFactory.newCreator(getCurrentScopeId()); + TriggerCreator triggerCreator = new TriggerCreator(getCurrentScopeId()); KapuaId currentTriggerDefId = (KapuaId) stepData.get(TRIGGER_DEFINITION_ID); triggerCreator.setTriggerDefinitionId(currentTriggerDefId); triggerCreator.setName(null); @@ -169,7 +169,7 @@ public void aTriggerCreatorWithoutAName() { @And("A regular trigger creator with the name {string} and following properties") public void aRegularTriggerCreatorWithTheNameAndFollowingProperties(String triggerName, List list) { - TriggerCreator triggerCreator = triggerFactory.newCreator(getCurrentScopeId()); + TriggerCreator triggerCreator = new TriggerCreator(getCurrentScopeId()); KapuaId currentTriggerDefId = (KapuaId) stepData.get(TRIGGER_DEFINITION_ID); triggerCreator.setName(triggerName); triggerCreator.setDescription("A trigger description"); @@ -412,7 +412,7 @@ public void iDeleteTriggerWithName(String arg0) throws Throwable { @And("I search for the trigger with name {string} in the database") public void iSearchForTheTriggerWithNameInTheDatabase(String triggerName) throws Throwable { - TriggerQuery triggerQuery = triggerFactory.newQuery(getCurrentScopeId()); + KapuaQuery triggerQuery = new KapuaQuery(getCurrentScopeId()); triggerQuery.setPredicate(triggerQuery.attributePredicate(TriggerAttributes.NAME, triggerName, AttributePredicate.Operator.EQUAL)); primeException(); try { @@ -435,7 +435,7 @@ public void iTryToEditSchedulerPropertyTo(String trigerDefinition) throws Except Trigger trigger = (Trigger) stepData.get(TRIGGER); primeException(); try { - TriggerDefinitionQuery triggerDefinitionQuery = triggerDefinitionFactory.newQuery(getCurrentScopeId()); + TriggerDefinitionQuery triggerDefinitionQuery = new TriggerDefinitionQuery(getCurrentScopeId()); triggerDefinitionQuery.setPredicate(triggerDefinitionQuery.attributePredicate(TriggerDefinitionAttributes.NAME, trigerDefinition, AttributePredicate.Operator.EQUAL)); TriggerDefinition triggerDefinition = triggerDefinitionService.query(triggerDefinitionQuery).getFirstItem(); trigger.setTriggerDefinitionId(triggerDefinition.getId()); diff --git a/service/scheduler/test/pom.xml b/service/scheduler/test/pom.xml index 79a7a9b7b3e..860d765f45d 100644 --- a/service/scheduler/test/pom.xml +++ b/service/scheduler/test/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-scheduler - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-scheduler-test diff --git a/service/scheduler/test/src/test/java/org/eclipse/kapua/service/scheduler/test/SchedulerLocatorConfiguration.java b/service/scheduler/test/src/test/java/org/eclipse/kapua/service/scheduler/test/SchedulerLocatorConfiguration.java index f569a08610c..aa3daf531b5 100644 --- a/service/scheduler/test/src/test/java/org/eclipse/kapua/service/scheduler/test/SchedulerLocatorConfiguration.java +++ b/service/scheduler/test/src/test/java/org/eclipse/kapua/service/scheduler/test/SchedulerLocatorConfiguration.java @@ -24,14 +24,12 @@ import org.eclipse.kapua.commons.metric.CommonsMetric; import org.eclipse.kapua.commons.metric.MetricsService; import org.eclipse.kapua.commons.metric.MetricsServiceImpl; -import org.eclipse.kapua.commons.model.query.QueryFactoryImpl; import org.eclipse.kapua.commons.service.internal.cache.CacheManagerProvider; import org.eclipse.kapua.commons.setting.system.SystemSetting; import org.eclipse.kapua.commons.util.xml.XmlUtil; import org.eclipse.kapua.job.engine.client.JobEngineServiceClient; import org.eclipse.kapua.job.engine.client.settings.JobEngineClientSetting; import org.eclipse.kapua.locator.KapuaLocator; -import org.eclipse.kapua.model.query.QueryFactory; import org.eclipse.kapua.qa.common.MockedLocator; import org.eclipse.kapua.qa.common.TestJAXBContextProvider; import org.eclipse.kapua.service.account.AccountFactory; @@ -43,7 +41,6 @@ import org.eclipse.kapua.service.authorization.AuthorizationService; import org.eclipse.kapua.service.authorization.domain.DomainRegistryService; import org.eclipse.kapua.service.authorization.permission.Permission; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; import org.eclipse.kapua.service.job.JobFactory; import org.eclipse.kapua.service.job.JobService; import org.eclipse.kapua.service.job.internal.JobFactoryImpl; @@ -106,10 +103,6 @@ protected void configure() { bind(AuthorizationService.class).toInstance(mockedAuthorization); bind(KapuaJpaRepositoryConfiguration.class).toInstance(new KapuaJpaRepositoryConfiguration()); - // Inject mocked Permission Factory - final PermissionFactory permissionFactory = Mockito.mock(PermissionFactory.class); - bind(PermissionFactory.class).toInstance(permissionFactory); - // binding Account related services bind(AccountRelativeFinder.class).toInstance(Mockito.mock(AccountRelativeFinder.class)); bind(AccountService.class).toInstance(Mockito.mock(AccountService.class)); @@ -129,7 +122,6 @@ protected void configure() { final TriggerFactoryImpl triggerFactory = new TriggerFactoryImpl(); final TriggerServiceImpl triggerService = new TriggerServiceImpl( mockedAuthorization, - permissionFactory, schedulerTxManager, triggerRepository, triggerFactory, @@ -139,7 +131,6 @@ protected void configure() { bind(JobService.class).toInstance(new JobServiceImpl( Mockito.mock(ServiceConfigurationManager.class), new JobEngineServiceClient(new JobEngineClientSetting(), new XmlUtil(new TestJAXBContextProvider())), - permissionFactory, mockedAuthorization, new KapuaJpaTxManagerFactory(maxInsertAttempts).create("kapua-job"), jobRepository, @@ -149,14 +140,10 @@ protected void configure() { bind(TriggerFactory.class).toInstance(triggerFactory); bind(TriggerDefinitionService.class).toInstance(new TriggerDefinitionServiceImpl( mockedAuthorization, - permissionFactory, schedulerTxManager, triggerDefinitionRepository, triggerDefinitionFactory)); bind(TriggerDefinitionFactory.class).toInstance(triggerDefinitionFactory); - - // bind Query related services - bind(QueryFactory.class).toInstance(new QueryFactoryImpl()); } }; diff --git a/service/security/authentication/api/pom.xml b/service/security/authentication/api/pom.xml index 99ab2e99607..784de19b3f4 100644 --- a/service/security/authentication/api/pom.xml +++ b/service/security/authentication/api/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-security-authentication - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-security-authentication-api diff --git a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/AccessTokenCredentials.java b/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/AccessTokenCredentials.java deleted file mode 100644 index 1dd067387c9..00000000000 --- a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/AccessTokenCredentials.java +++ /dev/null @@ -1,47 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authentication; - -import org.eclipse.kapua.service.authentication.token.AccessToken; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlType; - -/** - * {@link AccessToken} {@link AuthenticationCredentials} definition. - * - * @since 1.0.0 - */ -@XmlRootElement(name = "accessTokenCredentials") -@XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = AuthenticationXmlRegistry.class, factoryMethod = "newAccessTokenCredentials") -public interface AccessTokenCredentials extends SessionCredentials { - - /** - * Gets the session JWT to authenticate. - * - * @return The session JWT to authenticate. - * @since 1.0.0 - */ - String getTokenId(); - - /** - * Sets the session JWT to authenticate. - * - * @param tokenId The session JWT to authenticate. - * @since 1.0.0 - */ - void setTokenId(String tokenId); -} diff --git a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/ApiKeyCredentials.java b/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/ApiKeyCredentials.java index f521a7f81a2..12184fa00c0 100644 --- a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/ApiKeyCredentials.java +++ b/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/ApiKeyCredentials.java @@ -25,23 +25,47 @@ */ @XmlRootElement(name = "apiKeyCredentials") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = AuthenticationXmlRegistry.class, factoryMethod = "newApiKeyCredentials") -public interface ApiKeyCredentials extends LoginCredentials { +@XmlType +public class ApiKeyCredentials implements LoginCredentials { + + private static final long serialVersionUID = -5920944517814926028L; + + private String apiKey; + + public ApiKeyCredentials() { + } /** - * Gets the Api Key to authenticate. + * Constructor. + * + * @param apiKey + * The Api Key. + * @since 1.0.0 + */ + public ApiKeyCredentials(String apiKey) { + setApiKey(apiKey); + } + + /** + * /** Gets the Api Key to authenticate. * * @return The Api Key to authenticate. * @since 1.0.0 */ @XmlElement(name = "apiKey") - String getApiKey(); + public String getApiKey() { + return apiKey; + } /** * Sets the Api Key to authenticate. * - * @param apiKey The Api Key to authenticate. + * @param apiKey + * The Api Key to authenticate. * @since 1.0.0 */ - void setApiKey(String apiKey); + public void setApiKey(String apiKey) { + this.apiKey = apiKey; + } + } diff --git a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/AuthenticationXmlRegistry.java b/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/AuthenticationXmlRegistry.java deleted file mode 100644 index fca84cc0544..00000000000 --- a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/AuthenticationXmlRegistry.java +++ /dev/null @@ -1,66 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - * Red Hat Inc - *******************************************************************************/ -package org.eclipse.kapua.service.authentication; - -import org.eclipse.kapua.locator.KapuaLocator; - -public class AuthenticationXmlRegistry { - - private final CredentialsFactory credentialsFactory = KapuaLocator.getInstance().getFactory(CredentialsFactory.class); - - /** - * Creates a new {@link UsernamePasswordCredentials} instance - * - * @return - */ - public UsernamePasswordCredentials newUsernamePasswordCredentials() { - return credentialsFactory.newUsernamePasswordCredentials(); - } - - /** - * Creates a new {@link ApiKeyCredentials} instance - * - * @return - */ - public ApiKeyCredentials newApiKeyCredentials() { - return credentialsFactory.newApiKeyCredentials(null); - } - - /** - * Creates a new {@link JwtCredentials} instance - * - * @return - */ - public JwtCredentials newJwtCredentials() { - return credentialsFactory.newJwtCredentials(null, null); - } - - /** - * Creates a new {@link AccessTokenCredentials} instance - * - * @return - */ - public AccessTokenCredentials newAccessTokenCredentials() { - return credentialsFactory.newAccessTokenCredentials(null); - } - - /** - * Creates a new {@link RefreshTokenCredentials} instance - * - * @return - */ - public RefreshTokenCredentials newRefreshTokenCredentials() { - return credentialsFactory.newRefreshTokenCredentials(null, null); - } -} diff --git a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/CredentialsFactory.java b/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/CredentialsFactory.java deleted file mode 100644 index 3066c769102..00000000000 --- a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/CredentialsFactory.java +++ /dev/null @@ -1,74 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - * Red Hat Inc - *******************************************************************************/ -package org.eclipse.kapua.service.authentication; - -import org.eclipse.kapua.model.KapuaObjectFactory; - -/** - * {@link CredentialsFactory} factory definition. - */ -public interface CredentialsFactory extends KapuaObjectFactory { - - /** - * Creates a new {@link UsernamePasswordCredentials} instance based on provided username and password - * - * @param username the name of the user - * @param password the password of the user - * @return the new credentials - */ - UsernamePasswordCredentials newUsernamePasswordCredentials(String username, String password); - - /** - * Creates a new {@link UsernamePasswordCredentials} instance based on username and password with no preset values - * - * @return the new, empty credentials instance - */ - default UsernamePasswordCredentials newUsernamePasswordCredentials() { - return newUsernamePasswordCredentials(null, null); - } - - /** - * Creates a new {@link ApiKeyCredentials} instance based on provided api key - * - * @param apiKey - * @return - */ - ApiKeyCredentials newApiKeyCredentials(String apiKey); - - /** - * Creates a new {@link JwtCredentials} instance based on provided Json Web Token - * - * @param jwt - * @param idToken the OpenID Connect idToken, used for the logout - * @return - */ - JwtCredentials newJwtCredentials(String jwt, String idToken); - - /** - * Creates a new {@link AccessTokenCredentials} instance based on provided tokenId - * - * @param tokenId - * @return - */ - AccessTokenCredentials newAccessTokenCredentials(String tokenId); - - /** - * Creates a new {@link RefreshTokenCredentials} instance based on provided tokenId and refresh token - * - * @param tokenId - * @return - */ - RefreshTokenCredentials newRefreshTokenCredentials(String tokenId, String refreshToken); - -} diff --git a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/JwtCredentials.java b/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/JwtCredentials.java index 74b69fe3288..bcec8296265 100644 --- a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/JwtCredentials.java +++ b/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/JwtCredentials.java @@ -25,8 +25,30 @@ */ @XmlRootElement(name = "jwtCredentials") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = AuthenticationXmlRegistry.class, factoryMethod = "newJwtCredentials") -public interface JwtCredentials extends LoginCredentials { +@XmlType +public class JwtCredentials implements LoginCredentials { + + private static final long serialVersionUID = -5920944517814926028L; + + private String accessToken; + private String idToken; + + public JwtCredentials() { + } + + /** + * Constructor. + * + * @param accessToken + * The credential access token + * @param idToken + * The credential id token. + * @since 1.4.0 + */ + public JwtCredentials(String accessToken, String idToken) { + setAccessToken(accessToken); + setIdToken(idToken); + } /** * Gets the OpenID Connect accessToken. @@ -35,15 +57,20 @@ public interface JwtCredentials extends LoginCredentials { * @since 1.3.0 */ @XmlElement(name = "accessToken") - String getAccessToken(); + public String getAccessToken() { + return accessToken; + } /** * Set the OpenID Connect accessToken. * - * @param accessToken The OpenID Connect accessToken. + * @param accessToken + * The OpenID Connect accessToken. * @since 1.3.0 */ - void setAccessToken(String accessToken); + public void setAccessToken(String accessToken) { + this.accessToken = accessToken; + } /** * Gets the OpenID Connect idToken. @@ -52,13 +79,19 @@ public interface JwtCredentials extends LoginCredentials { * @since 1.3.0 */ @XmlElement(name = "idToken") - String getIdToken(); + public String getIdToken() { + return idToken; + } /** * Set the OpenID Connect idToken. * - * @param idToken The OpenID Connect idToken. + * @param idToken + * The OpenID Connect idToken. * @since 1.3.0 */ - void setIdToken(String idToken); + public void setIdToken(String idToken) { + this.idToken = idToken; + } + } diff --git a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/RefreshTokenCredentials.java b/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/RefreshTokenCredentials.java index 0db0d1f127b..53dfd32076f 100644 --- a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/RefreshTokenCredentials.java +++ b/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/RefreshTokenCredentials.java @@ -12,14 +12,14 @@ *******************************************************************************/ package org.eclipse.kapua.service.authentication; -import org.eclipse.kapua.service.authentication.token.AccessToken; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; +import org.eclipse.kapua.service.authentication.token.AccessToken; + /** * {@link AccessToken#getRefreshToken()} {@link LoginCredentials} definition. * @@ -27,8 +27,28 @@ */ @XmlRootElement(name = "refreshTokenCredentials") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = AuthenticationXmlRegistry.class, factoryMethod = "newRefreshTokenCredentials") -public interface RefreshTokenCredentials extends LoginCredentials { +@XmlType +public class RefreshTokenCredentials implements LoginCredentials { + + private String tokenId; + private String refreshToken; + + public RefreshTokenCredentials() { + } + + /** + * Constructor. + * + * @param tokenId + * The {@link AccessToken#getTokenId()} + * @param refreshToken + * TThe {@link AccessToken#getRefreshToken()} + * @since 1.0.0 + */ + public RefreshTokenCredentials(String tokenId, String refreshToken) { + this.tokenId = tokenId; + this.refreshToken = refreshToken; + } /** * Gets the {@link AccessToken#getTokenId()} to authenticate. @@ -37,15 +57,20 @@ public interface RefreshTokenCredentials extends LoginCredentials { * @since 1.0.0 */ @XmlElement(name = "tokenId") - String getTokenId(); + public String getTokenId() { + return tokenId; + } /** * Set the {@link AccessToken#getTokenId()} to authenticate. * - * @param tokenId The {@link AccessToken#getTokenId()} to authenticate. + * @param tokenId + * The {@link AccessToken#getTokenId()} to authenticate. * @since 1.0.0 */ - void setTokenId(String tokenId); + public void setTokenId(String tokenId) { + this.tokenId = tokenId; + } /** * Gets the AccessToken#getRefreshToken()} to authenticate. @@ -54,13 +79,19 @@ public interface RefreshTokenCredentials extends LoginCredentials { * @since 1.0.0 */ @XmlElement(name = "refreshToken") - String getRefreshToken(); + public String getRefreshToken() { + return refreshToken; + } /** * Set the {@link AccessToken#getRefreshToken()} to authenticate. * - * @param refreshToken The AccessToken#getRefreshToken()} to authenticate. + * @param refreshToken + * The AccessToken#getRefreshToken()} to authenticate. * @since 1.0.0 */ - void setRefreshToken(String refreshToken); + public void setRefreshToken(String refreshToken) { + this.refreshToken = refreshToken; + } + } diff --git a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/UsernamePasswordCredentials.java b/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/UsernamePasswordCredentials.java index 425f706e3fd..4b126b0de7b 100644 --- a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/UsernamePasswordCredentials.java +++ b/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/UsernamePasswordCredentials.java @@ -24,8 +24,24 @@ */ @XmlRootElement(name = "usernamePasswordCredentials") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = AuthenticationXmlRegistry.class, factoryMethod = "newUsernamePasswordCredentials") -public interface UsernamePasswordCredentials extends LoginCredentials { +@XmlType +public class UsernamePasswordCredentials implements LoginCredentials { + + private static final long serialVersionUID = -7549848672967689716L; + + private String username; + private String password; + private String authenticationCode; + private String trustKey; + private boolean trustMe; + + public UsernamePasswordCredentials() { + } + + public UsernamePasswordCredentials(String username, String password) { + this.username = username; + this.password = password; + } /** * Gets the username. @@ -33,15 +49,20 @@ public interface UsernamePasswordCredentials extends LoginCredentials { * @return The username. * @since 1.0.0 */ - String getUsername(); + public String getUsername() { + return username; + } /** * Sets the username. * - * @param username The username. + * @param username + * The username. * @since 1.0.0 */ - void setUsername(String username); + public void setUsername(String username) { + this.username = username; + } /** * Gets the password. @@ -49,15 +70,20 @@ public interface UsernamePasswordCredentials extends LoginCredentials { * @return The password. * @since 1.0.0 */ - String getPassword(); + public String getPassword() { + return password; + } /** * Sets the password. * - * @param password The password. + * @param password + * The password. * @since 1.0.0 */ - void setPassword(String password); + public void setPassword(String password) { + this.password = password; + } /** * Gets the MFA authentication code. @@ -65,15 +91,20 @@ public interface UsernamePasswordCredentials extends LoginCredentials { * @return The MFA authentication code. * @since 1.3.0 */ - String getAuthenticationCode(); + public String getAuthenticationCode() { + return authenticationCode; + } /** * Sets the MFA authentication code. * - * @param authenticationCode The MFA authentication code. + * @param authenticationCode + * The MFA authentication code. * @since 1.3.0 */ - void setAuthenticationCode(String authenticationCode); + public void setAuthenticationCode(String authenticationCode) { + this.authenticationCode = authenticationCode; + } /** * Gets the trust key. @@ -81,15 +112,20 @@ public interface UsernamePasswordCredentials extends LoginCredentials { * @return The trust key. * @since 1.3.0 */ - String getTrustKey(); + public String getTrustKey() { + return trustKey; + } /** * Sets the trust key. * - * @param trustKey The trust key. + * @param trustKey + * The trust key. * @since 1.3.0 */ - void setTrustKey(String trustKey); + public void setTrustKey(String trustKey) { + this.trustKey = trustKey; + } /** * Gets whether create a trust key or not. @@ -97,13 +133,19 @@ public interface UsernamePasswordCredentials extends LoginCredentials { * @return {@code true} if to be created, {@code false} otherwise * @since 2.0.0 */ - boolean getTrustMe(); + public boolean getTrustMe() { + return trustMe; + } /** * Sets whether create a trust key or not. * - * @param trustMe {@code true} if to be created, {@code false} if not. + * @param trustMe + * {@code true} if to be created, {@code false} if not. * @since 2.0.0 */ - void setTrustMe(boolean trustMe); + public void setTrustMe(boolean trustMe) { + this.trustMe = trustMe; + } + } diff --git a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/credential/CredentialCreator.java b/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/credential/CredentialCreator.java index 9221fade50b..b405ed433d8 100644 --- a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/credential/CredentialCreator.java +++ b/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/credential/CredentialCreator.java @@ -12,11 +12,7 @@ *******************************************************************************/ package org.eclipse.kapua.service.authentication.credential; -import org.eclipse.kapua.model.KapuaEntityCreator; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.model.id.KapuaIdAdapter; -import org.eclipse.kapua.model.xml.DateXmlAdapter; -import org.eclipse.kapua.service.user.User; +import java.util.Date; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; @@ -24,7 +20,12 @@ import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; -import java.util.Date; + +import org.eclipse.kapua.model.KapuaEntityCreator; +import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.id.KapuaIdAdapter; +import org.eclipse.kapua.model.xml.DateXmlAdapter; +import org.eclipse.kapua.service.user.User; /** * {@link Credential} {@link KapuaEntityCreator} @@ -33,8 +34,59 @@ */ @XmlRootElement(name = "credentialCreator") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = CredentialXmlRegistry.class, factoryMethod = "newCredentialCreator") -public interface CredentialCreator extends KapuaEntityCreator { +@XmlType +public class CredentialCreator extends KapuaEntityCreator { + + private static final long serialVersionUID = -5020680413729882095L; + + private KapuaId userId; + private String credentialType; + private String credentialKey; + private Date expirationDate; + private CredentialStatus credentialStatus; + + public CredentialCreator() { + } + + public CredentialCreator(KapuaId scopeId) { + super(scopeId); + } + + public CredentialCreator(KapuaEntityCreator entityCreator) { + super(entityCreator); + } + + /** + * Constructor. + * + * @param scopeId + * The {@link CredentialCreator#getScopeId()} + * @param userId + * The {@link CredentialCreator#getUserId()} + * @param credentialType + * The {@link CredentialCreator#getCredentialType()} + * @param credentialKey + * The plain {@link CredentialCreator#getCredentialPlainKey()} + * @param credentialStatus + * The {@link CredentialCreator#getCredentialStatus()} + * @param expirationDate + * The {@link CredentialCreator#getExpirationDate()} + * @since 1.0.0 + */ + public CredentialCreator(KapuaId scopeId, + KapuaId userId, + String credentialType, + String credentialKey, + CredentialStatus credentialStatus, + Date expirationDate) { + super(scopeId); + + this.userId = userId; + this.credentialType = credentialType; + this.credentialKey = credentialKey; + this.credentialStatus = credentialStatus; + this.expirationDate = expirationDate; + } /** * Gets the {@link User#getId()} owner of the {@link Credential} @@ -44,15 +96,20 @@ public interface CredentialCreator extends KapuaEntityCreator { */ @XmlElement(name = "userId") @XmlJavaTypeAdapter(KapuaIdAdapter.class) - KapuaId getUserId(); + public KapuaId getUserId() { + return userId; + } /** * Sets the {@link User#getId()} owner of the {@link Credential} * - * @param userId The {@link User#getId()} + * @param userId + * The {@link User#getId()} * @since 1.0.0 */ - void setUserId(KapuaId userId); + public void setUserId(KapuaId userId) { + this.userId = userId; + } /** * Gets the type. @@ -61,15 +118,20 @@ public interface CredentialCreator extends KapuaEntityCreator { * @since 1.0.0 */ @XmlElement(name = "credentialType") - String getCredentialType(); + public String getCredentialType() { + return credentialType; + } /** * Sets the type. * - * @param credentialType The type. + * @param credentialType + * The type. * @since 1.0.0 */ - void setCredentialType(String credentialType); + public void setCredentialType(String credentialType) { + this.credentialType = credentialType; + } /** * Gets the plain secret key @@ -78,15 +140,20 @@ public interface CredentialCreator extends KapuaEntityCreator { * @since 1.0.0 */ @XmlElement(name = "credentialKey") - String getCredentialPlainKey(); + public String getCredentialPlainKey() { + return credentialKey; + } /** * Set the plain secret key * - * @param plainKey The plain secret key + * @param plainKey + * The plain secret key * @since 1.0.0 */ - void setCredentialPlainKey(String plainKey); + public void setCredentialPlainKey(String plainKey) { + this.credentialKey = plainKey; + } /** * Gets the expiration date @@ -96,15 +163,20 @@ public interface CredentialCreator extends KapuaEntityCreator { */ @XmlElement(name = "expirationDate") @XmlJavaTypeAdapter(DateXmlAdapter.class) - Date getExpirationDate(); + public Date getExpirationDate() { + return expirationDate; + } /** * Sets the expiration date * - * @param expirationDate The expiration date + * @param expirationDate + * The expiration date * @since 1.0.0 */ - void setExpirationDate(Date expirationDate); + public void setExpirationDate(Date expirationDate) { + this.expirationDate = expirationDate; + } /** * Gets the {@link CredentialStatus} @@ -113,13 +185,18 @@ public interface CredentialCreator extends KapuaEntityCreator { * @since 1.0.0 */ @XmlElement(name = "credentialStatus") - CredentialStatus getCredentialStatus(); + public CredentialStatus getCredentialStatus() { + return credentialStatus; + } /** * Sets the {@link CredentialStatus} * - * @param credentialStatus The {@link CredentialStatus} + * @param credentialStatus + * The {@link CredentialStatus} * @since 1.0.0 */ - void setCredentialStatus(CredentialStatus credentialStatus); + public void setCredentialStatus(CredentialStatus credentialStatus) { + this.credentialStatus = credentialStatus; + } } diff --git a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/credential/CredentialFactory.java b/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/credential/CredentialFactory.java index 42434a61f87..5cfa2a99c73 100644 --- a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/credential/CredentialFactory.java +++ b/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/credential/CredentialFactory.java @@ -12,43 +12,36 @@ *******************************************************************************/ package org.eclipse.kapua.service.authentication.credential; +import java.util.Date; + import org.eclipse.kapua.model.KapuaEntityFactory; import org.eclipse.kapua.model.id.KapuaId; -import java.util.Date; - /** * {@link Credential} {@link KapuaEntityFactory} definition. * * @since 1.0.0 */ -public interface CredentialFactory extends KapuaEntityFactory { +public interface CredentialFactory extends KapuaEntityFactory { /** * Instantiates a new {@link Credential}. * - * @param scopeId The scope {@link KapuaId} to set into the {@link Credential}. - * @param userId The {@link org.eclipse.kapua.service.user.User} {@link KapuaId} to set into the {@link Credential}. - * @param credentialType The {@link Credential} type to set into the {@link Credential}. - * @param credentialKey The key to set into the {@link Credential}. - * @param credentialStatus The {@link CredentialStatus} to set into the {@link Credential}. - * @param expirationDate The expiration date to set into the {@link Credential}. + * @param scopeId + * The scope {@link KapuaId} to set into the {@link Credential}. + * @param userId + * The {@link org.eclipse.kapua.service.user.User} {@link KapuaId} to set into the {@link Credential}. + * @param credentialType + * The {@link Credential} type to set into the {@link Credential}. + * @param credentialKey + * The key to set into the {@link Credential}. + * @param credentialStatus + * The {@link CredentialStatus} to set into the {@link Credential}. + * @param expirationDate + * The expiration date to set into the {@link Credential}. * @return The newly instantiated {@link Credential} * @since 1.0.0 */ Credential newCredential(KapuaId scopeId, KapuaId userId, String credentialType, String credentialKey, CredentialStatus credentialStatus, Date expirationDate); - /** - * Instantiates a new {@link CredentialCreator}. - * - * @param scopeId The scope {@link KapuaId} to set into the {@link CredentialCreator}. - * @param userId The {@link org.eclipse.kapua.service.user.User} {@link KapuaId} to set into the {@link CredentialCreator}. - * @param credentialType The {@link Credential} type to set into the {@link CredentialCreator}. - * @param credentialKey The key to set into the {@link CredentialCreator}. - * @param credentialStatus The {@link CredentialStatus} to set into the {@link CredentialCreator}. - * @param expirationDate The expiration date to set into the {@link CredentialCreator}. - * @return The newly instantiated {@link CredentialCreator} - * @since 1.0.0 - */ - CredentialCreator newCreator(KapuaId scopeId, KapuaId userId, String credentialType, String credentialKey, CredentialStatus credentialStatus, Date expirationDate); } diff --git a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/credential/CredentialListResult.java b/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/credential/CredentialListResult.java index bfec64cea74..5b2ef707c00 100644 --- a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/credential/CredentialListResult.java +++ b/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/credential/CredentialListResult.java @@ -26,7 +26,9 @@ */ @XmlRootElement(name = "credentialListResult") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = CredentialXmlRegistry.class, factoryMethod = "newCredentialListResult") -public interface CredentialListResult extends KapuaListResult { +@XmlType +public class CredentialListResult extends KapuaListResult { + + static final long serialVersionUID = -7949012585401032274L; } diff --git a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/credential/CredentialQuery.java b/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/credential/CredentialQuery.java deleted file mode 100644 index 9e235aba25c..00000000000 --- a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/credential/CredentialQuery.java +++ /dev/null @@ -1,32 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authentication.credential; - -import org.eclipse.kapua.model.query.KapuaQuery; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlType; - -/** - * {@link Credential} {@link KapuaQuery} definition. - * - * @see KapuaQuery - * @since 1.0.0 - */ -@XmlRootElement(name = "query") -@XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = CredentialXmlRegistry.class, factoryMethod = "newCredentialQuery") -public interface CredentialQuery extends KapuaQuery { -} diff --git a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/credential/CredentialService.java b/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/credential/CredentialService.java index 852888961d4..a83a22f34a6 100644 --- a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/credential/CredentialService.java +++ b/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/credential/CredentialService.java @@ -12,6 +12,8 @@ *******************************************************************************/ package org.eclipse.kapua.service.authentication.credential; +import java.util.Set; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.model.query.KapuaQuery; @@ -21,8 +23,6 @@ import org.eclipse.kapua.service.config.KapuaConfigurableService; import org.eclipse.kapua.service.user.User; -import java.util.Set; - /** * {@link Credential} {@link KapuaEntityService} definition. * @@ -35,8 +35,10 @@ public interface CredentialService extends KapuaEntityService { +@XmlType +public class MfaOptionCreator extends KapuaEntityCreator { + + private static final long serialVersionUID = -4619585500941519330L; + + private KapuaId userId; + + public MfaOptionCreator() { + } + + public MfaOptionCreator(KapuaId scopeId) { + super(scopeId); + } + + public MfaOptionCreator(KapuaEntityCreator entityCreator) { + super(entityCreator); + } + + /** + * Constructor + * + * @param scopeId + * scope identifier + * @param userId + * user identifier + */ + public MfaOptionCreator(KapuaId scopeId, KapuaId userId) { + super(scopeId); + this.userId = userId; + } /** * Gets the {@link User#getId()} @@ -42,13 +70,18 @@ public interface MfaOptionCreator extends KapuaEntityCreator { */ @XmlElement(name = "userId") @XmlJavaTypeAdapter(KapuaIdAdapter.class) - KapuaId getUserId(); + public KapuaId getUserId() { + return userId; + } /** * Sets the {@link User#getId()} * - * @param userId The {@link User#getId()} + * @param userId + * The {@link User#getId()} * @since 1.3.0 */ - void setUserId(KapuaId userId); + public void setUserId(KapuaId userId) { + this.userId = userId; + } } diff --git a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/MfaOptionFactory.java b/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/MfaOptionFactory.java index 72734309d73..7f8f103d27f 100644 --- a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/MfaOptionFactory.java +++ b/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/MfaOptionFactory.java @@ -13,8 +13,6 @@ package org.eclipse.kapua.service.authentication.credential.mfa; import org.eclipse.kapua.model.KapuaEntityFactory; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.authentication.token.AccessToken; /** * {@link MfaOption} {@link KapuaEntityFactory} definition. @@ -22,16 +20,6 @@ * @see KapuaEntityFactory * @since 1.3.0 */ -public interface MfaOptionFactory extends KapuaEntityFactory { - - /** - * Instantiates a new {@link MfaOptionCreator}. - * - * @param scopeId The scope {@link KapuaId} to set into the {@link MfaOptionCreator}. - * @param userId The {@link org.eclipse.kapua.service.user.User} {@link KapuaId} to set into the{@link AccessToken}. - * @return The newly instantiated {@link MfaOptionCreator} - * @since 1.3.0 - */ - MfaOptionCreator newCreator(KapuaId scopeId, KapuaId userId); +public interface MfaOptionFactory extends KapuaEntityFactory { } diff --git a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/MfaOptionListResult.java b/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/MfaOptionListResult.java index 2f9ebbcd453..bc729c21269 100644 --- a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/MfaOptionListResult.java +++ b/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/MfaOptionListResult.java @@ -12,13 +12,13 @@ *******************************************************************************/ package org.eclipse.kapua.service.authentication.credential.mfa; -import org.eclipse.kapua.model.query.KapuaListResult; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; +import org.eclipse.kapua.model.query.KapuaListResult; + /** * {@link MfaOption} {@link KapuaListResult} definition. * @@ -26,7 +26,9 @@ */ @XmlRootElement(name = "mfaOptionListResult") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = MfaOptionXmlRegistry.class, factoryMethod = "newMfaOptionListResult") -public interface MfaOptionListResult extends KapuaListResult { +@XmlType +public class MfaOptionListResult extends KapuaListResult { + + private static final long serialVersionUID = -4204695192086365901L; } diff --git a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/MfaOptionQuery.java b/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/MfaOptionQuery.java deleted file mode 100644 index 33cc42ad3b7..00000000000 --- a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/MfaOptionQuery.java +++ /dev/null @@ -1,32 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2020, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authentication.credential.mfa; - -import org.eclipse.kapua.model.query.KapuaQuery; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlType; - -/** - * {@link MfaOption} {@link KapuaQuery} definition. - * - * @see KapuaQuery - * @since 1.3.0 - */ -@XmlRootElement(name = "query") -@XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = MfaOptionXmlRegistry.class, factoryMethod = "newQuery") -public interface MfaOptionQuery extends KapuaQuery { -} diff --git a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/MfaOptionXmlRegistry.java b/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/MfaOptionXmlRegistry.java index 033942201c0..7988d0991a4 100644 --- a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/MfaOptionXmlRegistry.java +++ b/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/MfaOptionXmlRegistry.java @@ -12,25 +12,15 @@ *******************************************************************************/ package org.eclipse.kapua.service.authentication.credential.mfa; -import org.eclipse.kapua.locator.KapuaLocator; - import javax.xml.bind.annotation.XmlRegistry; +import org.eclipse.kapua.locator.KapuaLocator; + @XmlRegistry public class MfaOptionXmlRegistry { private final MfaOptionFactory mfaOptionFactory = KapuaLocator.getInstance().getFactory(MfaOptionFactory.class); - /** - * Instantiates a new {@link MfaOptionCreator} instance - * - * @return The newly instantiated {@link MfaOptionCreator} - * @since 1.3.0 - */ - public MfaOptionCreator newMfaOptionCreator() { - return mfaOptionFactory.newCreator(null, null); - } - /** * Instantiates a new {@link MfaOption} instance * @@ -40,24 +30,4 @@ public MfaOptionCreator newMfaOptionCreator() { public MfaOption newMfaOption() { return mfaOptionFactory.newEntity(null); } - - /** - * Instantiates a new {@link MfaOptionListResult} instance - * - * @return The newly instantiated {@link MfaOptionListResult} - * @since 1.3.0 - */ - public MfaOptionListResult newMfaOptionListResult() { - return mfaOptionFactory.newListResult(); - } - - /** - * Instantiates a new {@link MfaOptionQuery} instance. - * - * @return The newly instantiated {@link MfaOptionQuery} - * @since 1.3.0 - */ - public MfaOptionQuery newQuery() { - return mfaOptionFactory.newQuery(null); - } } diff --git a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/ScratchCodeFactory.java b/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/ScratchCodeFactory.java index d055ddcc70e..d1d702a6e49 100644 --- a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/ScratchCodeFactory.java +++ b/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/ScratchCodeFactory.java @@ -15,7 +15,6 @@ import org.eclipse.kapua.model.KapuaEntityFactory; import org.eclipse.kapua.model.KapuaObjectFactory; import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.model.query.KapuaListResult; /** * {@link ScratchCode} {@link KapuaEntityFactory} definition. @@ -27,26 +26,23 @@ public interface ScratchCodeFactory extends KapuaObjectFactory { /** * Instantiates a new {@link ScratchCode}. - * @param scopeId The {@link ScratchCode#getScopeId()} + * + * @param scopeId + * The {@link ScratchCode#getScopeId()} * @return The newly instantiated {@link ScratchCode} * @since 1.3.0 */ ScratchCode newEntity(KapuaId scopeId); - /** - * Instantiates a new {@link KapuaListResult}. - * - * @return The newly instantiated {@link KapuaListResult} - * @since 1.0.0 - */ - ScratchCodeListResult newListResult(); - /** * Instantiates a new {@link ScratchCode}. * - * @param scopeId The {@link ScratchCode#getScopeId()} - * @param mfaOptionId The {@link MfaOption#getId()} - * @param code The {@link ScratchCode#getCode()}. + * @param scopeId + * The {@link ScratchCode#getScopeId()} + * @param mfaOptionId + * The {@link MfaOption#getId()} + * @param code + * The {@link ScratchCode#getCode()}. * @return The newly instantiated {@link ScratchCode} * @since 1.3.0 */ diff --git a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/ScratchCodeListResult.java b/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/ScratchCodeListResult.java index a34014fb6e6..9d375196a40 100644 --- a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/ScratchCodeListResult.java +++ b/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/ScratchCodeListResult.java @@ -12,19 +12,21 @@ *******************************************************************************/ package org.eclipse.kapua.service.authentication.credential.mfa; -import org.eclipse.kapua.model.query.KapuaListResult; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; +import org.eclipse.kapua.model.query.KapuaListResult; + /** * {@link ScratchCode} {@link KapuaListResult} definition. */ @XmlRootElement(name = "scratchCodeListResult") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = ScratchCodeXmlRegistry.class, factoryMethod = "newScratchCodeListResult") -public interface ScratchCodeListResult extends KapuaListResult { +@XmlType +public class ScratchCodeListResult extends KapuaListResult { + + private static final long serialVersionUID = -5154461760797879319L; } diff --git a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/ScratchCodeXmlRegistry.java b/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/ScratchCodeXmlRegistry.java index 41a194f7b52..726ab4f071c 100644 --- a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/ScratchCodeXmlRegistry.java +++ b/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/ScratchCodeXmlRegistry.java @@ -12,10 +12,10 @@ *******************************************************************************/ package org.eclipse.kapua.service.authentication.credential.mfa; -import org.eclipse.kapua.locator.KapuaLocator; - import javax.xml.bind.annotation.XmlRegistry; +import org.eclipse.kapua.locator.KapuaLocator; + @XmlRegistry public class ScratchCodeXmlRegistry { @@ -30,14 +30,4 @@ public class ScratchCodeXmlRegistry { public ScratchCode newScratchCode() { return scratchCodeFactory.newEntity(null); } - - /** - * Instantiates a new {@link ScratchCodeListResult} instance - * - * @return The newly instantiated {@link ScratchCodeListResult} - * @since 1.3.0 - */ - public ScratchCodeListResult newScratchCodeListResult() { - return scratchCodeFactory.newListResult(); - } } diff --git a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/token/AccessTokenCreator.java b/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/token/AccessTokenCreator.java index 91d1703c670..fb62ad4146d 100644 --- a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/token/AccessTokenCreator.java +++ b/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/token/AccessTokenCreator.java @@ -12,15 +12,16 @@ *******************************************************************************/ package org.eclipse.kapua.service.authentication.token; -import org.eclipse.kapua.model.KapuaEntityCreator; -import org.eclipse.kapua.model.id.KapuaId; +import java.util.Date; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; -import java.util.Date; + +import org.eclipse.kapua.model.KapuaEntityCreator; +import org.eclipse.kapua.model.id.KapuaId; /** * Access token creator service definition @@ -28,35 +29,89 @@ * @since 1.0 */ @XmlRootElement -@XmlAccessorType(XmlAccessType.FIELD) +@XmlAccessorType(XmlAccessType.PROPERTY) @XmlType(propOrder = { "tokenId", "userId", "expiresOn", "refreshToken", "refreshExpiresOn", "tokenIdentifier" -}, // - factoryClass = AccessTokenXmlRegistry.class, // - factoryMethod = "newAccessTokenCreator") -public interface AccessTokenCreator extends KapuaEntityCreator { +}) +public class AccessTokenCreator extends KapuaEntityCreator { + + private static final long serialVersionUID = -27718046815190710L; + + private String tokenId; + private KapuaId userId; + private Date expiresOn; + private String refreshToken; + private Date refreshExpiresOn; + private String tokenIdentifier; + + public AccessTokenCreator() { + } + + public AccessTokenCreator(KapuaId scopeId) { + super(scopeId); + } + + public AccessTokenCreator(KapuaEntityCreator entityCreator) { + super(entityCreator); + } + + /** + * Instantiates a new {@link AccessTokenCreator}. + * + * @param scopeId + * The scope {@link KapuaId} to set into the{@link AccessToken}. + * @param userId + * The {@link org.eclipse.kapua.service.user.User} {@link KapuaId} to set into the{@link AccessToken}. + * @param tokenId + * The token id to set into the{@link AccessToken}. + * @param expiresOn + * The expiration date to set into the{@link AccessToken}. + * @param refreshToken + * The refresh token to set into the{@link AccessToken}. + * @since 1.0.0 + */ + public AccessTokenCreator( + KapuaId scopeId, + KapuaId userId, + String tokenId, + Date expiresOn, + String refreshToken, + Date refreshExpiresOn, + String tokenIdentifier) { + super(scopeId); + this.userId = userId; + this.tokenId = tokenId; + this.expiresOn = expiresOn; + this.refreshToken = refreshToken; + this.refreshExpiresOn = refreshExpiresOn; + this.tokenIdentifier = tokenIdentifier; + } /** - * Gets the token id - * This represents the content of the JWT token + * Gets the token id This represents the content of the JWT token * * @return The token id * @since 1.0 */ @XmlElement(name = "tokenId") - String getTokenId(); + public String getTokenId() { + return tokenId; + } /** * Sets the token id * - * @param tokenId the token id to set + * @param tokenId + * the token id to set * @since 1.0 */ - void setTokenId(String tokenId); + public void setTokenId(String tokenId) { + this.tokenId = tokenId; + } /** * Gets the user id owner of this token @@ -65,15 +120,20 @@ public interface AccessTokenCreator extends KapuaEntityCreator { * @since 1.0 */ @XmlElement(name = "userId") - KapuaId getUserId(); + public KapuaId getUserId() { + return userId; + } /** * Sets the user id owner of this token. * - * @param userId The user id owner of this token. + * @param userId + * The user id owner of this token. * @since 1.0 */ - void setUserId(KapuaId userId); + public void setUserId(KapuaId userId) { + this.userId = userId; + } /** * Gets the expire date of this token. @@ -82,15 +142,20 @@ public interface AccessTokenCreator extends KapuaEntityCreator { * @since 1.0 */ @XmlElement(name = "expiresOn") - Date getExpiresOn(); + public Date getExpiresOn() { + return expiresOn; + } /** * Sets the expire date of this token. * - * @param expiresOn The expire date of this token. + * @param expiresOn + * The expire date of this token. * @since 1.0 */ - void setExpiresOn(Date expiresOn); + public void setExpiresOn(Date expiresOn) { + this.expiresOn = expiresOn; + } /** * Gets the refresh token to obtain a new {@link AccessToken} after expiration. @@ -98,15 +163,20 @@ public interface AccessTokenCreator extends KapuaEntityCreator { * @since 1.0 */ @XmlElement(name = "refreshToken") - String getRefreshToken(); + public String getRefreshToken() { + return refreshToken; + } /** * Sets the refresh token to obtain a new {@link AccessToken} after expiration. * - * @param refreshToken The refresh token + * @param refreshToken + * The refresh token * @since 1.0 */ - void setRefreshToken(String refreshToken); + public void setRefreshToken(String refreshToken) { + this.refreshToken = refreshToken; + } /** * Gets the expiration date of the refresh token. @@ -114,33 +184,41 @@ public interface AccessTokenCreator extends KapuaEntityCreator { * @since 1.0 */ @XmlElement(name = "refreshExpiresOn") - Date getRefreshExpiresOn(); + public Date getRefreshExpiresOn() { + return refreshExpiresOn; + } /** * Sets the expire date of this token. * - * @param refreshExpiresOn The expiration date of the refresh token. + * @param refreshExpiresOn + * The expiration date of the refresh token. * @since 1.0 */ - void setRefreshExpiresOn(Date refreshExpiresOn); + public void setRefreshExpiresOn(Date refreshExpiresOn) { + this.refreshExpiresOn = refreshExpiresOn; + } /** - * Gets the token identifier - * This represents an id for the JWT token and is meant to be inserted inside its payload + * Gets the token identifier This represents an id for the JWT token and is meant to be inserted inside its payload * * @return The token id * @since 2.0 */ @XmlElement(name = "tokenIdentifier") - String getTokenIdentifier(); + public String getTokenIdentifier() { + return tokenIdentifier; + } /** * Sets the token identifier * - * @param tokenId the token id to set + * @param tokenId + * the token id to set * @since 2.0 */ - void setTokenIdentifier(String tokenId); - + public void setTokenIdentifier(String tokenId) { + this.tokenIdentifier = tokenId; + } } diff --git a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/token/AccessTokenFactory.java b/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/token/AccessTokenFactory.java index 5aabab8123b..a3d74e51f3f 100644 --- a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/token/AccessTokenFactory.java +++ b/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/token/AccessTokenFactory.java @@ -13,9 +13,6 @@ package org.eclipse.kapua.service.authentication.token; import org.eclipse.kapua.model.KapuaEntityFactory; -import org.eclipse.kapua.model.id.KapuaId; - -import java.util.Date; /** * {@link AccessTokenFactory} definition. @@ -23,26 +20,6 @@ * @see org.eclipse.kapua.model.KapuaEntityFactory * @since 1.0.0 */ -public interface AccessTokenFactory extends KapuaEntityFactory { - - /** - * Instantiates a new {@link AccessTokenCreator}. - * - * @param scopeId The scope {@link KapuaId} to set into the{@link AccessToken}. - * @param userId The {@link org.eclipse.kapua.service.user.User} {@link KapuaId} to set into the{@link AccessToken}. - * @param tokenId The token id to set into the{@link AccessToken}. - * @param expiresOn The expiration date to set into the{@link AccessToken}. - * @param refreshToken The refresh token to set into the{@link AccessToken}. - * @return The newly instantiated {@link AccessTokenCreator}. - * @since 1.0.0 - */ - AccessTokenCreator newCreator(KapuaId scopeId, KapuaId userId, String tokenId, Date expiresOn, String refreshToken, Date refreshExpiresOn, String tokenIdentifier); - - /** - * Instantiates a new {@link LoginInfo} - * - * @return a new {@link LoginInfo} object - */ - LoginInfo newLoginInfo(); +public interface AccessTokenFactory extends KapuaEntityFactory { } diff --git a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/token/AccessTokenListResult.java b/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/token/AccessTokenListResult.java index 1aac02406e8..6ce21f55b6f 100644 --- a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/token/AccessTokenListResult.java +++ b/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/token/AccessTokenListResult.java @@ -18,8 +18,9 @@ * Access token list result definition. * * @since 1.0 - * */ -public interface AccessTokenListResult extends KapuaListResult { +public class AccessTokenListResult extends KapuaListResult { + + private static final long serialVersionUID = -2596004122285166444L; } diff --git a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/token/AccessTokenQuery.java b/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/token/AccessTokenQuery.java deleted file mode 100644 index fb49ebcd280..00000000000 --- a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/token/AccessTokenQuery.java +++ /dev/null @@ -1,24 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authentication.token; - -import org.eclipse.kapua.model.query.KapuaQuery; - -/** - * {@link AccessToken} {@link KapuaQuery} definition. - * - * @see KapuaQuery - * @since 1.0.0 - */ -public interface AccessTokenQuery extends KapuaQuery { -} diff --git a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/token/AccessTokenXmlRegistry.java b/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/token/AccessTokenXmlRegistry.java index 8c313ac1d35..c228c2c92b1 100644 --- a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/token/AccessTokenXmlRegistry.java +++ b/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/token/AccessTokenXmlRegistry.java @@ -12,10 +12,10 @@ *******************************************************************************/ package org.eclipse.kapua.service.authentication.token; -import org.eclipse.kapua.locator.KapuaLocator; - import javax.xml.bind.annotation.XmlRegistry; +import org.eclipse.kapua.locator.KapuaLocator; + @XmlRegistry public class AccessTokenXmlRegistry { @@ -24,8 +24,4 @@ public class AccessTokenXmlRegistry { public AccessToken newAccessToken() { return accessTokenFactory.newEntity(null); } - - public AccessTokenCreator newAccessTokenCreator() { - return accessTokenFactory.newCreator(null, null, null, null, null, null, null); - } } diff --git a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/token/LoginInfo.java b/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/token/LoginInfo.java index 675897ec573..9177e9fb6a5 100644 --- a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/token/LoginInfo.java +++ b/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/token/LoginInfo.java @@ -12,35 +12,52 @@ *******************************************************************************/ package org.eclipse.kapua.service.authentication.token; +import java.util.Set; + import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; -import java.util.Set; - import org.eclipse.kapua.KapuaSerializable; import org.eclipse.kapua.service.authorization.access.AccessPermission; import org.eclipse.kapua.service.authorization.role.RolePermission; @XmlRootElement @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = AccessTokenXmlRegistry.class, factoryMethod = "newAccessToken") -public interface LoginInfo extends KapuaSerializable { +@XmlType +public class LoginInfo implements KapuaSerializable { + + private AccessToken accessToken; + private Set rolePermissions; + private Set accessPermissions; @XmlElement(name = "accessToken") - AccessToken getAccessToken(); + public AccessToken getAccessToken() { + return accessToken; + } - void setAccessToken(AccessToken accessToken); + public void setAccessToken(AccessToken accessToken) { + this.accessToken = accessToken; + } @XmlElement(name = "rolePermission") - Set getRolePermission(); + public Set getRolePermission() { + return rolePermissions; + } - void setRolePermission(Set rolePermissions); + public void setRolePermission(Set rolePermissions) { + this.rolePermissions = rolePermissions; + } @XmlElement(name = "accessPermission") - Set getAccessPermission(); + public Set getAccessPermission() { + return accessPermissions; + } + + public void setAccessPermission(Set accessPermissions) { + this.accessPermissions = accessPermissions; + } - void setAccessPermission(Set accessPermissions); } diff --git a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/user/PasswordChangeRequest.java b/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/user/PasswordChangeRequest.java index a60c9d97e99..1338e091b69 100644 --- a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/user/PasswordChangeRequest.java +++ b/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/user/PasswordChangeRequest.java @@ -20,19 +20,28 @@ @XmlRootElement @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = UserCredentialsXmlRegistry.class, factoryMethod = "newPasswordChangeRequest") -public interface PasswordChangeRequest { - @XmlElement(name = "currentPassword") - String getCurrentPassword(); +@XmlType +public class PasswordChangeRequest { + private String newPassword; + private String currentPassword; - void setCurrentPassword(String currentPassword); + @XmlElement(name = "currentPassword") + public String getCurrentPassword() { + return currentPassword; + } + public void setCurrentPassword(String currentPassword) { + this.currentPassword = currentPassword; + } @XmlElement(name = "newPassword") - String getNewPassword(); - + public String getNewPassword() { + return newPassword; + } - void setNewPassword(String newPassword); + public void setNewPassword(String newPassword) { + this.newPassword = newPassword; + } } diff --git a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/user/PasswordResetRequest.java b/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/user/PasswordResetRequest.java index 2161bf9818c..cacd3e8acc1 100644 --- a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/user/PasswordResetRequest.java +++ b/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/user/PasswordResetRequest.java @@ -12,7 +12,6 @@ *******************************************************************************/ package org.eclipse.kapua.service.authentication.user; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; @@ -21,11 +20,18 @@ @XmlRootElement @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = UserCredentialsXmlRegistry.class, factoryMethod = "newPasswordResetRequest") -public interface PasswordResetRequest { +@XmlType +public class PasswordResetRequest { + + private String newPassword; + @XmlElement(name = "newPassword") - String getNewPassword(); + public String getNewPassword() { + return newPassword; + } + public void setNewPassword(String newPassword) { + this.newPassword = newPassword; + } - void setNewPassword(String newPassword); } diff --git a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/user/UserCredentialsFactory.java b/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/user/UserCredentialsFactory.java deleted file mode 100644 index 5d1512a83ec..00000000000 --- a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/user/UserCredentialsFactory.java +++ /dev/null @@ -1,40 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2023, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authentication.user; - -import org.eclipse.kapua.model.KapuaObjectFactory; - -/** - * {@link UserCredentialsFactory} definition. - * - * @see org.eclipse.kapua.model.KapuaEntityFactory - * @since 2.0.0 - */ -public interface UserCredentialsFactory extends KapuaObjectFactory { - /** - * Instantiates a new {@link PasswordChangeRequest}. - * - * @return The newly instantiated {@link PasswordChangeRequest} - * @since 2.0.0 - */ - PasswordChangeRequest newPasswordChangeRequest(); - - - /** - * Instantiates a new {@link PasswordResetRequest}. - * - * @return The newly instantiated {@link PasswordResetRequest} - * @since 2.0.0 - */ - PasswordResetRequest newPasswordResetRequest(); -} diff --git a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/user/UserCredentialsXmlRegistry.java b/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/user/UserCredentialsXmlRegistry.java deleted file mode 100644 index e83e5ebe08a..00000000000 --- a/service/security/authentication/api/src/main/java/org/eclipse/kapua/service/authentication/user/UserCredentialsXmlRegistry.java +++ /dev/null @@ -1,44 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authentication.user; - -import org.eclipse.kapua.locator.KapuaLocator; - -import javax.xml.bind.annotation.XmlRegistry; - -@XmlRegistry -public class UserCredentialsXmlRegistry { - - private final UserCredentialsFactory userCredentialsFactory = KapuaLocator.getInstance().getFactory(UserCredentialsFactory.class); - - - /** - * Creates a new credential instance - * - * @return - */ - public PasswordChangeRequest newPasswordChangeRequest() { - return userCredentialsFactory.newPasswordChangeRequest(); - } - - - /** - * Creates a new reset password request - * - * @return - */ - public PasswordResetRequest newPasswordResetRequest() { - return userCredentialsFactory.newPasswordResetRequest(); - } - -} diff --git a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/token/shiro/LoginInfoImplTest.java b/service/security/authentication/api/src/test/java/org/eclipse/kapua/service/authentication/token/LoginInfoTest.java similarity index 55% rename from service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/token/shiro/LoginInfoImplTest.java rename to service/security/authentication/api/src/test/java/org/eclipse/kapua/service/authentication/token/LoginInfoTest.java index 00f5b66cb56..52be7bb854f 100644 --- a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/token/shiro/LoginInfoImplTest.java +++ b/service/security/authentication/api/src/test/java/org/eclipse/kapua/service/authentication/token/LoginInfoTest.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2021, 2022 Eurotech and/or its affiliates and others + * Copyright (c) 2019, 2022 Eurotech and/or its affiliates and others * * This program and the accompanying materials are made * available under the terms of the Eclipse Public License 2.0 @@ -10,10 +10,12 @@ * Contributors: * Eurotech - initial API and implementation *******************************************************************************/ -package org.eclipse.kapua.service.authentication.token.shiro; +package org.eclipse.kapua.service.authentication.token; + +import java.util.HashSet; +import java.util.Set; import org.eclipse.kapua.qa.markers.junit.JUnitTests; -import org.eclipse.kapua.service.authentication.token.AccessToken; import org.eclipse.kapua.service.authorization.access.AccessPermission; import org.eclipse.kapua.service.authorization.role.RolePermission; import org.junit.Assert; @@ -22,39 +24,35 @@ import org.junit.experimental.categories.Category; import org.mockito.Mockito; -import java.util.HashSet; -import java.util.Set; - - @Category(JUnitTests.class) -public class LoginInfoImplTest { +public class LoginInfoTest { - LoginInfoImpl loginInfoImpl; + LoginInfo loginInfo; Set rolePermissions; Set accessPermissions; @Before public void initialize() { - loginInfoImpl = new LoginInfoImpl(); + loginInfo = new LoginInfo(); rolePermissions = new HashSet<>(); accessPermissions = new HashSet<>(); } @Test public void setAndGetAccessTokenTest() { - AccessToken[] accessTokens = {null, Mockito.mock(AccessToken.class)}; - Assert.assertNull("Null expected.", loginInfoImpl.getAccessToken()); + AccessToken[] accessTokens = { null, Mockito.mock(AccessToken.class) }; + Assert.assertNull("Null expected.", loginInfo.getAccessToken()); for (AccessToken accessToken : accessTokens) { - loginInfoImpl.setAccessToken(accessToken); - Assert.assertEquals("Expected and actual values should be the same.", accessToken, loginInfoImpl.getAccessToken()); + loginInfo.setAccessToken(accessToken); + Assert.assertEquals("Expected and actual values should be the same.", accessToken, loginInfo.getAccessToken()); } } @Test public void setAndGetRolePermissionEmptySetTest() { - Assert.assertNull("Null expected.", loginInfoImpl.getRolePermission()); - loginInfoImpl.setRolePermission(rolePermissions); - Assert.assertEquals("Expected and actual values should be the same.", rolePermissions, loginInfoImpl.getRolePermission()); + Assert.assertNull("Null expected.", loginInfo.getRolePermission()); + loginInfo.setRolePermission(rolePermissions); + Assert.assertEquals("Expected and actual values should be the same.", rolePermissions, loginInfo.getRolePermission()); } @Test @@ -62,23 +60,23 @@ public void setAndGetRolePermissionTest() { rolePermissions.add(Mockito.mock(RolePermission.class)); rolePermissions.add(Mockito.mock(RolePermission.class)); - Assert.assertNull("Null expected.", loginInfoImpl.getRolePermission()); - loginInfoImpl.setRolePermission(rolePermissions); - Assert.assertEquals("Expected and actual values should be the same.", rolePermissions, loginInfoImpl.getRolePermission()); + Assert.assertNull("Null expected.", loginInfo.getRolePermission()); + loginInfo.setRolePermission(rolePermissions); + Assert.assertEquals("Expected and actual values should be the same.", rolePermissions, loginInfo.getRolePermission()); } @Test public void setAndGetRolePermissionNullTest() { - Assert.assertNull("Null expected.", loginInfoImpl.getRolePermission()); - loginInfoImpl.setRolePermission(null); - Assert.assertNull("Null expected.", loginInfoImpl.getRolePermission()); + Assert.assertNull("Null expected.", loginInfo.getRolePermission()); + loginInfo.setRolePermission(null); + Assert.assertNull("Null expected.", loginInfo.getRolePermission()); } @Test public void setAndGetAccessPermissionEmptySetTest() { - Assert.assertNull("Null expected.", loginInfoImpl.getAccessPermission()); - loginInfoImpl.setAccessPermission(accessPermissions); - Assert.assertEquals("Expected and actual values should be the same.", accessPermissions, loginInfoImpl.getAccessPermission()); + Assert.assertNull("Null expected.", loginInfo.getAccessPermission()); + loginInfo.setAccessPermission(accessPermissions); + Assert.assertEquals("Expected and actual values should be the same.", accessPermissions, loginInfo.getAccessPermission()); } @Test @@ -86,15 +84,15 @@ public void setAndGetAccessPermissionTest() { accessPermissions.add(Mockito.mock(AccessPermission.class)); accessPermissions.add(Mockito.mock(AccessPermission.class)); - Assert.assertNull("Null expected.", loginInfoImpl.getAccessPermission()); - loginInfoImpl.setAccessPermission(accessPermissions); - Assert.assertEquals("Expected and actual values should be the same.", accessPermissions, loginInfoImpl.getAccessPermission()); + Assert.assertNull("Null expected.", loginInfo.getAccessPermission()); + loginInfo.setAccessPermission(accessPermissions); + Assert.assertEquals("Expected and actual values should be the same.", accessPermissions, loginInfo.getAccessPermission()); } @Test public void setAndGetAccessPermissionNullTest() { - Assert.assertNull("Null expected.", loginInfoImpl.getAccessPermission()); - loginInfoImpl.setAccessPermission(null); - Assert.assertNull("Null expected.", loginInfoImpl.getAccessPermission()); + Assert.assertNull("Null expected.", loginInfo.getAccessPermission()); + loginInfo.setAccessPermission(null); + Assert.assertNull("Null expected.", loginInfo.getAccessPermission()); } } \ No newline at end of file diff --git a/service/security/authentication/pom.xml b/service/security/authentication/pom.xml index ee0f23469ad..fd782adad5f 100644 --- a/service/security/authentication/pom.xml +++ b/service/security/authentication/pom.xml @@ -19,7 +19,7 @@ org.eclipse.kapua kapua-security - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT pom diff --git a/service/security/authorization/api/pom.xml b/service/security/authorization/api/pom.xml index a03de2ea37c..be074666293 100644 --- a/service/security/authorization/api/pom.xml +++ b/service/security/authorization/api/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-security-authorization - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-security-authorization-api diff --git a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessInfoCreator.java b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessInfoCreator.java index 4d6a82081cb..2c02a38ca02 100644 --- a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessInfoCreator.java +++ b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessInfoCreator.java @@ -12,12 +12,9 @@ *******************************************************************************/ package org.eclipse.kapua.service.authorization.access; -import org.eclipse.kapua.model.KapuaEntityCreator; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.model.id.KapuaIdAdapter; -import org.eclipse.kapua.service.authorization.domain.Domain; -import org.eclipse.kapua.service.authorization.permission.Permission; -import org.eclipse.kapua.service.user.User; +import java.security.Permissions; +import java.util.HashSet; +import java.util.Set; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; @@ -26,31 +23,63 @@ import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; -import java.security.Permissions; -import java.util.Set; + +import org.eclipse.kapua.model.KapuaEntityCreator; +import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.id.KapuaIdAdapter; +import org.eclipse.kapua.service.authorization.domain.Domain; +import org.eclipse.kapua.service.authorization.permission.Permission; +import org.eclipse.kapua.service.user.User; /** - * {@link AccessInfo} creator definition.
        - * It is used to assign a set of {@link Domain}s and {@link Permission}s to the referenced {@link User}.
        + * {@link AccessInfo} creator definition.
        It is used to assign a set of {@link Domain}s and {@link Permission}s to the referenced {@link User}.
        * * @since 1.0.0 */ @XmlRootElement -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(propOrder = {"userId", +@XmlAccessorType(XmlAccessType.PROPERTY) +@XmlType(propOrder = { "userId", "roleIds", - "permissions"}, - factoryClass = AccessInfoXmlRegistry.class, - factoryMethod = "newAccessInfoCreator") -public interface AccessInfoCreator extends KapuaEntityCreator { + "permissions" }) +public class AccessInfoCreator extends KapuaEntityCreator { + + private static final long serialVersionUID = 972154225756734130L; + + private KapuaId userId; + private Set roleIds; + private Set permissions; + + public AccessInfoCreator() { + } + + /** + * Constructor + * + * @param accessInfo + */ + @SuppressWarnings({ "rawtypes", "unchecked" }) + public AccessInfoCreator(AccessInfoCreator accessInfo) { + super((KapuaEntityCreator) accessInfo); + + setUserId(accessInfo.getUserId()); + setRoleIds(accessInfo.getRoleIds()); + setPermissions(accessInfo.getPermissions()); + } + + public AccessInfoCreator(KapuaId scopeId) { + super(scopeId); + } /** * Sets the user identifier. * - * @param userId The user id to set. + * @param userId + * The user id to set. * @since 1.0.0 */ - void setUserId(KapuaId userId); + public void setUserId(KapuaId userId) { + this.userId = userId; + } /** * Gets the user id. @@ -60,20 +89,23 @@ public interface AccessInfoCreator extends KapuaEntityCreator { */ @XmlElement(name = "userId") @XmlJavaTypeAdapter(KapuaIdAdapter.class) - KapuaId getUserId(); + public KapuaId getUserId() { + return userId; + } /** - * Sets the set of {@link Domain} ids to assign to the {@link AccessInfo} created entity. - * It up to the implementation class to make a clone of the set or use the given set. + * Sets the set of {@link Domain} ids to assign to the {@link AccessInfo} created entity. It up to the implementation class to make a clone of the set or use the given set. * - * @param roleIds The set of {@link Domain} ids. + * @param roleIds + * The set of {@link Domain} ids. * @since 1.0.0 */ - void setRoleIds(Set roleIds); + public void setRoleIds(Set roleIds) { + this.roleIds = roleIds; + } /** - * Gets the set of {@link Domain} ids added to this {@link AccessInfoCreator}. - * The implementation must return the reference of the set and not make a clone. + * Gets the set of {@link Domain} ids added to this {@link AccessInfoCreator}. The implementation must return the reference of the set and not make a clone. * * @return The set of {@link Domain} ids. * @since 1.0.0 @@ -81,26 +113,36 @@ public interface AccessInfoCreator extends KapuaEntityCreator { @XmlElementWrapper(name = "roleIds") @XmlElement(name = "roleId") @XmlJavaTypeAdapter(KapuaIdAdapter.class) - Set getRoleIds(); + public Set getRoleIds() { + if (roleIds == null) { + roleIds = new HashSet<>(); + } + return roleIds; + } /** - * Sets the set of {@link Permissions} to assign to the {@link AccessInfo} created entity. - * It up to the implementation class to make a clone of the set or use the given set. + * Sets the set of {@link Permissions} to assign to the {@link AccessInfo} created entity. It up to the implementation class to make a clone of the set or use the given set. * - * @param permissions The set of {@link Permissions}. + * @param permissions + * The set of {@link Permissions}. * @since 1.0.0 */ - void setPermissions(Set permissions); + public void setPermissions(Set permissions) { + this.permissions = permissions; + } /** - * Gets the set of {@link Permission} added to this {@link AccessInfoCreator}. - * The implementation must return the reference of the set and not make a clone. + * Gets the set of {@link Permission} added to this {@link AccessInfoCreator}. The implementation must return the reference of the set and not make a clone. * * @return The set of {@link Permission}. * @since 1.0.0 */ @XmlElementWrapper(name = "permissions") @XmlElement(name = "permission") -

        Set

        getPermissions(); - + public Set getPermissions() { + if (permissions == null) { + permissions = new HashSet<>(); + } + return permissions; + } } diff --git a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessInfoFactory.java b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessInfoFactory.java index 0e90817c47c..4ad03d82bd6 100644 --- a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessInfoFactory.java +++ b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessInfoFactory.java @@ -20,6 +20,6 @@ * @see org.eclipse.kapua.model.KapuaEntityFactory * @since 1.0.0 */ -public interface AccessInfoFactory extends KapuaEntityFactory { +public interface AccessInfoFactory extends KapuaEntityFactory { } diff --git a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessInfoListResult.java b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessInfoListResult.java index 386d15a601a..c9ffc9f7c3f 100644 --- a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessInfoListResult.java +++ b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessInfoListResult.java @@ -23,7 +23,9 @@ * @since 1.0.0 */ @XmlRootElement(name = "accessInfos") -@XmlType(factoryClass = AccessInfoXmlRegistry.class, factoryMethod = "newAccessInfoListResult") -public interface AccessInfoListResult extends KapuaListResult { +@XmlType +public class AccessInfoListResult extends KapuaListResult { + + static final long serialVersionUID = 2231053707705207563L; } diff --git a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessInfoQuery.java b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessInfoQuery.java deleted file mode 100644 index 29f9534835f..00000000000 --- a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessInfoQuery.java +++ /dev/null @@ -1,32 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authorization.access; - -import org.eclipse.kapua.model.query.KapuaQuery; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlType; - -/** - * {@link AccessInfo} {@link KapuaQuery} definition. - * - * @see KapuaQuery - * @since 1.0.0 - */ -@XmlRootElement(name = "query") -@XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = AccessInfoXmlRegistry.class, factoryMethod = "newQuery") -public interface AccessInfoQuery extends KapuaQuery { -} diff --git a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessInfoService.java b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessInfoService.java index 843726e13b3..3a647f61b15 100644 --- a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessInfoService.java +++ b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessInfoService.java @@ -26,10 +26,10 @@ public interface AccessInfoService extends KapuaEntityService { /** - * Creates a new {@link AccessInfo} entity.
        - * Is up to the implementation whether or not to check the existence of the referred {@link User} entity. + * Creates a new {@link AccessInfo} entity.
        Is up to the implementation whether or not to check the existence of the referred {@link User} entity. * - * @param accessInfoCreator The {@link AccessInfoCreator} form which create the {@link AccessInfo} + * @param accessInfoCreator + * The {@link AccessInfoCreator} form which create the {@link AccessInfo} * @return The created {@link AccessInfo} entity. * @throws KapuaException * @since 1.0.0 @@ -41,8 +41,10 @@ AccessInfo create(AccessInfoCreator accessInfoCreator) /** * Finds the {@link AccessInfo} by scope identifier and {@link AccessInfo} id. * - * @param scopeId The scope id in which to search. - * @param userId The {@link User} id to search. + * @param scopeId + * The scope id in which to search. + * @param userId + * The {@link User} id to search. * @return The {@link AccessInfo} found or {@code null} if no entity was found. * @throws KapuaException * @since 1.0.0 @@ -53,8 +55,10 @@ AccessInfo findByUserId(KapuaId scopeId, KapuaId userId) /** * Finds the {@link AccessInfo} by scope identifier and {@link User} id. * - * @param scopeId The scope id in which to search. - * @param accessInfoId The {@link AccessInfo} id to search. + * @param scopeId + * The scope id in which to search. + * @param accessInfoId + * The {@link AccessInfo} id to search. * @return The {@link AccessInfo} found or {@code null} if no entity was found. * @throws KapuaException * @since 1.0.0 @@ -66,7 +70,8 @@ AccessInfo find(KapuaId scopeId, KapuaId accessInfoId) /** * Returns the {@link AccessInfoListResult} with elements matching the provided query. * - * @param query The {@link AccessInfoQuery} used to filter results. + * @param query + * The {@link KapuaQuery} used to filter results. * @return The {@link AccessInfoListResult} with elements matching the query parameter. * @throws KapuaException * @since 1.0.0 @@ -78,7 +83,8 @@ AccessInfoListResult query(KapuaQuery query) /** * Returns the count of the {@link AccessInfo} elements matching the provided query. * - * @param query The {@link AccessInfoQuery} used to filter results. + * @param query + * The {@link KapuaQuery} used to filter results. * @return The count of the {@link AccessInfo} elements matching the provided query. * @throws KapuaException * @since 1.0.0 @@ -90,8 +96,10 @@ long count(KapuaQuery query) /** * Delete the {@link AccessInfo} by scope id and {@link AccessInfo} id. * - * @param scopeId The scope id in which to delete. - * @param accessInfoId The {@link AccessInfo} id to delete. + * @param scopeId + * The scope id in which to delete. + * @param accessInfoId + * The {@link AccessInfo} id to delete. * @throws KapuaException * @since 1.0.0 */ diff --git a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessInfoXmlRegistry.java b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessInfoXmlRegistry.java index f856ce81d65..6c111290e82 100644 --- a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessInfoXmlRegistry.java +++ b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessInfoXmlRegistry.java @@ -12,10 +12,10 @@ *******************************************************************************/ package org.eclipse.kapua.service.authorization.access; -import org.eclipse.kapua.locator.KapuaLocator; - import javax.xml.bind.annotation.XmlRegistry; +import org.eclipse.kapua.locator.KapuaLocator; + @XmlRegistry public class AccessInfoXmlRegistry { @@ -29,26 +29,4 @@ public class AccessInfoXmlRegistry { public AccessInfo newAccessInfo() { return accessInfoFactory.newEntity(null); } - - /** - * Creates a new access info creator instance - * - * @return - */ - public AccessInfoCreator newAccessInfoCreator() { - return accessInfoFactory.newCreator(null); - } - - /** - * Creates a new {@link AccessInfoListResult} instance - * - * @return - */ - public AccessInfoListResult newAccessInfoListResult() { - return accessInfoFactory.newListResult(); - } - - public AccessInfoQuery newQuery() { - return accessInfoFactory.newQuery(null); - } } diff --git a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessPermission.java b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessPermission.java index 4365a36f444..33f51bf59c7 100644 --- a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessPermission.java +++ b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessPermission.java @@ -12,11 +12,6 @@ *******************************************************************************/ package org.eclipse.kapua.service.authorization.access; -import org.eclipse.kapua.model.KapuaEntity; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.model.id.KapuaIdAdapter; -import org.eclipse.kapua.service.authorization.permission.Permission; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; @@ -24,20 +19,23 @@ import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; +import org.eclipse.kapua.model.KapuaEntity; +import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.id.KapuaIdAdapter; +import org.eclipse.kapua.service.authorization.permission.Permission; + /** - * Access permission entity.
        - * Describes a {@link Permission} associated to the access info.
        - * Wrapping of the {@link Permission} into this class is intended to adds auditing - * informations like {@link AccessPermission#getCreatedBy()} and{@link AccessPermission#getCreatedOn()}.
        + * Access permission entity.
        Describes a {@link Permission} associated to the access info.
        Wrapping of the {@link Permission} into this class is intended to adds auditing informations like + * {@link AccessPermission#getCreatedBy()} and{@link AccessPermission#getCreatedOn()}.
        *
        - * This is a not editable entity so it can be only removed or created and therefore any change to - * {@link AccessPermission#getAccessInfoId()} and {@link AccessPermission#getPermission()} property is forbidden. + * This is a not editable entity so it can be only removed or created and therefore any change to {@link AccessPermission#getAccessInfoId()} and {@link AccessPermission#getPermission()} property is + * forbidden. * * @since 1.0.0 */ @XmlRootElement(name = "accessPermission") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(propOrder = {"accessInfoId", "permission"}, // +@XmlType(propOrder = { "accessInfoId", "permission" }, // factoryClass = AccessPermissionXmlRegistry.class, // factoryMethod = "newAccessPermission") public interface AccessPermission extends KapuaEntity { @@ -52,7 +50,8 @@ default String getType() { /** * Sets the {@link AccessInfo} id of which this {@link AccessPermission} belongs. * - * @param accessId The {@link AccessInfo} id. + * @param accessId + * The {@link AccessInfo} id. * @since 1.0.0 */ void setAccessInfoId(KapuaId accessId); @@ -68,10 +67,10 @@ default String getType() { KapuaId getAccessInfoId(); /** - * Sets the {@link Permission} that this {@link AccessPermission} has.
        - * It up to the implementation class to make a clone of the given {@link Permission} or use the given {@link Permission}. + * Sets the {@link Permission} that this {@link AccessPermission} has.
        It up to the implementation class to make a clone of the given {@link Permission} or use the given {@link Permission}. * - * @param permission The {@link Permission} to set for this {@link AccessPermission}. + * @param permission + * The {@link Permission} to set for this {@link AccessPermission}. * @since 1.0.0 */ void setPermission(Permission permission); @@ -82,6 +81,6 @@ default String getType() { * @return The {@link Permission} that this {@link AccessPermission} has. */ @XmlElement(name = "permission") -

        P getPermission(); + Permission getPermission(); } diff --git a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessPermissionCreator.java b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessPermissionCreator.java index 96cfcf0356e..b0c60896ebc 100644 --- a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessPermissionCreator.java +++ b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessPermissionCreator.java @@ -12,11 +12,6 @@ *******************************************************************************/ package org.eclipse.kapua.service.authorization.access; -import org.eclipse.kapua.model.KapuaEntityCreator; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.model.id.KapuaIdAdapter; -import org.eclipse.kapua.service.authorization.permission.Permission; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; @@ -24,25 +19,43 @@ import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; +import org.eclipse.kapua.model.KapuaEntityCreator; +import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.id.KapuaIdAdapter; +import org.eclipse.kapua.service.authorization.permission.Permission; + /** - * {@link AccessPermission} creator definition.
        - * It is used to create a new {@link AccessPermission}. + * {@link AccessPermission} creator definition.
        It is used to create a new {@link AccessPermission}. * * @since 1.0.0 */ @XmlRootElement(name = "accessPermissionCreator") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(propOrder = {"accessInfoId", "permission"},// - factoryClass = AccessPermissionXmlRegistry.class, factoryMethod = "newCreator") -public interface AccessPermissionCreator extends KapuaEntityCreator { +@XmlType(propOrder = { "accessInfoId", "permission" }) +public class AccessPermissionCreator extends KapuaEntityCreator { + + private static final long serialVersionUID = 972154225756734130L; + + private KapuaId accessInfo; + private Permission permission; + + public AccessPermissionCreator() { + } + + public AccessPermissionCreator(KapuaId scopeId) { + super(scopeId); + } /** * Sets the {@link AccessInfo} id for this {@link AccessPermission}. * - * @param accessInfoId The {@link AccessInfo} id for this {@link AccessPermission}. + * @param accessInfoId + * The {@link AccessInfo} id for this {@link AccessPermission}. * @since 1.0.0 */ - void setAccessInfoId(KapuaId accessInfoId); + public void setAccessInfoId(KapuaId accessInfoId) { + this.accessInfo = accessInfoId; + } /** * Gets the {@link AccessInfo} id of this {@link AccessPermission}. @@ -52,16 +65,20 @@ public interface AccessPermissionCreator extends KapuaEntityCreator P getPermission(); + public Permission getPermission() { + return permission; + } } diff --git a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessPermissionFactory.java b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessPermissionFactory.java index 02f84fab518..77c6297bd1a 100644 --- a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessPermissionFactory.java +++ b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessPermissionFactory.java @@ -20,6 +20,6 @@ * @see org.eclipse.kapua.model.KapuaEntityFactory * @since 1.0.0 */ -public interface AccessPermissionFactory extends KapuaEntityFactory { +public interface AccessPermissionFactory extends KapuaEntityFactory { } diff --git a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessPermissionListResult.java b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessPermissionListResult.java index a2d61dabed3..2ab808b4973 100644 --- a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessPermissionListResult.java +++ b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessPermissionListResult.java @@ -23,7 +23,9 @@ * @since 1.0.0 */ @XmlRootElement(name = "accessPermissions") -@XmlType(factoryClass = AccessPermissionXmlRegistry.class, factoryMethod = "newAccessPermissionListResult") -public interface AccessPermissionListResult extends KapuaListResult { +@XmlType +public class AccessPermissionListResult extends KapuaListResult { + + private static final long serialVersionUID = -7673771564266332772L; } diff --git a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessPermissionQuery.java b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessPermissionQuery.java deleted file mode 100644 index 45bf90708e8..00000000000 --- a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessPermissionQuery.java +++ /dev/null @@ -1,32 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authorization.access; - -import org.eclipse.kapua.model.query.KapuaQuery; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlType; - -/** - * {@link AccessPermission} {@link KapuaQuery} definition. - * - * @see KapuaQuery - * @since 1.0.0 - */ -@XmlRootElement(name = "query") -@XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = AccessPermissionXmlRegistry.class, factoryMethod = "newQuery") -public interface AccessPermissionQuery extends KapuaQuery { -} diff --git a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessPermissionService.java b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessPermissionService.java index 8b41b1812e6..1d95f69f3e7 100644 --- a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessPermissionService.java +++ b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessPermissionService.java @@ -25,10 +25,10 @@ public interface AccessPermissionService extends KapuaEntityService { /** - * Creates a new {@link AccessPermission} based on the parameters provided in the {@link AccessPermissionCreator}.
        - * {@link AccessPermission} must have a unique name within the scope. + * Creates a new {@link AccessPermission} based on the parameters provided in the {@link AccessPermissionCreator}.
        {@link AccessPermission} must have a unique name within the scope. * - * @param accessPermissionCreator The creator object from which to create the {@link AccessPermission}. + * @param accessPermissionCreator + * The creator object from which to create the {@link AccessPermission}. * @throws KapuaException * @since 1.0.0 */ @@ -38,8 +38,10 @@ public interface AccessPermissionService extends KapuaEntityService - * It is used to create a new {@link AccessRole}. + * {@link AccessRole} creator definition.
        It is used to create a new {@link AccessRole}. * * @since 1.0.0 */ @XmlRootElement(name = "accessRoleCreator") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(propOrder = { "accessInfoId", "roleId" },// - factoryClass = AccessRoleXmlRegistry.class, factoryMethod = "newCreator") -public interface AccessRoleCreator extends KapuaEntityCreator { +@XmlType(propOrder = { "accessInfoId", "roleId" }) +public class AccessRoleCreator extends KapuaEntityCreator { + + private static final long serialVersionUID = 972154225756734130L; + + private KapuaId accessInfo; + private KapuaId roleId; + + public AccessRoleCreator() { + } + + /** + * Constructor + * + * @param scopeId + */ + public AccessRoleCreator(KapuaId scopeId) { + super(scopeId); + } /** * Sets the {@link AccessInfo} id for this {@link AccessRole}. * - * @param accessInfoId The {@link AccessInfo} id for this {@link AccessRole}. + * @param accessInfoId + * The {@link AccessInfo} id for this {@link AccessRole}. * @since 1.0.0 */ - void setAccessInfoId(KapuaId accessInfoId); + public void setAccessInfoId(KapuaId accessInfoId) { + this.accessInfo = accessInfoId; + } /** * Gets the {@link AccessInfo} id of this {@link AccessRole}. @@ -52,16 +70,20 @@ public interface AccessRoleCreator extends KapuaEntityCreator { */ @XmlElement(name = "accessInfoId") @XmlJavaTypeAdapter(KapuaIdAdapter.class) - KapuaId getAccessInfoId(); + public KapuaId getAccessInfoId() { + return accessInfo; + } /** - * Sets the {@link Role} id to assign to the {@link AccessRole} created entity. - * It up to the implementation class to make a clone of the object or use the given object. + * Sets the {@link Role} id to assign to the {@link AccessRole} created entity. It up to the implementation class to make a clone of the object or use the given object. * - * @param roleId The {@link Role} id + * @param roleId + * The {@link Role} id * @since 1.0.0 */ - void setRoleId(KapuaId roleId); + public void setRoleId(KapuaId roleId) { + this.roleId = roleId; + } /** * Gets the {@link Role} id added to this {@link AccessRole}. @@ -71,5 +93,7 @@ public interface AccessRoleCreator extends KapuaEntityCreator { */ @XmlElement(name = "roleId") @XmlJavaTypeAdapter(KapuaIdAdapter.class) - KapuaId getRoleId(); + public KapuaId getRoleId() { + return roleId; + } } diff --git a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessRoleFactory.java b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessRoleFactory.java index f4e158d1310..2d53af95d47 100644 --- a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessRoleFactory.java +++ b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessRoleFactory.java @@ -20,6 +20,6 @@ * @see org.eclipse.kapua.model.KapuaEntityFactory * @since 1.0.0 */ -public interface AccessRoleFactory extends KapuaEntityFactory { +public interface AccessRoleFactory extends KapuaEntityFactory { } diff --git a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessRoleListResult.java b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessRoleListResult.java index 5a54983a4c8..7cb32c9f004 100644 --- a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessRoleListResult.java +++ b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessRoleListResult.java @@ -23,7 +23,9 @@ * @since 1.0.0 */ @XmlRootElement(name = "accessPermissions") -@XmlType(factoryClass = AccessRoleXmlRegistry.class, factoryMethod = "newAccessRoleListResult") -public interface AccessRoleListResult extends KapuaListResult { +@XmlType +public class AccessRoleListResult extends KapuaListResult { + + private static final long serialVersionUID = 2406073775830391702L; } diff --git a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessRoleQuery.java b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessRoleQuery.java deleted file mode 100644 index 5f0276e686d..00000000000 --- a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessRoleQuery.java +++ /dev/null @@ -1,32 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authorization.access; - -import org.eclipse.kapua.model.query.KapuaQuery; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlType; - -/** - * {@link AccessRole} {@link KapuaQuery} definition. - * - * @see KapuaQuery - * @since 1.0.0 - */ -@XmlRootElement(name = "query") -@XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = AccessRoleXmlRegistry.class, factoryMethod = "newQuery") -public interface AccessRoleQuery extends KapuaQuery { -} diff --git a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessRoleService.java b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessRoleService.java index 25225c4b97a..0316fceee6b 100644 --- a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessRoleService.java +++ b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/access/AccessRoleService.java @@ -25,10 +25,10 @@ public interface AccessRoleService extends KapuaEntityService { /** - * Creates a new {@link AccessRole} based on the parameters provided in the {@link AccessRoleCreator}.
        - * {@link AccessRole} must have a unique name within the scope. + * Creates a new {@link AccessRole} based on the parameters provided in the {@link AccessRoleCreator}.
        {@link AccessRole} must have a unique name within the scope. * - * @param accessRoleCreator The creator object from which to create the {@link AccessRole}. + * @param accessRoleCreator + * The creator object from which to create the {@link AccessRole}. * @throws KapuaException * @since 1.0.0 */ @@ -38,8 +38,10 @@ public interface AccessRoleService extends KapuaEntityService @@ -30,49 +32,100 @@ */ @XmlRootElement(name = "domainCreator") @XmlAccessorType(XmlAccessType.PROPERTY) -public interface DomainCreator extends KapuaEntityCreator { // org.eclipse.kapua.model.domain.Domain { +public class DomainCreator extends KapuaEntityCreator { // org.eclipse.kapua.model.domain.Domain { + + private static final long serialVersionUID = -4676187845961673421L; - String getName(); + private String name; - String getServiceName(); + private String serviceName; + private Set actions; + private boolean groupable; - Set getActions(); + public DomainCreator() { + } - boolean getGroupable(); + public DomainCreator(KapuaId scopeId, String name) { + super(scopeId); + this.name = name; + } + + public DomainCreator(KapuaId scopeId) { + super(scopeId); + } + + /** + * Constructor + * + * @param name + * The name to set for this {@link DomainCreator}. + * @since 1.0.0 + */ + public DomainCreator(String name) { + this.name = name; + } + + public String getServiceName() { + return serviceName; + } + + public Set getActions() { + return actions; + } + + public boolean getGroupable() { + return groupable; + } /** * Sets the {@link Domain} name. * - * @param name The {@link Domain} name. + * @param name + * The {@link Domain} name. * @since 1.0.0 */ - void setName(String name); + public void setName(String name) { + this.name = name; + } + + public String getName() { + return name; + } /** * Sets the {@link Domain} service name. * - * @param serviceName The {@link Domain} name. + * @param serviceName + * The {@link Domain} name. * @since 1.0.0 */ - void setServiceName(String serviceName); + public void setServiceName(String serviceName) { + this.serviceName = serviceName; + } /** - * Sets the set of {@link Actions} available in the {@link Domain}.
        - * It up to the implementation class to make a clone of the set or use the given set. + * Sets the set of {@link Actions} available in the {@link Domain}.
        It up to the implementation class to make a clone of the set or use the given set. * - * @param actions The set of {@link Actions}. + * @param actions + * The set of {@link Actions}. * @since 1.0.0 */ - void setActions(Set actions); + public void setActions(Set actions) { + this.actions = actions; + } /** - * Sets whether or not this {@link Domain} is group-able or not. - * This determines if the {@link org.eclipse.kapua.service.authorization.permission.Permission} in this {@link Domain} can have a {@link org.eclipse.kapua.service.authorization.group.Group} or not. - * This is related to the {@link org.eclipse.kapua.service.authorization.group.Groupable} property of a {@link KapuaEntityCreator}. + * Sets whether or not this {@link Domain} is group-able or not. This determines if the {@link org.eclipse.kapua.service.authorization.permission.Permission} in this {@link Domain} can have a + * {@link org.eclipse.kapua.service.authorization.group.Group} or not. This is related to the {@link org.eclipse.kapua.service.authorization.group.Groupable} property of a + * {@link KapuaEntityCreator}. * - * @param groupable {@code true} if the {@link org.eclipse.kapua.service.authorization.permission.Permission} on this {@link Domain} can have the {@link Permission#getGroupId()} property set, {@code false} otherwise. + * @param groupable + * {@code true} if the {@link org.eclipse.kapua.service.authorization.permission.Permission} on this {@link Domain} can have the {@link Permission#getGroupId()} property set, {@code false} + * otherwise. * @since 0.3.1 */ - void setGroupable(boolean groupable); + public void setGroupable(boolean groupable) { + this.groupable = groupable; + } } diff --git a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/domain/DomainFactory.java b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/domain/DomainFactory.java index faed82b4ee8..7dfbc936a28 100644 --- a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/domain/DomainFactory.java +++ b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/domain/DomainFactory.java @@ -20,15 +20,6 @@ * @see org.eclipse.kapua.model.KapuaEntityFactory * @since 1.0.0 */ -public interface DomainFactory extends KapuaEntityFactory { - - /** - * Instantiates a new {@link DomainCreator} - * - * @param name The name to set into the {@link Domain}. - * @return The newly instantiated {@link Domain}. - * @since 1.0.0 - */ - DomainCreator newCreator(String name); +public interface DomainFactory extends KapuaEntityFactory { } diff --git a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/domain/DomainListResult.java b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/domain/DomainListResult.java index c38cffc1a20..7426fe39b02 100644 --- a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/domain/DomainListResult.java +++ b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/domain/DomainListResult.java @@ -22,6 +22,8 @@ * @since 1.0.0 */ @XmlRootElement(name = "domains") -public interface DomainListResult extends KapuaListResult { +public class DomainListResult extends KapuaListResult { + + private static final long serialVersionUID = -5086830452591857912L; } diff --git a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/domain/DomainQuery.java b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/domain/DomainQuery.java deleted file mode 100644 index fd3361f781f..00000000000 --- a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/domain/DomainQuery.java +++ /dev/null @@ -1,32 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authorization.domain; - -import org.eclipse.kapua.model.query.KapuaQuery; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlType; - -/** - * {@link Domain} {@link KapuaQuery} definition. - * - * @see KapuaQuery - * @since 1.0.0 - */ -@XmlRootElement(name = "query") -@XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = DomainXmlRegistry.class, factoryMethod = "newQuery") -public interface DomainQuery extends KapuaQuery { -} diff --git a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/domain/DomainRegistryService.java b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/domain/DomainRegistryService.java index d67abb8eca5..86c77483b21 100644 --- a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/domain/DomainRegistryService.java +++ b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/domain/DomainRegistryService.java @@ -25,12 +25,13 @@ public interface DomainRegistryService extends KapuaEntityService { /** - * Creates a new {@link Domain} based on the parameters provided in the {@link DomainCreator}.
        - * {@link Domain} must have a unique name. + * Creates a new {@link Domain} based on the parameters provided in the {@link DomainCreator}.
        {@link Domain} must have a unique name. * - * @param domainCreator The creator object from which to create the {@link Domain}. + * @param domainCreator + * The creator object from which to create the {@link Domain}. * @return The created {@link Domain} - * @throws KapuaException When there is an oeror22 + * @throws KapuaException + * When there is an oeror22 * @since 1.0.0 */ @Override @@ -39,8 +40,10 @@ public interface DomainRegistryService extends KapuaEntityService @@ -28,6 +29,19 @@ */ @XmlRootElement(name = "groupCreator") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = GroupXmlRegistry.class, factoryMethod = "newGroupCreator") -public interface GroupCreator extends KapuaNamedEntityCreator { +@XmlType +public class GroupCreator extends KapuaNamedEntityCreator { + + private static final long serialVersionUID = -4676187845961673421L; + + public GroupCreator() { + } + + public GroupCreator(KapuaId scopeId) { + super(scopeId); + } + + public GroupCreator(KapuaId scopeId, String name) { + super(scopeId, name); + } } diff --git a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/group/GroupFactory.java b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/group/GroupFactory.java index 01d084daf4a..560e3c39a79 100644 --- a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/group/GroupFactory.java +++ b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/group/GroupFactory.java @@ -13,7 +13,6 @@ package org.eclipse.kapua.service.authorization.group; import org.eclipse.kapua.model.KapuaEntityFactory; -import org.eclipse.kapua.model.id.KapuaId; /** * {@link GroupFactory} definition. @@ -21,16 +20,6 @@ * @see org.eclipse.kapua.model.KapuaEntityFactory * @since 1.0.0 */ -public interface GroupFactory extends KapuaEntityFactory { - - /** - * Instantiates a new {@link GroupCreator}. - * - * @param scopeId The scope {@link KapuaId} to set into the {@link GroupCreator} - * @param name The name to set into the {@link GroupCreator} - * @return The newly instantatied {@link GroupCreator} - * @since 1.0.0 - */ - GroupCreator newCreator(KapuaId scopeId, String name); +public interface GroupFactory extends KapuaEntityFactory { } diff --git a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/group/GroupListResult.java b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/group/GroupListResult.java index 024c5c0baa1..f41dbc3cbce 100644 --- a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/group/GroupListResult.java +++ b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/group/GroupListResult.java @@ -23,7 +23,9 @@ * @since 1.0.0 */ @XmlRootElement(name = "groups") -@XmlType(factoryClass = GroupXmlRegistry.class, factoryMethod = "newGroupListResult") -public interface GroupListResult extends KapuaListResult { +@XmlType +public class GroupListResult extends KapuaListResult { + + private static final long serialVersionUID = 791258978210911362L; } diff --git a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/group/GroupMatchPredicate.java b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/group/GroupMatchPredicate.java index 23afb4f1acc..4b9c6f39761 100644 --- a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/group/GroupMatchPredicate.java +++ b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/group/GroupMatchPredicate.java @@ -12,8 +12,24 @@ *******************************************************************************/ package org.eclipse.kapua.service.authorization.group; -import org.eclipse.kapua.model.query.predicate.MatchPredicate; +import java.util.Arrays; -public interface GroupMatchPredicate extends MatchPredicate { +import org.eclipse.kapua.model.query.predicate.AbstractMatchPredicate; + +public class GroupMatchPredicate extends AbstractMatchPredicate { + + /** + * Constructor. + * + * @param matchTerm + * @since 2.1.0 + */ + public GroupMatchPredicate(T matchTerm) { + this.attributeNames = Arrays.asList( + GroupAttributes.DESCRIPTION, + GroupAttributes.NAME + ); + this.matchTerm = matchTerm; + } } diff --git a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/group/GroupQuery.java b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/group/GroupQuery.java index 94b9a53d183..be23ba6290a 100644 --- a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/group/GroupQuery.java +++ b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/group/GroupQuery.java @@ -12,13 +12,14 @@ *******************************************************************************/ package org.eclipse.kapua.service.authorization.group; -import org.eclipse.kapua.model.query.KapuaQuery; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; +import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.query.KapuaQuery; + /** * {@link Group} {@link KapuaQuery} definition. * @@ -27,15 +28,34 @@ */ @XmlRootElement(name = "query") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = GroupXmlRegistry.class, factoryMethod = "newQuery") -public interface GroupQuery extends KapuaQuery { +@XmlType +public class GroupQuery extends KapuaQuery { + + public GroupQuery() { + } + + /** + * Constructor. + * + * @param scopeId + * The {@link #getScopeId()}. + * @since 1.0.0 + */ + public GroupQuery(KapuaId scopeId) { + super(scopeId); + } + /** * Instantiates a new {@link GroupMatchPredicate}. * - * @param matchTerm The term to use to match. - * @param The type of the term + * @param matchTerm + * The term to use to match. + * @param + * The type of the term * @return The newly instantiated {@link GroupMatchPredicate}. * @since 2.1.0 */ - GroupMatchPredicate matchPredicate(T matchTerm); + public GroupMatchPredicate matchPredicate(T matchTerm) { + return new GroupMatchPredicate<>(matchTerm); + } } diff --git a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/group/GroupXmlRegistry.java b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/group/GroupXmlRegistry.java index 31f777e9ca4..dc14bd45e82 100644 --- a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/group/GroupXmlRegistry.java +++ b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/group/GroupXmlRegistry.java @@ -12,10 +12,10 @@ *******************************************************************************/ package org.eclipse.kapua.service.authorization.group; -import org.eclipse.kapua.locator.KapuaLocator; - import javax.xml.bind.annotation.XmlRegistry; +import org.eclipse.kapua.locator.KapuaLocator; + @XmlRegistry public class GroupXmlRegistry { @@ -30,34 +30,4 @@ public class GroupXmlRegistry { public Group newGroup() { return groupFactory.newEntity(null); } - - /** - * Creates a new {@link GroupCreator} instance. - * - * @return The newly created {@link GroupCreator} instance. - * @since 1.0.0 - */ - public GroupCreator newGroupCreator() { - return groupFactory.newCreator(null, null); - } - - /** - * Creates a new {@link GroupListResult} instance. - * - * @return The newly created {@link GroupListResult} instance. - * @since 1.0.0 - */ - public GroupListResult newGroupListResult() { - return groupFactory.newListResult(); - } - - /** - * Creates a new {@link GroupQuery} instance. - * - * @return The newly created {@link GroupQuery} instance. - * @since 1.0.0 - */ - public GroupQuery newQuery() { - return groupFactory.newQuery(null); - } } diff --git a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/permission/Permission.java b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/permission/Permission.java index f9008803450..c247488c585 100644 --- a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/permission/Permission.java +++ b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/permission/Permission.java @@ -12,12 +12,9 @@ *******************************************************************************/ package org.eclipse.kapua.service.authorization.permission; -import org.eclipse.kapua.model.domain.Actions; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.model.id.KapuaIdAdapter; -import org.eclipse.kapua.service.authorization.access.AccessInfo; -import org.eclipse.kapua.service.authorization.domain.Domain; -import org.eclipse.kapua.service.authorization.group.Group; +import java.util.Arrays; +import java.util.Collection; +import java.util.stream.Collectors; import javax.security.auth.Subject; import javax.xml.bind.annotation.XmlAccessType; @@ -27,10 +24,16 @@ import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; +import org.eclipse.kapua.model.domain.Actions; +import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.id.KapuaIdAdapter; +import org.eclipse.kapua.service.authorization.access.AccessInfo; +import org.eclipse.kapua.service.authorization.domain.Domain; +import org.eclipse.kapua.service.authorization.group.Group; + /** - * {@link Permission} definition.
        - * A permission can be associated to a {@link Subject} (using {@link AccessInfo} entity) or a {@link Domain}.
        - * {@link Permission}s enable the assignee to do {@link Actions} under specified {@link Domain} and in specified scopes. + * {@link Permission} definition.
        A permission can be associated to a {@link Subject} (using {@link AccessInfo} entity) or a {@link Domain}.
        {@link Permission}s enable the assignee to do + * {@link Actions} under specified {@link Domain} and in specified scopes. * * @since 1.0.0 */ @@ -42,21 +45,50 @@ "targetScopeId", // "groupId", // "forwardable" // -}, // - factoryClass = PermissionXmlRegistry.class, // - factoryMethod = "newPermission") -public interface Permission { +}, factoryMethod = "newPermission") +public class Permission { - String WILDCARD = "*"; - String SEPARATOR = ":"; + public static final String WILDCARD = "*"; + public static final String SEPARATOR = ":"; + @XmlElement(name = "domain") + private final String domain; + @XmlElement(name = "action") + private final Actions action; + @XmlElement(name = "targetScopeId") + @XmlJavaTypeAdapter(KapuaIdAdapter.class) + private final KapuaId targetScopeId; + @XmlElement(name = "groupId") + @XmlJavaTypeAdapter(KapuaIdAdapter.class) + private final KapuaId groupId; + @XmlElement(name = "forwardable") + private final boolean forwardable; - /** - * Sets the domain on which the {@link Permission} gives access. - * - * @param domain The domain of the {@link Permission}. - * @since 1.0.0 - */ - void setDomain(String domain); + // For you, JAXB + private static Permission newPermission() { + return new Permission(null, null, null); + } + + public Permission(String domain, Actions action, KapuaId targetScopeId) { + this(domain, action, targetScopeId, null, false); + } + + public Permission(String domain, Actions action, KapuaId targetScopeId, KapuaId groupId) { + this(domain, action, targetScopeId, groupId, false); + } + + public Permission(String domain, Actions action, KapuaId targetScopeId, KapuaId groupId, boolean forwardable) { + this.domain = domain; + this.action = action; + this.targetScopeId = targetScopeId; + this.groupId = groupId; + this.forwardable = forwardable; + } + + public static Collection newPermissions(String domain, KapuaId targetScopeId, Actions... actions) { + return Arrays.stream(actions) + .map(action -> new Permission(domain, action, targetScopeId, null, false)) + .collect(Collectors.toList()); + } /** * Gets the domain on which the {@link Permission} gives access. @@ -64,16 +96,9 @@ public interface Permission { * @return The domain on which the {@link Permission} gives access. * @since 1.0.0 */ - @XmlElement(name = "domain") - String getDomain(); - - /** - * Sets the {@link org.eclipse.kapua.model.domain.Actions} that this {@link Permission} allows to do on the domain. - * - * @param action The {@link javax.swing.Action} that this {@link Permission} allows - * @since 1.0.0 - */ - void setAction(Actions action); + public String getDomain() { + return this.domain; + } /** * Gets the {@link Actions} that this {@link Permission} allows to do on the domain. @@ -81,16 +106,9 @@ public interface Permission { * @return The {@link Actions} that this {@link Permission} allows. * @since 1.0.0 */ - @XmlElement(name = "action") - Actions getAction(); - - /** - * Sets the target scope id that this {@link Permission} gives access. - * - * @param targetScopeId The target scope id that this {@link Permission} gives access. - * @since 1.0.0 - */ - void setTargetScopeId(KapuaId targetScopeId); + public Actions getAction() { + return this.action; + } /** * Gets the target scope id that this {@link Permission} gives access. @@ -98,17 +116,10 @@ public interface Permission { * @return The target scope id that this {@link Permission} gives access. * @since 1.0.0 */ - @XmlElement(name = "targetScopeId") - @XmlJavaTypeAdapter(KapuaIdAdapter.class) - KapuaId getTargetScopeId(); - /** - * Sets the {@link Group} id that this {@link Permission} gives access. - * - * @param groupId The {@link Group} id that this {@link Permission} gives access. - * @since 1.0.0 - */ - void setGroupId(KapuaId groupId); + public KapuaId getTargetScopeId() { + return this.targetScopeId; + } /** * Gets the {@link Group} id that this {@link Permission} gives access. @@ -116,26 +127,81 @@ public interface Permission { * @return The {@link Group} id that this {@link Permission} gives access. * @since 1.0.0 */ - @XmlElement(name = "groupId") - @XmlJavaTypeAdapter(KapuaIdAdapter.class) - KapuaId getGroupId(); - /** - * Sets whether or not this {@link Permission} is valid also for children scopeId. - * - * @param forwardable {@code true} if this {@link Permission} is forward-able to children scopeIds. - * @since 1.0.0 - */ - void setForwardable(boolean forwardable); + public KapuaId getGroupId() { + return this.groupId; + } /** - * Gets whether or not this {@link Permission} is valid also for children scopeIds. - * If a {@link Permission} is forward-able to children, the {@link Permission} will be valid - * for all scopeIds of the {@link #getTargetScopeId()} scopeId. + * Gets whether or not this {@link Permission} is valid also for children scopeIds. If a {@link Permission} is forward-able to children, the {@link Permission} will be valid for all scopeIds of + * the {@link #getTargetScopeId()} scopeId. * * @return {@code true} if this {@link Permission} is forward-able to children scopeIds. * @since 1.0.0 */ - @XmlElement(name = "forwardable") - boolean getForwardable(); + public boolean getForwardable() { + return this.forwardable; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + + sb.append(domain != null ? domain : Permission.WILDCARD) + .append(Permission.SEPARATOR) + .append(action != null ? action.name() : Permission.WILDCARD) + .append(Permission.SEPARATOR) + .append(targetScopeId != null ? targetScopeId.getId() : Permission.WILDCARD) + .append(Permission.SEPARATOR) + .append(groupId != null ? groupId.getId() : Permission.WILDCARD); + + return sb.toString(); + } + + @Override + public int hashCode() { + int prime = 31; + int result = 1; + result = prime * result + (action == null ? 0 : action.hashCode()); + result = prime * result + (domain == null ? 0 : domain.hashCode()); + result = prime * result + (targetScopeId == null ? 0 : targetScopeId.hashCode()); + result = prime * result + (groupId == null ? 0 : groupId.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + Permission other = (Permission) obj; + if (action != other.action) { + return false; + } + if (domain == null) { + if (other.domain != null) { + return false; + } + } else if (!domain.equals(other.domain)) { + return false; + } + if (targetScopeId == null) { + if (other.targetScopeId != null) { + return false; + } + } else if (!targetScopeId.equals(other.targetScopeId)) { + return false; + } + if (groupId == null) { + return other.groupId == null; + } else { + return groupId.equals(other.groupId); + } + } } diff --git a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/permission/PermissionFactory.java b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/permission/PermissionFactory.java deleted file mode 100644 index 0b2a2236501..00000000000 --- a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/permission/PermissionFactory.java +++ /dev/null @@ -1,108 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - * Red Hat Inc - *******************************************************************************/ -package org.eclipse.kapua.service.authorization.permission; - -import org.eclipse.kapua.model.KapuaObjectFactory; -import org.eclipse.kapua.model.domain.Actions; -import org.eclipse.kapua.model.domain.Domain; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.authorization.group.Group; - -import java.util.Arrays; -import java.util.Collection; -import java.util.stream.Collectors; - -/** - * {@link Permission} object factory. - */ -public interface PermissionFactory extends KapuaObjectFactory { - - /** - * Instantiate a new {@link Permission} implementing object with the provided parameters. - * - * @param domain The {@link Domain} of the new {@link Permission}. - * @param action The {@link Actions} of the new {@link Permission}. - * @param targetScopeId The target scope id of the new {@link Permission}. - * @return A instance of the implementing class of {@link Permission}. - */ - default Permission newPermission(String domain, Actions action, KapuaId targetScopeId) { - return newPermission(domain, action, targetScopeId, null); - } - - /** - * Instantiate a new {@link Permission} implementing object with the provided parameters. - * - * @param domain The {@link Domain} of the new {@link Permission}. - * @param action The {@link Actions} of the new {@link Permission}. - * @param targetScopeId The target scope id of the new {@link Permission}. - * @param groupId The {@link Group} id that this {@link Permission} gives access. - * @return A instance of the implementing class of {@link Permission}. - */ - default Permission newPermission(String domain, Actions action, KapuaId targetScopeId, KapuaId groupId) { - return newPermission(domain, action, targetScopeId, groupId, false); - } - - /** - * Instantiate a new {@link Permission} implementing object with the provided parameters. - * - * @param domain The {@link Domain} of the new {@link Permission}. - * @param action The {@link Actions} of the new {@link Permission}. - * @param targetScopeId The target scope id of the new {@link Permission}. - * @param groupId The {@link Group} id that this {@link Permission} gives access. - * @param forwardable If the {@link Permission} is forward-able to children scopeIds - * @return A instance of the implementing class of {@link Permission}. - */ - Permission newPermission(String domain, Actions action, KapuaId targetScopeId, KapuaId groupId, boolean forwardable); - - /** - * Instantiate new {@link Permission}s implementing object with the provided parameters. - * - * @param domain The {@link Domain} of the new {@link Permission}. - * @param targetScopeId The target scope id of the new {@link Permission}. - * @param actions The {@link Actions} of the new {@link Permission}s. - * @return A collection of instances of the implementing class of {@link Permission}. - */ - default Collection newPermissions(String domain, KapuaId targetScopeId, Actions... actions) { - return newPermissions(domain, targetScopeId, null, actions); - } - - /** - * Instantiate new {@link Permission}s implementing object with the provided parameters. - * - * @param domain The {@link Domain} of the new {@link Permission}. - * @param targetScopeId The target scope id of the new {@link Permission}. - * @param groupId The {@link Group} id that this {@link Permission} gives access. - * @param actions The {@link Actions} of the new {@link Permission}s. - * @return A collection of instances of the implementing class of {@link Permission}. - */ - default Collection newPermissions(String domain, KapuaId targetScopeId, KapuaId groupId, Actions... actions) { - return newPermissions(domain, targetScopeId, groupId, false, actions); - } - - /** - * Instantiate new {@link Permission}s implementing object with the provided parameters. - * - * @param domain The {@link Domain} of the new {@link Permission}. - * @param targetScopeId The target scope id of the new {@link Permission}. - * @param groupId The {@link Group} id that this {@link Permission} gives access. - * @param forwardable If the {@link Permission} is forward-auble to children scopeIds - * @param actions The {@link Actions} of the new {@link Permission}s. - * @return A collection of instances of the implementing class of {@link Permission}. - */ - default Collection newPermissions(String domain, KapuaId targetScopeId, KapuaId groupId, boolean forwardable, Actions... actions) { - return Arrays.stream(actions) - .map(action -> newPermission(domain, action, targetScopeId, groupId, forwardable)) - .collect(Collectors.toList()); - } -} diff --git a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/permission/PermissionXmlRegistry.java b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/permission/PermissionXmlRegistry.java deleted file mode 100644 index 91b9a30a054..00000000000 --- a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/permission/PermissionXmlRegistry.java +++ /dev/null @@ -1,33 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authorization.permission; - -import org.eclipse.kapua.locator.KapuaLocator; - -import javax.xml.bind.annotation.XmlRegistry; - -@XmlRegistry -public class PermissionXmlRegistry { - - private final PermissionFactory permissionFactory = KapuaLocator.getInstance().getFactory(PermissionFactory.class); - - /** - * Creates a new {@link Permission} instance - * - * @return A new {@link Permission} instance - * @since 1.0.0 - */ - public Permission newPermission() { - return permissionFactory.newPermission(null, null, null, null); - } -} diff --git a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/role/RoleCreator.java b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/role/RoleCreator.java index 0752ae89ad8..1c3f8da7880 100644 --- a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/role/RoleCreator.java +++ b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/role/RoleCreator.java @@ -12,8 +12,9 @@ *******************************************************************************/ package org.eclipse.kapua.service.authorization.role; -import org.eclipse.kapua.model.KapuaNamedEntityCreator; -import org.eclipse.kapua.service.authorization.permission.Permission; +import java.security.Permissions; +import java.util.HashSet; +import java.util.Set; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; @@ -21,8 +22,10 @@ import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; -import java.security.Permissions; -import java.util.Set; + +import org.eclipse.kapua.model.KapuaNamedEntityCreator; +import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.service.authorization.permission.Permission; /** * {@link RoleCreator} definition. @@ -33,27 +36,44 @@ */ @XmlRootElement(name = "roleCreator") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = RoleXmlRegistry.class, factoryMethod = "newRoleCreator") -public interface RoleCreator extends KapuaNamedEntityCreator { +@XmlType +public class RoleCreator extends KapuaNamedEntityCreator { + + private static final long serialVersionUID = 972154225756734130L; + + private Set permissions; + + public RoleCreator() { + + } + + public RoleCreator(KapuaId scopeId) { + super(scopeId); + } /** - * Sets the set of {@link Permissions} to assign to the {@link Role} created entity. - * It up to the implementation class to make a clone of the set or use the given set. + * Sets the set of {@link Permissions} to assign to the {@link Role} created entity. It up to the implementation class to make a clone of the set or use the given set. * - * @param permissions The set of {@link Permissions}. + * @param permissions + * The set of {@link Permissions}. * @since 1.0.0 */ - void setPermissions(Set permissions); + public void setPermissions(Set permissions) { + this.permissions = permissions; + } /** - * Gets the set of {@link Permission} added to this {@link Role}. - * The implementation must return the reference of the set and not make a clone. + * Gets the set of {@link Permission} added to this {@link Role}. The implementation must return the reference of the set and not make a clone. * - * @param

        The {@link Permission} class implementation. * @return The set of {@link Permission}. * @since 1.0.0 */ @XmlElementWrapper(name = "permissions") @XmlElement(name = "permission") -

        Set

        getPermissions(); + public Set getPermissions() { + if (permissions == null) { + permissions = new HashSet<>(); + } + return permissions; + } } diff --git a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/role/RoleFactory.java b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/role/RoleFactory.java index 209b342c0b6..cec18c32d22 100644 --- a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/role/RoleFactory.java +++ b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/role/RoleFactory.java @@ -20,7 +20,7 @@ * @see org.eclipse.kapua.model.KapuaEntityFactory * @since 1.0.0 */ -public interface RoleFactory extends KapuaEntityFactory { +public interface RoleFactory extends KapuaEntityFactory { /** * Instantiates a new {@link RolePermission}. diff --git a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/role/RoleListResult.java b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/role/RoleListResult.java index 94027eff5cd..0b942bb4f05 100644 --- a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/role/RoleListResult.java +++ b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/role/RoleListResult.java @@ -23,7 +23,9 @@ * @since 1.0.0 */ @XmlRootElement(name = "roles") -@XmlType(factoryClass = RoleXmlRegistry.class, factoryMethod = "newRoleListResult") -public interface RoleListResult extends KapuaListResult { +@XmlType +public class RoleListResult extends KapuaListResult { + + private static final long serialVersionUID = -5902522234186399802L; } diff --git a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/role/RoleMatchPredicate.java b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/role/RoleMatchPredicate.java index 5f1e7edbfc6..f7b00050624 100644 --- a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/role/RoleMatchPredicate.java +++ b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/role/RoleMatchPredicate.java @@ -12,8 +12,23 @@ *******************************************************************************/ package org.eclipse.kapua.service.authorization.role; -import org.eclipse.kapua.model.query.predicate.MatchPredicate; +import java.util.Arrays; -public interface RoleMatchPredicate extends MatchPredicate { +import org.eclipse.kapua.model.query.predicate.AbstractMatchPredicate; +public class RoleMatchPredicate extends AbstractMatchPredicate { + + /** + * Constructor. + * + * @param matchTerm + * @since 2.1.0 + */ + public RoleMatchPredicate(T matchTerm) { + this.attributeNames = Arrays.asList( + RoleAttributes.DESCRIPTION, + RoleAttributes.NAME + ); + this.matchTerm = matchTerm; + } } diff --git a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/role/RolePermissionCreator.java b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/role/RolePermissionCreator.java index d503e0f231d..7a30643bca4 100644 --- a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/role/RolePermissionCreator.java +++ b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/role/RolePermissionCreator.java @@ -12,11 +12,6 @@ *******************************************************************************/ package org.eclipse.kapua.service.authorization.role; -import org.eclipse.kapua.model.KapuaEntityCreator; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.model.id.KapuaIdAdapter; -import org.eclipse.kapua.service.authorization.permission.Permission; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; @@ -24,25 +19,43 @@ import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; +import org.eclipse.kapua.model.KapuaEntityCreator; +import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.id.KapuaIdAdapter; +import org.eclipse.kapua.service.authorization.permission.Permission; + /** - * {@link RolePermission} creator definition.
        - * It is used to create a new {@link RolePermission}. + * {@link RolePermission} creator definition.
        It is used to create a new {@link RolePermission}. * * @since 1.0.0 */ @XmlRootElement(name = "rolePermissionCreator") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(propOrder = {"roleId", "permission"},// - factoryClass = RolePermissionXmlRegistry.class, factoryMethod = "newCreator") -public interface RolePermissionCreator extends KapuaEntityCreator { +@XmlType(propOrder = { "roleId", "permission" }) +public class RolePermissionCreator extends KapuaEntityCreator { + + private static final long serialVersionUID = 972154225756734130L; + + private KapuaId roleId; + private Permission permission; + + public RolePermissionCreator() { + } + + public RolePermissionCreator(KapuaId scopeId) { + super(scopeId); + } /** * Sets the {@link Role} id for this {@link RolePermission}. * - * @param roleId The {@link Role} id for this {@link RolePermission}. + * @param roleId + * The {@link Role} id for this {@link RolePermission}. * @since 1.0.0 */ - void setRoleId(KapuaId roleId); + public void setRoleId(KapuaId roleId) { + this.roleId = roleId; + } /** * Gets the {@link Role} id of this {@link RolePermission}. @@ -52,16 +65,20 @@ public interface RolePermissionCreator extends KapuaEntityCreator P getPermission(); + public Permission getPermission() { + return permission; + } } diff --git a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/role/RolePermissionFactory.java b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/role/RolePermissionFactory.java index e97e7177f2c..3a694eb1a56 100644 --- a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/role/RolePermissionFactory.java +++ b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/role/RolePermissionFactory.java @@ -20,6 +20,6 @@ * @see org.eclipse.kapua.model.KapuaEntityFactory * @since 1.0.0 */ -public interface RolePermissionFactory extends KapuaEntityFactory { +public interface RolePermissionFactory extends KapuaEntityFactory { } diff --git a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/role/RolePermissionListResult.java b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/role/RolePermissionListResult.java index 7bb2c6b935d..936734d4232 100644 --- a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/role/RolePermissionListResult.java +++ b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/role/RolePermissionListResult.java @@ -23,7 +23,9 @@ * @since 1.0.0 */ @XmlRootElement(name = "rolePermissions") -@XmlType(factoryClass = RolePermissionXmlRegistry.class, factoryMethod = "newRolePermissionListResult") -public interface RolePermissionListResult extends KapuaListResult { +@XmlType +public class RolePermissionListResult extends KapuaListResult { + + private static final long serialVersionUID = -4732941050197499090L; } diff --git a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/role/RolePermissionQuery.java b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/role/RolePermissionQuery.java deleted file mode 100644 index 5de910b2579..00000000000 --- a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/role/RolePermissionQuery.java +++ /dev/null @@ -1,32 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authorization.role; - -import org.eclipse.kapua.model.query.KapuaQuery; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlType; - -/** - * {@link RolePermission} {@link KapuaQuery} definition. - * - * @see KapuaQuery - * @since 1.0.0 - */ -@XmlRootElement(name = "query") -@XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = RolePermissionXmlRegistry.class, factoryMethod = "newQuery") -public interface RolePermissionQuery extends KapuaQuery { -} diff --git a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/role/RolePermissionService.java b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/role/RolePermissionService.java index 6af0eaee8c8..952ef173e41 100644 --- a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/role/RolePermissionService.java +++ b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/role/RolePermissionService.java @@ -25,10 +25,10 @@ public interface RolePermissionService extends KapuaEntityService { /** - * Creates a new {@link RolePermission} based on the parameters provided in the {@link RolePermissionCreator}.
        - * {@link RolePermission} must have a unique name within the scope. + * Creates a new {@link RolePermission} based on the parameters provided in the {@link RolePermissionCreator}.
        {@link RolePermission} must have a unique name within the scope. * - * @param rolePermissionCreator The creator object from which to create the {@link RolePermission}. + * @param rolePermissionCreator + * The creator object from which to create the {@link RolePermission}. * @throws KapuaException * @since 1.0.0 */ @@ -38,8 +38,10 @@ public interface RolePermissionService extends KapuaEntityService The type of the term + * @param matchTerm + * The term to use to match. + * @param + * The type of the term * @return The newly instantiated {@link RoleMatchPredicate}. * @since 2.1.0 */ - RoleMatchPredicate matchPredicate(T matchTerm); + public RoleMatchPredicate matchPredicate(T matchTerm) { + return new RoleMatchPredicate<>(matchTerm); + } } diff --git a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/role/RoleXmlRegistry.java b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/role/RoleXmlRegistry.java index b46b8aa8af1..ee52f98433e 100644 --- a/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/role/RoleXmlRegistry.java +++ b/service/security/authorization/api/src/main/java/org/eclipse/kapua/service/authorization/role/RoleXmlRegistry.java @@ -12,10 +12,10 @@ *******************************************************************************/ package org.eclipse.kapua.service.authorization.role; -import org.eclipse.kapua.locator.KapuaLocator; - import javax.xml.bind.annotation.XmlRegistry; +import org.eclipse.kapua.locator.KapuaLocator; + @XmlRegistry public class RoleXmlRegistry { @@ -31,33 +31,4 @@ public Role newRole() { return roleFactory.newEntity(null); } - /** - * Creates a new {@link RoleCreator} instance. - * - * @return The newly created {@link RoleCreator} instance. - * @since 1.0.0 - */ - public RoleCreator newRoleCreator() { - return roleFactory.newCreator(null); - } - - /** - * Creates a new {@link RoleListResult} instance. - * - * @return The newly created {@link RoleListResult} instance. - * @since 1.0.0 - */ - public RoleListResult newRoleListResult() { - return roleFactory.newListResult(); - } - - /** - * Creates a new {@link RoleQuery} instance. - * - * @return The newly created {@link RoleQuery} instance. - * @since 1.0.0 - */ - public RoleQuery newQuery() { - return roleFactory.newQuery(null); - } } diff --git a/service/security/authorization/pom.xml b/service/security/authorization/pom.xml index 7e7437df613..0ff58c9e704 100644 --- a/service/security/authorization/pom.xml +++ b/service/security/authorization/pom.xml @@ -19,7 +19,7 @@ org.eclipse.kapua kapua-security - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT pom diff --git a/service/security/certificate/api/pom.xml b/service/security/certificate/api/pom.xml index 490d4b98b81..f8eb36e157a 100644 --- a/service/security/certificate/api/pom.xml +++ b/service/security/certificate/api/pom.xml @@ -18,7 +18,7 @@ kapua-security-certificate org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT 4.0.0 diff --git a/service/security/certificate/api/src/main/java/org/eclipse/kapua/service/certificate/CertificateCreator.java b/service/security/certificate/api/src/main/java/org/eclipse/kapua/service/certificate/CertificateCreator.java index ee17959ac1f..e4698d99d4f 100644 --- a/service/security/certificate/api/src/main/java/org/eclipse/kapua/service/certificate/CertificateCreator.java +++ b/service/security/certificate/api/src/main/java/org/eclipse/kapua/service/certificate/CertificateCreator.java @@ -12,10 +12,8 @@ *******************************************************************************/ package org.eclipse.kapua.service.certificate; -import org.eclipse.kapua.model.KapuaNamedEntityCreator; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.model.id.KapuaIdAdapter; -import org.eclipse.kapua.service.certificate.xml.CertificateXmlRegistry; +import java.util.HashSet; +import java.util.Set; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; @@ -24,7 +22,10 @@ import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; -import java.util.Set; + +import org.eclipse.kapua.model.KapuaNamedEntityCreator; +import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.id.KapuaIdAdapter; /** * {@link Certificate} {@link org.eclipse.kapua.model.KapuaEntityCreator}encapsulates all the information needed to create a new {@link Certificate} in the system. @@ -33,43 +34,97 @@ */ @XmlRootElement(name = "certificateCreator") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = CertificateXmlRegistry.class, factoryMethod = "newCreator") -public interface CertificateCreator extends KapuaNamedEntityCreator { +@XmlType +public class CertificateCreator extends KapuaNamedEntityCreator { + + private String certificate; + private CertificateStatus status; + private String privateKey; + private KapuaId caId; + private String password; + private Set certificateUsages; + private Boolean forwardable; + + public CertificateCreator() { + } + + public CertificateCreator(KapuaId scopeId) { + super(scopeId); + } + + public CertificateCreator(KapuaId scopeId, String name) { + super(scopeId, name); + } @XmlElement(name = "certificate") - String getCertificate(); + public String getCertificate() { + return certificate; + } - void setCertificate(String certificate); + public void setCertificate(String certificate) { + this.certificate = certificate; + } @XmlElement(name = "status") - CertificateStatus getStatus(); + public CertificateStatus getStatus() { + //Kind hackish, but the database does not allow nulls here. + //default value was previously set in the constructor, but that only works if the field is not present in the "dto" (request payload for rest apis), and not when the field is passed as null, and changing the field to be required would break back-compatibility. + return status == null ? CertificateStatus.VALID : status; + } - void setStatus(CertificateStatus status); + public void setStatus(CertificateStatus status) { + this.status = status; + } @XmlElement(name = "privateKey") - String getPrivateKey(); + public String getPrivateKey() { + return privateKey; + } - void setPrivateKey(String privateKey); + public void setPrivateKey(String privateKey) { + this.privateKey = privateKey; + } @XmlElement(name = "caId") @XmlJavaTypeAdapter(KapuaIdAdapter.class) - KapuaId getCaId(); + public KapuaId getCaId() { + return caId; + } - void setCaId(KapuaId caId); + public void setCaId(KapuaId caId) { + this.caId = caId; + } @XmlElement(name = "password") - String getPassword(); + public String getPassword() { + return password; + } - void setPassword(String password); + public void setPassword(String password) { + this.password = password; + } @XmlElementWrapper(name = "certificateUsages") @XmlElement(name = "certificateUsage") - Set getCertificateUsages(); - - void setCertificateUsages(Set certificateUsages); + public Set getCertificateUsages() { + return certificateUsages; + } + + public void setCertificateUsages(Set set) { + Set newSet = new HashSet<>(); + for (CertificateUsage certificateUsage : set) { + newSet.add(certificateUsage); + } + certificateUsages = newSet; + } @XmlElement(name = "forwardable") - Boolean getForwardable(); + public Boolean getForwardable() { + return forwardable; + } + + public void setForwardable(Boolean forwardable) { + this.forwardable = forwardable; + } - void setForwardable(Boolean forwardable); } diff --git a/service/security/certificate/api/src/main/java/org/eclipse/kapua/service/certificate/CertificateFactory.java b/service/security/certificate/api/src/main/java/org/eclipse/kapua/service/certificate/CertificateFactory.java index 0006c87a0bb..b73aded9ad9 100644 --- a/service/security/certificate/api/src/main/java/org/eclipse/kapua/service/certificate/CertificateFactory.java +++ b/service/security/certificate/api/src/main/java/org/eclipse/kapua/service/certificate/CertificateFactory.java @@ -20,12 +20,13 @@ * @see org.eclipse.kapua.model.KapuaEntityFactory * @since 1.0.0 */ -public interface CertificateFactory extends KapuaEntityFactory { +public interface CertificateFactory extends KapuaEntityFactory { /** * Instantiates a new {@link CertificateUsage}. * - * @param name The name to set into the {@link CertificateUsage} + * @param name + * The name to set into the {@link CertificateUsage} * @return The newly instantiated {@link CertificateUsage} * @since 1.0.0 */ @@ -34,9 +35,12 @@ public interface CertificateFactory extends KapuaEntityFactory { +@XmlType +public class CertificateListResult extends KapuaListResult { + } diff --git a/service/security/certificate/api/src/main/java/org/eclipse/kapua/service/certificate/CertificateQuery.java b/service/security/certificate/api/src/main/java/org/eclipse/kapua/service/certificate/CertificateQuery.java index bce32852b6c..5ea9862f40b 100644 --- a/service/security/certificate/api/src/main/java/org/eclipse/kapua/service/certificate/CertificateQuery.java +++ b/service/security/certificate/api/src/main/java/org/eclipse/kapua/service/certificate/CertificateQuery.java @@ -12,16 +12,16 @@ *******************************************************************************/ package org.eclipse.kapua.service.certificate; -import org.eclipse.kapua.model.query.KapuaForwardableEntityQuery; -import org.eclipse.kapua.model.query.KapuaQuery; -import org.eclipse.kapua.service.certificate.xml.CertificateXmlRegistry; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; +import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.query.KapuaForwardableEntityQuery; +import org.eclipse.kapua.model.query.KapuaQuery; + /** * {@link Certificate} {@link KapuaQuery} definition. * @@ -30,25 +30,40 @@ */ @XmlRootElement(name = "query") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = CertificateXmlRegistry.class, factoryMethod = "newQuery") -public interface CertificateQuery extends KapuaForwardableEntityQuery { +@XmlType +public class CertificateQuery extends KapuaForwardableEntityQuery { + + public CertificateQuery() { + } + + public CertificateQuery(KapuaId scopeId) { + super(scopeId); + } + + public CertificateQuery(KapuaQuery query) { + super(query); + } @Override /** - * Gets whether or not to get also inherited {@link CertificateInfo}s + * Gets whether or not to get also inherited {@link Certificate}s * - * @return {@code true} if set to get inherited {@link CertificateInfo}s, {@code false} otherwise. + * @return {@code true} if set to get inherited {@link Certificate}s, {@code false} otherwise. * @since 1.0.0 */ @XmlElement(name = "includeInherited") - Boolean getIncludeInherited(); + public Boolean getIncludeInherited() { + return includeInherited; + } @Override /** - * Sets whether or not to get also inherited {@link CertificateInfo}s + * Sets whether or not to get also inherited {@link Certificate}s * - * @param includeInherited {@code true} to get inherited {@link CertificateInfo}s, {@code false} otherwise. + * @param includeInherited {@code true} to get inherited {@link Certificate}s, {@code false} otherwise. * @since 1.0.0 */ - void setIncludeInherited(Boolean includeInherited); + public void setIncludeInherited(Boolean includeInherited) { + this.includeInherited = includeInherited; + } } diff --git a/service/security/certificate/api/src/main/java/org/eclipse/kapua/service/certificate/info/CertificateInfoCreator.java b/service/security/certificate/api/src/main/java/org/eclipse/kapua/service/certificate/info/CertificateInfoCreator.java index 862056e315d..d05aa63fc5b 100644 --- a/service/security/certificate/api/src/main/java/org/eclipse/kapua/service/certificate/info/CertificateInfoCreator.java +++ b/service/security/certificate/api/src/main/java/org/eclipse/kapua/service/certificate/info/CertificateInfoCreator.java @@ -12,19 +12,32 @@ *******************************************************************************/ package org.eclipse.kapua.service.certificate.info; -import org.eclipse.kapua.model.KapuaNamedEntityCreator; -import org.eclipse.kapua.service.certificate.info.xml.CertificateInfoXmlRegistry; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; +import org.eclipse.kapua.model.KapuaNamedEntityCreator; +import org.eclipse.kapua.model.id.KapuaId; + /** * @since 1.1.0 */ @XmlRootElement(name = "certificateInfoCreator") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = CertificateInfoXmlRegistry.class, factoryMethod = "newCreator") -public interface CertificateInfoCreator extends KapuaNamedEntityCreator { +@XmlType +//This class exists only because the Service needed a placeholder.Sigh. +public class CertificateInfoCreator extends KapuaNamedEntityCreator { + + public CertificateInfoCreator() { + throw new UnsupportedOperationException(); + } + + public CertificateInfoCreator(KapuaId scopeId) { + throw new UnsupportedOperationException(); + } + + public CertificateInfoCreator(KapuaId scopeId, String name) { + throw new UnsupportedOperationException(); + } } diff --git a/service/security/certificate/api/src/main/java/org/eclipse/kapua/service/certificate/info/CertificateInfoFactory.java b/service/security/certificate/api/src/main/java/org/eclipse/kapua/service/certificate/info/CertificateInfoFactory.java index e188bd24b7a..c1ba0bdc295 100644 --- a/service/security/certificate/api/src/main/java/org/eclipse/kapua/service/certificate/info/CertificateInfoFactory.java +++ b/service/security/certificate/api/src/main/java/org/eclipse/kapua/service/certificate/info/CertificateInfoFactory.java @@ -17,5 +17,6 @@ /** * @since 1.1.0 */ -public interface CertificateInfoFactory extends KapuaEntityFactory { +public interface CertificateInfoFactory extends KapuaEntityFactory { + } diff --git a/service/security/certificate/api/src/main/java/org/eclipse/kapua/service/certificate/info/CertificateInfoListResult.java b/service/security/certificate/api/src/main/java/org/eclipse/kapua/service/certificate/info/CertificateInfoListResult.java index 5e1c679e2ff..3c66f97bbba 100644 --- a/service/security/certificate/api/src/main/java/org/eclipse/kapua/service/certificate/info/CertificateInfoListResult.java +++ b/service/security/certificate/api/src/main/java/org/eclipse/kapua/service/certificate/info/CertificateInfoListResult.java @@ -12,19 +12,19 @@ *******************************************************************************/ package org.eclipse.kapua.service.certificate.info; -import org.eclipse.kapua.model.query.KapuaListResult; -import org.eclipse.kapua.service.certificate.info.xml.CertificateInfoXmlRegistry; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; +import org.eclipse.kapua.model.query.KapuaListResult; + /** * @since 1.1.0 */ @XmlRootElement(name = "certificateListResult") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = CertificateInfoXmlRegistry.class, factoryMethod = "newListResult") -public interface CertificateInfoListResult extends KapuaListResult { +@XmlType +public class CertificateInfoListResult extends KapuaListResult { + } diff --git a/service/security/certificate/api/src/main/java/org/eclipse/kapua/service/certificate/info/CertificateInfoMatchPredicate.java b/service/security/certificate/api/src/main/java/org/eclipse/kapua/service/certificate/info/CertificateInfoMatchPredicate.java index 80d1166cb16..92036c50b41 100644 --- a/service/security/certificate/api/src/main/java/org/eclipse/kapua/service/certificate/info/CertificateInfoMatchPredicate.java +++ b/service/security/certificate/api/src/main/java/org/eclipse/kapua/service/certificate/info/CertificateInfoMatchPredicate.java @@ -12,8 +12,26 @@ *******************************************************************************/ package org.eclipse.kapua.service.certificate.info; -import org.eclipse.kapua.model.query.predicate.MatchPredicate; +import java.util.Arrays; -public interface CertificateInfoMatchPredicate extends MatchPredicate { +import org.eclipse.kapua.model.query.predicate.AbstractMatchPredicate; +public class CertificateInfoMatchPredicate extends AbstractMatchPredicate { + + /** + * Constructor. + * + * @param matchTerm + * @since 2.1.0 + */ + public CertificateInfoMatchPredicate(T matchTerm) { + this.attributeNames = Arrays.asList( + CertificateInfoAttributes.NAME, + CertificateInfoAttributes.SERIAL, + CertificateInfoAttributes.SIGNATURE, + CertificateInfoAttributes.ALGORITHM, + CertificateInfoAttributes.SUBJECT + ); + this.matchTerm = matchTerm; + } } \ No newline at end of file diff --git a/service/security/certificate/api/src/main/java/org/eclipse/kapua/service/certificate/info/CertificateInfoQuery.java b/service/security/certificate/api/src/main/java/org/eclipse/kapua/service/certificate/info/CertificateInfoQuery.java index 1bf1f33dee5..531001c5790 100644 --- a/service/security/certificate/api/src/main/java/org/eclipse/kapua/service/certificate/info/CertificateInfoQuery.java +++ b/service/security/certificate/api/src/main/java/org/eclipse/kapua/service/certificate/info/CertificateInfoQuery.java @@ -12,16 +12,16 @@ *******************************************************************************/ package org.eclipse.kapua.service.certificate.info; -import org.eclipse.kapua.model.query.KapuaForwardableEntityQuery; -import org.eclipse.kapua.model.query.KapuaQuery; -import org.eclipse.kapua.service.certificate.info.xml.CertificateInfoXmlRegistry; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; +import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.query.KapuaForwardableEntityQuery; +import org.eclipse.kapua.model.query.KapuaQuery; + /** * {@link CertificateInfo} {@link KapuaQuery} definition. * @@ -30,8 +30,19 @@ */ @XmlRootElement(name = "query") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = CertificateInfoXmlRegistry.class, factoryMethod = "newQuery") -public interface CertificateInfoQuery extends KapuaForwardableEntityQuery { +@XmlType +public class CertificateInfoQuery extends KapuaForwardableEntityQuery { + + public CertificateInfoQuery() { + } + + public CertificateInfoQuery(KapuaId scopeId) { + super(scopeId); + } + + public CertificateInfoQuery(KapuaQuery query) { + super(query); + } @Override /** @@ -41,7 +52,9 @@ public interface CertificateInfoQuery extends KapuaForwardableEntityQuery { * @since 1.1.0 */ @XmlElement(name = "includeInherited") - Boolean getIncludeInherited(); + public Boolean getIncludeInherited() { + return includeInherited; + } @Override /** @@ -50,15 +63,21 @@ public interface CertificateInfoQuery extends KapuaForwardableEntityQuery { * @param includeInherited {@code true} to get inherited {@link CertificateInfo}s, {@code false} otherwise. * @since 1.1.0 */ - void setIncludeInherited(Boolean includeInherited); + public void setIncludeInherited(Boolean includeInherited) { + this.includeInherited = includeInherited; + } /** * Instantiates a new {@link CertificateInfoMatchPredicate}. * - * @param matchTerm The term to use to match. - * @param The type of the term + * @param matchTerm + * The term to use to match. + * @param + * The type of the term * @return The newly instantiated {@link CertificateInfoMatchPredicate}. * @since 2.1.0 */ - CertificateInfoMatchPredicate matchPredicate(T matchTerm); + public CertificateInfoMatchPredicate matchPredicate(T matchTerm) { + return new CertificateInfoMatchPredicate<>(matchTerm); + } } diff --git a/service/security/certificate/api/src/main/java/org/eclipse/kapua/service/certificate/info/xml/CertificateInfoXmlRegistry.java b/service/security/certificate/api/src/main/java/org/eclipse/kapua/service/certificate/info/xml/CertificateInfoXmlRegistry.java index 8400f77b56f..ce65eeeac87 100644 --- a/service/security/certificate/api/src/main/java/org/eclipse/kapua/service/certificate/info/xml/CertificateInfoXmlRegistry.java +++ b/service/security/certificate/api/src/main/java/org/eclipse/kapua/service/certificate/info/xml/CertificateInfoXmlRegistry.java @@ -12,14 +12,11 @@ *******************************************************************************/ package org.eclipse.kapua.service.certificate.info.xml; +import javax.xml.bind.annotation.XmlRegistry; + import org.eclipse.kapua.locator.KapuaLocator; import org.eclipse.kapua.service.certificate.info.CertificateInfo; -import org.eclipse.kapua.service.certificate.info.CertificateInfoCreator; import org.eclipse.kapua.service.certificate.info.CertificateInfoFactory; -import org.eclipse.kapua.service.certificate.info.CertificateInfoListResult; -import org.eclipse.kapua.service.certificate.info.CertificateInfoQuery; - -import javax.xml.bind.annotation.XmlRegistry; @XmlRegistry public class CertificateInfoXmlRegistry { @@ -29,16 +26,4 @@ public class CertificateInfoXmlRegistry { public CertificateInfo newCertificateInfo() { return certificateInfoFactory.newEntity(null); } - - public CertificateInfoCreator newCreator() { - return certificateInfoFactory.newCreator(null); - } - - public CertificateInfoQuery newQuery() { - return certificateInfoFactory.newQuery(null); - } - - public CertificateInfoListResult newListResult() { - return certificateInfoFactory.newListResult(); - } } diff --git a/service/security/certificate/api/src/main/java/org/eclipse/kapua/service/certificate/xml/CertificateXmlRegistry.java b/service/security/certificate/api/src/main/java/org/eclipse/kapua/service/certificate/xml/CertificateXmlRegistry.java index 588be879c8f..bde79ee1232 100644 --- a/service/security/certificate/api/src/main/java/org/eclipse/kapua/service/certificate/xml/CertificateXmlRegistry.java +++ b/service/security/certificate/api/src/main/java/org/eclipse/kapua/service/certificate/xml/CertificateXmlRegistry.java @@ -12,17 +12,14 @@ *******************************************************************************/ package org.eclipse.kapua.service.certificate.xml; +import javax.xml.bind.annotation.XmlRegistry; + import org.eclipse.kapua.locator.KapuaLocator; import org.eclipse.kapua.service.certificate.Certificate; -import org.eclipse.kapua.service.certificate.CertificateCreator; import org.eclipse.kapua.service.certificate.CertificateFactory; import org.eclipse.kapua.service.certificate.CertificateGenerator; -import org.eclipse.kapua.service.certificate.CertificateListResult; -import org.eclipse.kapua.service.certificate.CertificateQuery; import org.eclipse.kapua.service.certificate.CertificateUsage; -import javax.xml.bind.annotation.XmlRegistry; - @XmlRegistry public class CertificateXmlRegistry { @@ -32,18 +29,6 @@ public Certificate newCertificate() { return certificateFactory.newEntity(null); } - public CertificateCreator newCreator() { - return certificateFactory.newCreator(null); - } - - public CertificateQuery newQuery() { - return certificateFactory.newQuery(null); - } - - public CertificateListResult newListResult() { - return certificateFactory.newListResult(); - } - public CertificateGenerator newCertificateGenerator() { return certificateFactory.newCertificateGenerator(); } diff --git a/service/security/certificate/internal/pom.xml b/service/security/certificate/internal/pom.xml index a6845068dc7..b890dfe3060 100644 --- a/service/security/certificate/internal/pom.xml +++ b/service/security/certificate/internal/pom.xml @@ -18,7 +18,7 @@ kapua-security-certificate org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT 4.0.0 diff --git a/service/security/certificate/internal/src/main/java/org/eclipse/kapua/service/certificate/info/internal/CertificateInfoFactoryImpl.java b/service/security/certificate/internal/src/main/java/org/eclipse/kapua/service/certificate/info/internal/CertificateInfoFactoryImpl.java index 06d67d43e0b..80e518ab3d4 100644 --- a/service/security/certificate/internal/src/main/java/org/eclipse/kapua/service/certificate/info/internal/CertificateInfoFactoryImpl.java +++ b/service/security/certificate/internal/src/main/java/org/eclipse/kapua/service/certificate/info/internal/CertificateInfoFactoryImpl.java @@ -12,15 +12,12 @@ *******************************************************************************/ package org.eclipse.kapua.service.certificate.info.internal; +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaEntityCloneException; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.certificate.info.CertificateInfo; -import org.eclipse.kapua.service.certificate.info.CertificateInfoCreator; import org.eclipse.kapua.service.certificate.info.CertificateInfoFactory; -import org.eclipse.kapua.service.certificate.info.CertificateInfoListResult; -import org.eclipse.kapua.service.certificate.info.CertificateInfoQuery; - -import javax.inject.Singleton; @Singleton public class CertificateInfoFactoryImpl implements CertificateInfoFactory { @@ -30,21 +27,6 @@ public CertificateInfo newEntity(KapuaId scopeId) { return new CertificateInfoImpl(scopeId); } - @Override - public CertificateInfoCreator newCreator(KapuaId scopeId) { - throw new UnsupportedOperationException(); - } - - @Override - public CertificateInfoQuery newQuery(KapuaId scopeId) { - return new CertificateInfoQueryImpl(scopeId); - } - - @Override - public CertificateInfoListResult newListResult() { - return new CertificateInfoListResultImpl(); - } - @Override public CertificateInfo clone(CertificateInfo certificateInfo) throws KapuaEntityCloneException { try { diff --git a/service/security/certificate/internal/src/main/java/org/eclipse/kapua/service/certificate/info/internal/CertificateInfoListResultImpl.java b/service/security/certificate/internal/src/main/java/org/eclipse/kapua/service/certificate/info/internal/CertificateInfoListResultImpl.java deleted file mode 100644 index d1c3dc2b83a..00000000000 --- a/service/security/certificate/internal/src/main/java/org/eclipse/kapua/service/certificate/info/internal/CertificateInfoListResultImpl.java +++ /dev/null @@ -1,27 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2018, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.certificate.info.internal; - -import org.eclipse.kapua.commons.model.query.KapuaListResultImpl; -import org.eclipse.kapua.service.certificate.info.CertificateInfo; -import org.eclipse.kapua.service.certificate.info.CertificateInfoListResult; - -/** - * {@link CertificateInfoListResult} implementation. - * - * @since 1.0 - */ - -public class CertificateInfoListResultImpl extends KapuaListResultImpl implements CertificateInfoListResult { - -} diff --git a/service/security/certificate/internal/src/main/java/org/eclipse/kapua/service/certificate/info/internal/CertificateInfoMatchPredicateImpl.java b/service/security/certificate/internal/src/main/java/org/eclipse/kapua/service/certificate/info/internal/CertificateInfoMatchPredicateImpl.java deleted file mode 100644 index 4d42434e7a5..00000000000 --- a/service/security/certificate/internal/src/main/java/org/eclipse/kapua/service/certificate/info/internal/CertificateInfoMatchPredicateImpl.java +++ /dev/null @@ -1,40 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2018, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.certificate.info.internal; - -import org.eclipse.kapua.commons.model.query.predicate.AbstractMatchPredicate; -import org.eclipse.kapua.service.certificate.info.CertificateInfoAttributes; -import org.eclipse.kapua.service.certificate.info.CertificateInfoMatchPredicate; - -import java.util.Arrays; - -public class CertificateInfoMatchPredicateImpl extends AbstractMatchPredicate implements CertificateInfoMatchPredicate { - - /** - * Constructor. - * - * @param matchTerm - * @since 2.1.0 - */ - public CertificateInfoMatchPredicateImpl(T matchTerm) { - this.attributeNames = Arrays.asList( - CertificateInfoAttributes.NAME, - CertificateInfoAttributes.SERIAL, - CertificateInfoAttributes.SIGNATURE, - CertificateInfoAttributes.ALGORITHM, - CertificateInfoAttributes.SUBJECT - ); - this.matchTerm = matchTerm; - } - -} diff --git a/service/security/certificate/internal/src/main/java/org/eclipse/kapua/service/certificate/info/internal/CertificateInfoQueryImpl.java b/service/security/certificate/internal/src/main/java/org/eclipse/kapua/service/certificate/info/internal/CertificateInfoQueryImpl.java deleted file mode 100644 index 3c64874d30f..00000000000 --- a/service/security/certificate/internal/src/main/java/org/eclipse/kapua/service/certificate/info/internal/CertificateInfoQueryImpl.java +++ /dev/null @@ -1,63 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2018, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.certificate.info.internal; - -import org.eclipse.kapua.commons.model.query.AbstractKapuaNamedQuery; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.certificate.info.CertificateInfoMatchPredicate; -import org.eclipse.kapua.service.certificate.info.CertificateInfoQuery; - -/** - * {@link CertificateInfoQuery} implementation. - * - * @since 1.0.0 - */ -public class CertificateInfoQueryImpl extends AbstractKapuaNamedQuery implements CertificateInfoQuery { - - private Boolean includeInherited = Boolean.FALSE; - - /** - * Constructor. - * - * @since 1.0.0 - */ - private CertificateInfoQueryImpl() { - super(); - } - - /** - * Constructor. - * - * @param scopeId The {@link #getScopeId()}. - * @since 1.0.0 - */ - public CertificateInfoQueryImpl(KapuaId scopeId) { - this(); - setScopeId(scopeId); - } - - @Override - public Boolean getIncludeInherited() { - return includeInherited; - } - - @Override - public void setIncludeInherited(Boolean includeInherited) { - this.includeInherited = includeInherited; - } - - @Override - public CertificateInfoMatchPredicate matchPredicate(T matchTerm) { - return new CertificateInfoMatchPredicateImpl<>(matchTerm); - } -} diff --git a/service/security/certificate/internal/src/main/java/org/eclipse/kapua/service/certificate/info/internal/CertificateInfoServiceImpl.java b/service/security/certificate/internal/src/main/java/org/eclipse/kapua/service/certificate/info/internal/CertificateInfoServiceImpl.java index 1d99a7c42d1..0d248c93046 100644 --- a/service/security/certificate/internal/src/main/java/org/eclipse/kapua/service/certificate/info/internal/CertificateInfoServiceImpl.java +++ b/service/security/certificate/internal/src/main/java/org/eclipse/kapua/service/certificate/info/internal/CertificateInfoServiceImpl.java @@ -12,6 +12,11 @@ *******************************************************************************/ package org.eclipse.kapua.service.certificate.info.internal; +import java.util.List; + +import javax.inject.Inject; +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.commons.util.ArgumentValidator; import org.eclipse.kapua.model.id.KapuaId; @@ -24,11 +29,6 @@ import org.eclipse.kapua.service.certificate.info.CertificateInfoListResult; import org.eclipse.kapua.service.certificate.info.CertificateInfoQuery; import org.eclipse.kapua.service.certificate.info.CertificateInfoService; -import org.eclipse.kapua.service.certificate.internal.CertificateQueryImpl; - -import javax.inject.Inject; -import javax.inject.Singleton; -import java.util.List; @Singleton public class CertificateInfoServiceImpl implements CertificateInfoService { @@ -54,9 +54,9 @@ public CertificateInfo find(KapuaId scopeId, KapuaId entityId) { public CertificateInfoListResult query(KapuaQuery query) throws KapuaException { ArgumentValidator.notNull(query, "query"); - CertificateQuery certificateQuery = new CertificateQueryImpl(query); + CertificateQuery certificateQuery = new CertificateQuery(query); - CertificateInfoListResult publicCertificates = new CertificateInfoListResultImpl(); + CertificateInfoListResult publicCertificates = new CertificateInfoListResult(); publicCertificates.addItem(certificateService.query(certificateQuery).getFirstItem()); return publicCertificates; @@ -66,7 +66,7 @@ public CertificateInfoListResult query(KapuaQuery query) throws KapuaException { public long count(KapuaQuery query) throws KapuaException { ArgumentValidator.notNull(query, "query"); - CertificateQuery privateQuery = new CertificateQueryImpl(query); + CertificateQuery privateQuery = new CertificateQuery(query); privateQuery.setIncludeInherited(((CertificateInfoQuery) query).getIncludeInherited()); return certificateService.count(privateQuery); diff --git a/service/security/certificate/internal/src/main/java/org/eclipse/kapua/service/certificate/internal/CertificateFactoryImpl.java b/service/security/certificate/internal/src/main/java/org/eclipse/kapua/service/certificate/internal/CertificateFactoryImpl.java index 8f0e7a4bf9b..51c66fbbe4d 100644 --- a/service/security/certificate/internal/src/main/java/org/eclipse/kapua/service/certificate/internal/CertificateFactoryImpl.java +++ b/service/security/certificate/internal/src/main/java/org/eclipse/kapua/service/certificate/internal/CertificateFactoryImpl.java @@ -12,20 +12,17 @@ *******************************************************************************/ package org.eclipse.kapua.service.certificate.internal; +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaEntityCloneException; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.certificate.Certificate; -import org.eclipse.kapua.service.certificate.CertificateCreator; import org.eclipse.kapua.service.certificate.CertificateFactory; import org.eclipse.kapua.service.certificate.CertificateGenerator; -import org.eclipse.kapua.service.certificate.CertificateListResult; -import org.eclipse.kapua.service.certificate.CertificateQuery; import org.eclipse.kapua.service.certificate.CertificateUsage; import org.eclipse.kapua.service.certificate.KeyUsage; import org.eclipse.kapua.service.certificate.KeyUsageSetting; -import javax.inject.Singleton; - /** * {@link CertificateFactory} implementation. * @@ -39,21 +36,6 @@ public Certificate newEntity(KapuaId scopeId) { return new CertificateImpl(scopeId); } - @Override - public CertificateCreator newCreator(KapuaId scopeId) { - throw new UnsupportedOperationException(); - } - - @Override - public CertificateQuery newQuery(KapuaId scopeId) { - return new CertificateQueryImpl(scopeId); - } - - @Override - public CertificateListResult newListResult() { - return new CertificateListResultImpl(); - } - @Override public CertificateUsage newCertificateUsage(String name) { return new CertificateUsageImpl(name); diff --git a/service/security/certificate/internal/src/main/java/org/eclipse/kapua/service/certificate/internal/CertificateListResultImpl.java b/service/security/certificate/internal/src/main/java/org/eclipse/kapua/service/certificate/internal/CertificateListResultImpl.java deleted file mode 100644 index fb00cdb2eaa..00000000000 --- a/service/security/certificate/internal/src/main/java/org/eclipse/kapua/service/certificate/internal/CertificateListResultImpl.java +++ /dev/null @@ -1,27 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2017, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.certificate.internal; - -import org.eclipse.kapua.commons.model.query.KapuaListResultImpl; -import org.eclipse.kapua.service.certificate.Certificate; -import org.eclipse.kapua.service.certificate.CertificateListResult; - -/** - * {@link CertificateListResult} implementation. - * - * @since 1.0 - */ - -public class CertificateListResultImpl extends KapuaListResultImpl implements CertificateListResult { - -} diff --git a/service/security/certificate/internal/src/main/java/org/eclipse/kapua/service/certificate/internal/CertificateQueryImpl.java b/service/security/certificate/internal/src/main/java/org/eclipse/kapua/service/certificate/internal/CertificateQueryImpl.java deleted file mode 100644 index 5a7fc108e9a..00000000000 --- a/service/security/certificate/internal/src/main/java/org/eclipse/kapua/service/certificate/internal/CertificateQueryImpl.java +++ /dev/null @@ -1,56 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2017, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.certificate.internal; - -import org.eclipse.kapua.commons.model.query.AbstractKapuaForwardableEntityQuery; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.model.query.KapuaQuery; -import org.eclipse.kapua.service.certificate.CertificateQuery; - -/** - * {@link CertificateQuery} implementation. - * - * @since 1.0.0 - */ -public class CertificateQueryImpl extends AbstractKapuaForwardableEntityQuery implements CertificateQuery { - - /** - * Constructor. - * - * @since 1.0.0 - */ - private CertificateQueryImpl() { - super(); - } - - /** - * Constructor. - * - * @param scopeId The {@link #getScopeId()}. - * @since 1.0.0 - */ - public CertificateQueryImpl(KapuaId scopeId) { - this(); - setScopeId(scopeId); - } - - /** - * Clone constructor. - * - * @param query The {@link CertificateQuery} to clone. - * @since 1.0.0 - */ - public CertificateQueryImpl(KapuaQuery query) { - super(query); - } -} diff --git a/service/security/certificate/internal/src/main/java/org/eclipse/kapua/service/certificate/internal/CertificateServiceImpl.java b/service/security/certificate/internal/src/main/java/org/eclipse/kapua/service/certificate/internal/CertificateServiceImpl.java index abcc2da0c2a..7326729a2e6 100644 --- a/service/security/certificate/internal/src/main/java/org/eclipse/kapua/service/certificate/internal/CertificateServiceImpl.java +++ b/service/security/certificate/internal/src/main/java/org/eclipse/kapua/service/certificate/internal/CertificateServiceImpl.java @@ -25,16 +25,14 @@ import org.eclipse.kapua.commons.security.KapuaSecurityUtils; import org.eclipse.kapua.commons.util.ArgumentValidator; import org.eclipse.kapua.commons.util.KapuaFileUtils; -import org.eclipse.kapua.model.config.metatype.EmptyTocd; import org.eclipse.kapua.model.config.metatype.KapuaTocd; import org.eclipse.kapua.model.domain.Actions; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; +import org.eclipse.kapua.service.authorization.permission.Permission; import org.eclipse.kapua.service.certificate.Certificate; import org.eclipse.kapua.service.certificate.CertificateCreator; -import org.eclipse.kapua.service.certificate.CertificateFactory; import org.eclipse.kapua.service.certificate.CertificateGenerator; import org.eclipse.kapua.service.certificate.CertificateListResult; import org.eclipse.kapua.service.certificate.CertificateService; @@ -58,19 +56,15 @@ public class CertificateServiceImpl implements CertificateService { private static final Logger LOG = LoggerFactory.getLogger(CertificateServiceImpl.class); private final AuthorizationService authorizationService; - private final PermissionFactory permissionFactory; - private final CertificateFactory certificateFactory; private final KapuaCertificateSetting kapuaCertificateSetting; private String certificate; private String privateKey; private KapuaTocd emptyTocd; @Inject - public CertificateServiceImpl(AuthorizationService authorizationService, PermissionFactory permissionFactory, CertificateFactory certificateFactory, + public CertificateServiceImpl(AuthorizationService authorizationService, KapuaCertificateSetting kapuaCertificateSetting) throws KapuaException { this.authorizationService = authorizationService; - this.permissionFactory = permissionFactory; - this.certificateFactory = certificateFactory; this.kapuaCertificateSetting = kapuaCertificateSetting; KapuaSecurityUtils.doPrivileged(() -> { String privateKeyPath = kapuaCertificateSetting.getString(KapuaCertificateSettingKeys.CERTIFICATE_JWT_PRIVATE_KEY); @@ -85,7 +79,7 @@ public CertificateServiceImpl(AuthorizationService authorizationService, Permiss } }); - emptyTocd = new EmptyTocd(CertificateService.class.getName(), CertificateService.class.getSimpleName()); + emptyTocd = KapuaTocd.empty(CertificateService.class.getName(), CertificateService.class.getSimpleName()); } @@ -104,7 +98,7 @@ public CertificateListResult query(KapuaQuery query) throws KapuaException { // Argument Validation ArgumentValidator.notNull(query, "query"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.CERTIFICATE, Actions.read, query.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.CERTIFICATE, Actions.read, query.getScopeId())); // Create the default certificate CertificateUsage jwtCertificateUsage = new CertificateUsageImpl("JWT"); Set certificateUsages = Sets.newHashSet(jwtCertificateUsage); @@ -121,7 +115,7 @@ public CertificateListResult query(KapuaQuery query) throws KapuaException { kapuaCertificate.setCertificateUsages(certificateUsages); kapuaCertificate.setPassword(kapuaCertificateSetting.getString(KapuaCertificateSettingKeys.CERTIFICATE_JWT_PRIVATE_KEY_PASSWORD)); - CertificateListResult result = certificateFactory.newListResult(); + CertificateListResult result = new CertificateListResult(); result.addItem(kapuaCertificate); return result; diff --git a/service/security/certificate/pom.xml b/service/security/certificate/pom.xml index 94dac4e7302..b7cf0c479e8 100644 --- a/service/security/certificate/pom.xml +++ b/service/security/certificate/pom.xml @@ -18,7 +18,7 @@ kapua-security org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT 4.0.0 diff --git a/service/security/pom.xml b/service/security/pom.xml index 7d36e97e075..f858c5dcb48 100644 --- a/service/security/pom.xml +++ b/service/security/pom.xml @@ -19,7 +19,7 @@ org.eclipse.kapua kapua-service - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT pom diff --git a/service/security/registration/api/pom.xml b/service/security/registration/api/pom.xml index 30a6e408070..7336c93f4c2 100644 --- a/service/security/registration/api/pom.xml +++ b/service/security/registration/api/pom.xml @@ -19,7 +19,7 @@ org.eclipse.kapua kapua-security-registration - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-security-registration-api diff --git a/service/security/registration/pom.xml b/service/security/registration/pom.xml index a57ea61a4a2..ba487981b88 100644 --- a/service/security/registration/pom.xml +++ b/service/security/registration/pom.xml @@ -19,7 +19,7 @@ org.eclipse.kapua kapua-security - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-security-registration diff --git a/service/security/registration/simple/pom.xml b/service/security/registration/simple/pom.xml index 9218ec8dc06..809a3b33cf7 100644 --- a/service/security/registration/simple/pom.xml +++ b/service/security/registration/simple/pom.xml @@ -20,7 +20,7 @@ org.eclipse.kapua kapua-security-registration - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-security-registration-simple @@ -33,7 +33,7 @@ org.eclipse.kapua kapua-account-internal - + org.eclipse.kapua kapua-datastore-api diff --git a/service/security/registration/simple/src/main/java/org/eclipse/kapua/security/registration/simple/SimpleRegistrationModule.java b/service/security/registration/simple/src/main/java/org/eclipse/kapua/security/registration/simple/SimpleRegistrationModule.java index 4c86304e3c0..075ff84d2bb 100644 --- a/service/security/registration/simple/src/main/java/org/eclipse/kapua/security/registration/simple/SimpleRegistrationModule.java +++ b/service/security/registration/simple/src/main/java/org/eclipse/kapua/security/registration/simple/SimpleRegistrationModule.java @@ -12,25 +12,22 @@ *******************************************************************************/ package org.eclipse.kapua.security.registration.simple; -import com.google.inject.multibindings.ProvidesIntoSet; +import javax.inject.Singleton; + import org.eclipse.kapua.commons.core.AbstractKapuaModule; import org.eclipse.kapua.commons.liquibase.DatabaseCheckUpdate; import org.eclipse.kapua.security.registration.RegistrationProcessorProvider; import org.eclipse.kapua.security.registration.simple.setting.SimpleSetting; -import org.eclipse.kapua.service.account.AccountFactory; import org.eclipse.kapua.service.account.AccountService; -import org.eclipse.kapua.service.authentication.credential.CredentialFactory; import org.eclipse.kapua.service.authentication.credential.CredentialService; -import org.eclipse.kapua.service.authorization.access.AccessInfoFactory; import org.eclipse.kapua.service.authorization.access.AccessInfoService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; import org.eclipse.kapua.service.device.registry.DeviceRegistryService; -import org.eclipse.kapua.service.user.UserFactory; import org.eclipse.kapua.service.user.UserService; -import javax.inject.Singleton; +import com.google.inject.multibindings.ProvidesIntoSet; public class SimpleRegistrationModule extends AbstractKapuaModule { + @Override protected void configureModule() { bind(SimpleSetting.class).in(Singleton.class); @@ -41,27 +38,18 @@ protected void configureModule() { RegistrationProcessorProvider simpleRegistrationProcessorProvider( SimpleSetting simpleSetting, AccountService accountService, - AccountFactory accountFactory, CredentialService credentialService, - CredentialFactory credentialFactory, DeviceRegistryService deviceRegistryService, UserService userService, - UserFactory userFactory, AccessInfoService accessInfoService, - AccessInfoFactory accessInfoFactory, - PermissionFactory permissionFactory, //Liquibase must start before this DatabaseCheckUpdate databaseCheckUpdate) { return new SimpleRegistrationProcessorProvider(simpleSetting, accountService, - accountFactory, credentialService, - credentialFactory, deviceRegistryService, userService, - userFactory, - accessInfoService, - accessInfoFactory, - permissionFactory); + accessInfoService + ); } } diff --git a/service/security/registration/simple/src/main/java/org/eclipse/kapua/security/registration/simple/SimpleRegistrationProcessor.java b/service/security/registration/simple/src/main/java/org/eclipse/kapua/security/registration/simple/SimpleRegistrationProcessor.java index ceedb5e7d85..314d37e1c70 100644 --- a/service/security/registration/simple/src/main/java/org/eclipse/kapua/security/registration/simple/SimpleRegistrationProcessor.java +++ b/service/security/registration/simple/src/main/java/org/eclipse/kapua/security/registration/simple/SimpleRegistrationProcessor.java @@ -12,6 +12,16 @@ *******************************************************************************/ package org.eclipse.kapua.security.registration.simple; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.commons.model.domains.Domains; import org.eclipse.kapua.commons.security.KapuaSecurityUtils; @@ -24,46 +34,29 @@ import org.eclipse.kapua.security.registration.simple.setting.SimpleSettingKeys; import org.eclipse.kapua.service.account.Account; import org.eclipse.kapua.service.account.AccountCreator; -import org.eclipse.kapua.service.account.AccountFactory; import org.eclipse.kapua.service.account.AccountService; import org.eclipse.kapua.service.authentication.credential.CredentialCreator; -import org.eclipse.kapua.service.authentication.credential.CredentialFactory; import org.eclipse.kapua.service.authentication.credential.CredentialService; import org.eclipse.kapua.service.authentication.credential.CredentialStatus; import org.eclipse.kapua.service.authorization.access.AccessInfoCreator; -import org.eclipse.kapua.service.authorization.access.AccessInfoFactory; import org.eclipse.kapua.service.authorization.access.AccessInfoService; import org.eclipse.kapua.service.authorization.permission.Permission; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; import org.eclipse.kapua.service.device.registry.DeviceRegistryService; import org.eclipse.kapua.service.user.User; import org.eclipse.kapua.service.user.UserCreator; -import org.eclipse.kapua.service.user.UserFactory; import org.eclipse.kapua.service.user.UserService; import org.eclipse.kapua.service.user.UserType; import org.jose4j.jwt.consumer.JwtContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.time.Instant; -import java.time.temporal.ChronoUnit; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; - /** * A processor which creates a simple account and user setup *

        - * This processor creates a new account based on the OpenID SSO claim and creates a single - * user for this account. + * This processor creates a new account based on the OpenID SSO claim and creates a single user for this account. *

        *

        - * It is possible to define the root account which all accounts will be part of using - * the {@link Settings} class. + * It is possible to define the root account which all accounts will be part of using the {@link Settings} class. *

        */ public class SimpleRegistrationProcessor implements RegistrationProcessor { @@ -92,7 +85,8 @@ public KapuaId getRootAccount() { * If this value is negative then there will be no limit on the number of child users. *

        * - * @param maximumNumberOfChildUsers The number of child users to allow + * @param maximumNumberOfChildUsers + * The number of child users to allow */ public void setMaximumNumberOfUsers(int maximumNumberOfChildUsers) { this.maximumNumberOfUsers = maximumNumberOfChildUsers; @@ -141,20 +135,15 @@ private static SimpleRegistrationProcessor.Settings applySimpleSettings(KapuaId } private final AccountService accountService; - private final AccountFactory accountFactory; private final CredentialService credentialService; - private final CredentialFactory credentialFactory; private final DeviceRegistryService deviceRegistryService; private final UserService userService; - private final UserFactory userFactory; private final AccessInfoService accessInfoService; - private final AccessInfoFactory accessInfoFactory; - private final PermissionFactory permissionFactory; private final SimpleSetting simpleSetting; private final String claimName; @@ -164,43 +153,30 @@ private static SimpleRegistrationProcessor.Settings applySimpleSettings(KapuaId * Create a new simple registration processor * * @param accountService - * @param accountFactory * @param credentialService - * @param credentialFactory * @param deviceRegistryService * @param userService - * @param userFactory * @param accessInfoService - * @param accessInfoFactory - * @param permissionFactory * @param simpleSetting - * @param claimName the claim to use as account name - * @param settings the settings for the processor + * @param claimName + * the claim to use as account name + * @param settings + * the settings for the processor */ public SimpleRegistrationProcessor( AccountService accountService, - AccountFactory accountFactory, CredentialService credentialService, - CredentialFactory credentialFactory, DeviceRegistryService deviceRegistryService, UserService userService, - UserFactory userFactory, AccessInfoService accessInfoService, - AccessInfoFactory accessInfoFactory, - PermissionFactory permissionFactory, SimpleSetting simpleSetting, String claimName, Settings settings) { this.accountService = accountService; - this.accountFactory = accountFactory; this.credentialService = credentialService; - this.credentialFactory = credentialFactory; this.deviceRegistryService = deviceRegistryService; this.userService = userService; - this.userFactory = userFactory; this.accessInfoService = accessInfoService; - this.accessInfoFactory = accessInfoFactory; - this.permissionFactory = permissionFactory; this.simpleSetting = simpleSetting; this.claimName = claimName; this.settings = settings; @@ -241,7 +217,7 @@ private Optional internalCreateUser(JwtContext context) throws Exception { // define account - AccountCreator accountCreator = accountFactory.newCreator(settings.getRootAccount()); + AccountCreator accountCreator = new AccountCreator(settings.getRootAccount()); accountCreator.setName(name); accountCreator.setOrganizationEmail(email); accountCreator.setOrganizationName(name); @@ -280,7 +256,7 @@ private User createUser(String name, String email, String displayName, String su // define - UserCreator userCreator = userFactory.newCreator(account.getId(), name); + UserCreator userCreator = new UserCreator(account.getId(), name); userCreator.setUserType(UserType.EXTERNAL); userCreator.setExternalId(subject); userCreator.setEmail(email); @@ -292,22 +268,22 @@ private User createUser(String name, String email, String displayName, String su // assign login permissions - AccessInfoCreator accessInfoCreator = accessInfoFactory.newCreator(user.getScopeId()); + AccessInfoCreator accessInfoCreator = new AccessInfoCreator(user.getScopeId()); accessInfoCreator.setUserId(user.getId()); Set permissions = new HashSet<>(); - permissions.add(permissionFactory.newPermission(Domains.ACCESS_INFO, Actions.read, user.getScopeId())); - - permissions.addAll(permissionFactory.newPermissions(Domains.ACCOUNT, user.getScopeId(), Actions.read)); - permissions.addAll(permissionFactory.newPermissions(Domains.CREDENTIAL, user.getScopeId(), Actions.read, Actions.write, Actions.delete)); - permissions.addAll(permissionFactory.newPermissions(Domains.DATASTORE, user.getScopeId(), Actions.read)); - permissions.addAll(permissionFactory.newPermissions(Domains.DEVICE, user.getScopeId(), Actions.read, Actions.write, Actions.delete)); - permissions.addAll(permissionFactory.newPermissions(Domains.DEVICE_CONNECTION, user.getScopeId(), Actions.read)); - permissions.addAll(permissionFactory.newPermissions(Domains.DEVICE_EVENT, user.getScopeId(), Actions.read, Actions.write)); - permissions.addAll(permissionFactory.newPermissions(Domains.DEVICE_MANAGEMENT, user.getScopeId(), Actions.read, Actions.write, Actions.execute)); - permissions.addAll(permissionFactory.newPermissions(Domains.GROUP, user.getScopeId(), Actions.read)); - permissions.addAll(permissionFactory.newPermissions(Domains.ROLE, user.getScopeId(), Actions.read)); - permissions.addAll(permissionFactory.newPermissions(Domains.USER, user.getScopeId(), Actions.read)); + permissions.add(new Permission(Domains.ACCESS_INFO, Actions.read, user.getScopeId())); + + permissions.addAll(Permission.newPermissions(Domains.ACCOUNT, user.getScopeId(), Actions.read)); + permissions.addAll(Permission.newPermissions(Domains.CREDENTIAL, user.getScopeId(), Actions.read, Actions.write, Actions.delete)); + permissions.addAll(Permission.newPermissions(Domains.DATASTORE, user.getScopeId(), Actions.read)); + permissions.addAll(Permission.newPermissions(Domains.DEVICE, user.getScopeId(), Actions.read, Actions.write, Actions.delete)); + permissions.addAll(Permission.newPermissions(Domains.DEVICE_CONNECTION, user.getScopeId(), Actions.read)); + permissions.addAll(Permission.newPermissions(Domains.DEVICE_EVENT, user.getScopeId(), Actions.read, Actions.write)); + permissions.addAll(Permission.newPermissions(Domains.DEVICE_MANAGEMENT, user.getScopeId(), Actions.read, Actions.write, Actions.execute)); + permissions.addAll(Permission.newPermissions(Domains.GROUP, user.getScopeId(), Actions.read)); + permissions.addAll(Permission.newPermissions(Domains.ROLE, user.getScopeId(), Actions.read)); + permissions.addAll(Permission.newPermissions(Domains.USER, user.getScopeId(), Actions.read)); accessInfoCreator.setPermissions(permissions); @@ -322,7 +298,7 @@ private User createBrokerUser(String baseName, Account account) throws KapuaExce // define - UserCreator userCreator = userFactory.newCreator(account.getId(), baseName + "-broker"); + UserCreator userCreator = new UserCreator(account.getId(), baseName + "-broker"); userCreator.setUserType(UserType.INTERNAL); // FIXME: need to find out why this isn't DEVICE but INTERNAL userCreator.setDisplayName("Gateway User"); @@ -332,11 +308,11 @@ private User createBrokerUser(String baseName, Account account) throws KapuaExce // assign permissions - AccessInfoCreator accessInfoCreator = accessInfoFactory.newCreator(user.getScopeId()); + AccessInfoCreator accessInfoCreator = new AccessInfoCreator(user.getScopeId()); accessInfoCreator.setUserId(user.getId()); Set permissions = new HashSet<>(); - permissions.add(permissionFactory.newPermission(Domains.BROKER, Actions.connect, user.getScopeId())); + permissions.add(new Permission(Domains.BROKER, Actions.connect, user.getScopeId())); accessInfoCreator.setPermissions(permissions); @@ -344,7 +320,7 @@ private User createBrokerUser(String baseName, Account account) throws KapuaExce // Create default password - CredentialCreator credential = credentialFactory.newCreator(account.getId(), user.getId(), "PASSWORD", baseName + "-Password1!", CredentialStatus.ENABLED, null); + CredentialCreator credential = new CredentialCreator(account.getId(), user.getId(), "PASSWORD", baseName + "-Password1!", CredentialStatus.ENABLED, null); credentialService.create(credential); return user; diff --git a/service/security/registration/simple/src/main/java/org/eclipse/kapua/security/registration/simple/SimpleRegistrationProcessorProvider.java b/service/security/registration/simple/src/main/java/org/eclipse/kapua/security/registration/simple/SimpleRegistrationProcessorProvider.java index 26ea71350e6..f2160532e2a 100644 --- a/service/security/registration/simple/src/main/java/org/eclipse/kapua/security/registration/simple/SimpleRegistrationProcessorProvider.java +++ b/service/security/registration/simple/src/main/java/org/eclipse/kapua/security/registration/simple/SimpleRegistrationProcessorProvider.java @@ -12,64 +12,45 @@ *******************************************************************************/ package org.eclipse.kapua.security.registration.simple; +import java.util.Collections; +import java.util.Optional; +import java.util.Set; + +import javax.inject.Inject; + import org.eclipse.kapua.security.registration.RegistrationProcessor; import org.eclipse.kapua.security.registration.RegistrationProcessorProvider; import org.eclipse.kapua.security.registration.simple.SimpleRegistrationProcessor.Settings; import org.eclipse.kapua.security.registration.simple.setting.SimpleSetting; -import org.eclipse.kapua.service.account.AccountFactory; import org.eclipse.kapua.service.account.AccountService; -import org.eclipse.kapua.service.authentication.credential.CredentialFactory; import org.eclipse.kapua.service.authentication.credential.CredentialService; -import org.eclipse.kapua.service.authorization.access.AccessInfoFactory; import org.eclipse.kapua.service.authorization.access.AccessInfoService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; import org.eclipse.kapua.service.device.registry.DeviceRegistryService; -import org.eclipse.kapua.service.user.UserFactory; import org.eclipse.kapua.service.user.UserService; -import javax.inject.Inject; -import java.util.Collections; -import java.util.Optional; -import java.util.Set; - public class SimpleRegistrationProcessorProvider implements RegistrationProcessorProvider { private final SimpleSetting simpleSetting; private final AccountService accountService; - private final AccountFactory accountFactory; private final CredentialService credentialService; - private final CredentialFactory credentialFactory; private final DeviceRegistryService deviceRegistryService; private final UserService userService; - private final UserFactory userFactory; private final AccessInfoService accessInfoService; - private final AccessInfoFactory accessInfoFactory; - private final PermissionFactory permissionFactory; @Inject public SimpleRegistrationProcessorProvider( SimpleSetting simpleSetting, AccountService accountService, - AccountFactory accountFactory, CredentialService credentialService, - CredentialFactory credentialFactory, DeviceRegistryService deviceRegistryService, UserService userService, - UserFactory userFactory, - AccessInfoService accessInfoService, - AccessInfoFactory accessInfoFactory, - PermissionFactory permissionFactory) { + AccessInfoService accessInfoService) { this.simpleSetting = simpleSetting; this.accountService = accountService; - this.accountFactory = accountFactory; this.credentialService = credentialService; - this.credentialFactory = credentialFactory; this.deviceRegistryService = deviceRegistryService; this.userService = userService; - this.userFactory = userFactory; this.accessInfoService = accessInfoService; - this.accessInfoFactory = accessInfoFactory; - this.permissionFactory = permissionFactory; } @Override @@ -78,15 +59,10 @@ public Set createAll() { return result .map(settings -> new SimpleRegistrationProcessor( accountService, - accountFactory, credentialService, - credentialFactory, deviceRegistryService, userService, - userFactory, accessInfoService, - accessInfoFactory, - permissionFactory, simpleSetting, "preferred_username", settings)) diff --git a/service/security/shiro/pom.xml b/service/security/shiro/pom.xml index e763f31fff0..973d22c899f 100644 --- a/service/security/shiro/pom.xml +++ b/service/security/shiro/pom.xml @@ -19,7 +19,7 @@ org.eclipse.kapua kapua-security - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-security-shiro diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/shiro/MfaOptionCreatorImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/shiro/MfaOptionCreatorImpl.java deleted file mode 100644 index a3a0fd9c6ab..00000000000 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/shiro/MfaOptionCreatorImpl.java +++ /dev/null @@ -1,54 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2020, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authentication.credential.mfa.shiro; - -import org.eclipse.kapua.commons.model.AbstractKapuaEntityCreator; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.authentication.credential.mfa.MfaOption; -import org.eclipse.kapua.service.authentication.credential.mfa.MfaOptionCreator; - -/** - * {@link MfaOption} creator implementation. - */ -public class MfaOptionCreatorImpl extends AbstractKapuaEntityCreator implements MfaOptionCreator { - - private static final long serialVersionUID = -4619585500941519330L; - - private KapuaId userId; - - /** - * Constructor - * - * @param scopeId scope identifier - * @param userId user identifier - */ - public MfaOptionCreatorImpl(KapuaId scopeId, KapuaId userId) { - super(scopeId); - this.userId = userId; - } - - public MfaOptionCreatorImpl(KapuaId scopeId) { - super(scopeId); - } - - @Override - public KapuaId getUserId() { - return userId; - } - - @Override - public void setUserId(KapuaId userId) { - this.userId = userId; - } - -} diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/shiro/MfaOptionFactoryImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/shiro/MfaOptionFactoryImpl.java index 71466810c72..2bbbedadbc3 100644 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/shiro/MfaOptionFactoryImpl.java +++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/shiro/MfaOptionFactoryImpl.java @@ -12,15 +12,12 @@ *******************************************************************************/ package org.eclipse.kapua.service.authentication.credential.mfa.shiro; +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaEntityCloneException; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.authentication.credential.mfa.MfaOption; -import org.eclipse.kapua.service.authentication.credential.mfa.MfaOptionCreator; import org.eclipse.kapua.service.authentication.credential.mfa.MfaOptionFactory; -import org.eclipse.kapua.service.authentication.credential.mfa.MfaOptionListResult; -import org.eclipse.kapua.service.authentication.credential.mfa.MfaOptionQuery; - -import javax.inject.Singleton; /** * {@link MfaOptionFactory} implementation. @@ -28,26 +25,11 @@ @Singleton public class MfaOptionFactoryImpl implements MfaOptionFactory { - @Override - public MfaOptionListResult newListResult() { - return new MfaOptionListResultImpl(); - } - @Override public MfaOption newEntity(KapuaId scopeId) { return new MfaOptionImpl(scopeId); } - @Override - public MfaOptionQuery newQuery(KapuaId scopeId) { - return new MfaOptionQueryImpl(scopeId); - } - - @Override - public MfaOptionCreator newCreator(KapuaId scopeId) { - return new MfaOptionCreatorImpl(scopeId); - } - @Override public MfaOption clone(MfaOption mfaOption) { try { @@ -56,11 +38,4 @@ public MfaOption clone(MfaOption mfaOption) { throw new KapuaEntityCloneException(e, MfaOption.TYPE, mfaOption); } } - - @Override - public MfaOptionCreator newCreator(KapuaId scopeId, KapuaId userId) { - final MfaOptionCreatorImpl res = new MfaOptionCreatorImpl(scopeId); - res.setUserId(userId); - return res; - } } diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/shiro/MfaOptionImplJpaRepository.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/shiro/MfaOptionImplJpaRepository.java index 653f0cd1091..450d8487558 100644 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/shiro/MfaOptionImplJpaRepository.java +++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/shiro/MfaOptionImplJpaRepository.java @@ -27,8 +27,9 @@ public class MfaOptionImplJpaRepository extends KapuaUpdatableEntityJpaRepository implements MfaOptionRepository { + public MfaOptionImplJpaRepository(KapuaJpaRepositoryConfiguration jpaRepoConfig) { - super(MfaOptionImpl.class, MfaOption.TYPE, MfaOptionListResultImpl::new, jpaRepoConfig); + super(MfaOptionImpl.class, MfaOption.TYPE, MfaOptionListResult::new, jpaRepoConfig); } @Override diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/shiro/MfaOptionListResultImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/shiro/MfaOptionListResultImpl.java deleted file mode 100644 index ec3582158ac..00000000000 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/shiro/MfaOptionListResultImpl.java +++ /dev/null @@ -1,25 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2020, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authentication.credential.mfa.shiro; - -import org.eclipse.kapua.commons.model.query.KapuaListResultImpl; -import org.eclipse.kapua.service.authentication.credential.mfa.MfaOption; -import org.eclipse.kapua.service.authentication.credential.mfa.MfaOptionListResult; - -/** - * {@link MfaOption} list result implementation. - */ -public class MfaOptionListResultImpl extends KapuaListResultImpl implements MfaOptionListResult { - - private static final long serialVersionUID = -4204695192086365901L; -} diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/shiro/MfaOptionQueryImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/shiro/MfaOptionQueryImpl.java deleted file mode 100644 index e1a52d227b0..00000000000 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/shiro/MfaOptionQueryImpl.java +++ /dev/null @@ -1,46 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2020, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authentication.credential.mfa.shiro; - -import org.eclipse.kapua.commons.model.query.AbstractKapuaQuery; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.authentication.credential.mfa.MfaOption; -import org.eclipse.kapua.service.authentication.credential.mfa.MfaOptionQuery; - -/** - * {@link MfaOption} query implementation. - * - * @since 1.3.0 - */ -public class MfaOptionQueryImpl extends AbstractKapuaQuery implements MfaOptionQuery { - - /** - * Constructor. - * - * @since 1.3.0 - */ - public MfaOptionQueryImpl() { - super(); - } - - /** - * Constructor. - * - * @param scopeId The {@link #getScopeId()}. - * @since 1.3.0 - */ - public MfaOptionQueryImpl(KapuaId scopeId) { - this(); - setScopeId(scopeId); - } -} diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/shiro/MfaOptionServiceImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/shiro/MfaOptionServiceImpl.java index e12a28124c0..a7fbd8227ae 100644 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/shiro/MfaOptionServiceImpl.java +++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/shiro/MfaOptionServiceImpl.java @@ -56,7 +56,7 @@ import org.eclipse.kapua.service.authorization.AuthorizationService; import org.eclipse.kapua.service.authorization.exception.InternalUserOnlyException; import org.eclipse.kapua.service.authorization.exception.SelfManagedOnlyException; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; +import org.eclipse.kapua.service.authorization.permission.Permission; import org.eclipse.kapua.service.user.User; import org.eclipse.kapua.service.user.UserService; import org.eclipse.kapua.service.user.UserType; @@ -82,7 +82,6 @@ public class MfaOptionServiceImpl implements MfaOptionService { private final AccountService accountService; private final ScratchCodeRepository scratchCodeRepository; private final AuthorizationService authorizationService; - private final PermissionFactory permissionFactory; private final UserService userService; private final AuthenticationUtils authenticationUtils; private final QRCodeBuilder qrCodeBuilder; @@ -94,7 +93,6 @@ public MfaOptionServiceImpl( AccountService accountService, ScratchCodeRepository scratchCodeRepository, AuthorizationService authorizationService, - PermissionFactory permissionFactory, UserService userService, AuthenticationUtils authenticationUtils, QRCodeBuilder qrCodeBuilder) { this.trustKeyDuration = trustKeyDuration; @@ -104,7 +102,6 @@ public MfaOptionServiceImpl( this.accountService = accountService; this.scratchCodeRepository = scratchCodeRepository; this.authorizationService = authorizationService; - this.permissionFactory = permissionFactory; this.userService = userService; this.authenticationUtils = authenticationUtils; this.qrCodeBuilder = qrCodeBuilder; @@ -117,7 +114,7 @@ public MfaOption create(final MfaOptionCreator mfaOptionCreator) throws KapuaExc ArgumentValidator.notNull(mfaOptionCreator.getScopeId(), "mfaOptionCreator.scopeId"); ArgumentValidator.notNull(mfaOptionCreator.getUserId(), "mfaOptionCreator.userId"); // Check access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.CREDENTIAL, Actions.write, mfaOptionCreator.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.CREDENTIAL, Actions.write, mfaOptionCreator.getScopeId())); // Check that the operation is carried by the user itself final KapuaSession session = KapuaSecurityUtils.getSession(); final KapuaId expectedUser = session.getUserId(); @@ -178,9 +175,8 @@ private User fetchUser(MfaOptionCreator mfaOptionCreator) throws KapuaException } /** - * Generates all the scratch codes. - * The number of generated scratch codes is decided through the {@link org.eclipse.kapua.service.authentication.mfa.MfaAuthenticator} service. - * The scratch code provided within the scratchCodeCreator parameter is ignored. + * Generates all the scratch codes. The number of generated scratch codes is decided through the {@link org.eclipse.kapua.service.authentication.mfa.MfaAuthenticator} service. The scratch code + * provided within the scratchCodeCreator parameter is ignored. * * @return * @throws KapuaException @@ -213,7 +209,7 @@ public MfaOption find(KapuaId scopeId, KapuaId mfaOptionId) throws KapuaExceptio ArgumentValidator.notNull(scopeId, KapuaEntityAttributes.SCOPE_ID); ArgumentValidator.notNull(mfaOptionId, "mfaOptionId"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.CREDENTIAL, Actions.read, scopeId)); + authorizationService.checkPermission(new Permission(Domains.CREDENTIAL, Actions.read, scopeId)); return txManager.execute(tx -> mfaOptionRepository.find(tx, scopeId, mfaOptionId)) .map(this::clearSecuritySensibleFields) @@ -221,7 +217,7 @@ public MfaOption find(KapuaId scopeId, KapuaId mfaOptionId) throws KapuaExceptio } private MfaOption clearSecuritySensibleFields(MfaOption mfaOption) { -// Set the mfa secret key to null before returning the mfaOption, because they should never be seen again + // Set the mfa secret key to null before returning the mfaOption, because they should never be seen again mfaOption.setMfaSecretKey(null); mfaOption.setTrustKey(null); mfaOption.setScratchCodes(null); @@ -234,11 +230,11 @@ public MfaOptionListResult query(KapuaQuery query) throws KapuaException { // Argument Validation ArgumentValidator.notNull(query, "query"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.CREDENTIAL, Actions.read, query.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.CREDENTIAL, Actions.read, query.getScopeId())); final MfaOptionListResult res = txManager.execute(tx -> mfaOptionRepository.query(tx, query)); if (res.isEmpty() == false) { - final MfaOptionListResultImpl cleanedRes = new MfaOptionListResultImpl(); + final MfaOptionListResult cleanedRes = new MfaOptionListResult(); cleanedRes.setLimitExceeded(res.isLimitExceeded()); cleanedRes.setTotalCount(res.getTotalCount()); cleanedRes.addItems(res.getItems() @@ -255,7 +251,7 @@ public long count(KapuaQuery query) throws KapuaException { // Argument Validation ArgumentValidator.notNull(query, "query"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.CREDENTIAL, Actions.read, query.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.CREDENTIAL, Actions.read, query.getScopeId())); return txManager.execute(tx -> mfaOptionRepository.count(tx, query)); } @@ -266,7 +262,7 @@ public void delete(KapuaId scopeId, KapuaId mfaOptionId) throws KapuaException { ArgumentValidator.notNull(mfaOptionId, "mfaOptionId"); ArgumentValidator.notNull(scopeId, "scopeId"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.CREDENTIAL, Actions.delete, scopeId)); + authorizationService.checkPermission(new Permission(Domains.CREDENTIAL, Actions.delete, scopeId)); txManager.execute(tx -> mfaOptionRepository.delete(tx, scopeId, mfaOptionId)); } @@ -277,7 +273,7 @@ public void deleteByUserId(KapuaId scopeId, KapuaId userId) throws KapuaExceptio ArgumentValidator.notNull(scopeId, "scopeId"); ArgumentValidator.notNull(userId, "userId"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.CREDENTIAL, Actions.delete, scopeId)); + authorizationService.checkPermission(new Permission(Domains.CREDENTIAL, Actions.delete, scopeId)); txManager.execute(tx -> mfaOptionRepository .findByUserId(tx, scopeId, userId) @@ -395,7 +391,7 @@ public MfaOption findByUserId(KapuaId scopeId, KapuaId userId) throws KapuaExcep ArgumentValidator.notNull(scopeId, KapuaEntityAttributes.SCOPE_ID); ArgumentValidator.notNull(userId, MfaOptionAttributes.USER_ID); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.CREDENTIAL, Actions.read, scopeId)); + authorizationService.checkPermission(new Permission(Domains.CREDENTIAL, Actions.read, scopeId)); return txManager.execute(tx -> mfaOptionRepository.findByUserId(tx, scopeId, userId)) .map(this::clearSecuritySensibleFields) @@ -408,8 +404,8 @@ public String enableTrust(KapuaId scopeId, KapuaId userId) throws KapuaException ArgumentValidator.notNull(scopeId, "scopeId"); ArgumentValidator.notNull(userId, "userId"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.CREDENTIAL, Actions.read, scopeId)); - authorizationService.checkPermission(permissionFactory.newPermission(Domains.CREDENTIAL, Actions.write, scopeId)); + authorizationService.checkPermission(new Permission(Domains.CREDENTIAL, Actions.read, scopeId)); + authorizationService.checkPermission(new Permission(Domains.CREDENTIAL, Actions.write, scopeId)); return txManager.execute(tx -> { // Checking existence @@ -438,7 +434,7 @@ public void disableTrust(KapuaId scopeId, KapuaId mfaOptionId) throws KapuaExcep // Argument Validation ArgumentValidator.notNull(mfaOptionId, "mfaOptionId"); ArgumentValidator.notNull(scopeId, "scopeId"); - authorizationService.checkPermission(permissionFactory.newPermission(Domains.CREDENTIAL, Actions.write, scopeId)); + authorizationService.checkPermission(new Permission(Domains.CREDENTIAL, Actions.write, scopeId)); txManager.execute(tx -> { // extracting the MfaOption MfaOption mfaOption = mfaOptionRepository.find(tx, scopeId, mfaOptionId) @@ -471,7 +467,6 @@ private MfaOption doDisableTrust(TxContext tx, MfaOption mfaOption) throws Kapua return mfaOptionRepository.update(tx, mfaOption); } - /** * Generate the trust key string. * @@ -483,13 +478,17 @@ private String generateTrustKey() { } /** - * Produce a QR code in base64 format for the authenticator app. - * This QR code generator follows the spec detailed here for the URI format: https://github.com/google/google-authenticator/wiki/Key-Uri-Format + * Produce a QR code in base64 format for the authenticator app. This QR code generator follows the spec detailed here for the URI format: + * https://github.com/google/google-authenticator/wiki/Key-Uri-Format * - * @param organizationName the organization name to be used as issuer in the QR code - * @param accountName the account name of the account to which the user belongs - * @param username the username - * @param key the Mfa secret key in plain text + * @param organizationName + * the organization name to be used as issuer in the QR code + * @param accountName + * the account name of the account to which the user belongs + * @param username + * the username + * @param key + * the Mfa secret key in plain text * @return the QR code image in base64 format * @since 1.3.0 */ diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/shiro/ScratchCodeFactoryImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/shiro/ScratchCodeFactoryImpl.java index 2e0dfd6f57d..a3fc3c2874e 100644 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/shiro/ScratchCodeFactoryImpl.java +++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/shiro/ScratchCodeFactoryImpl.java @@ -12,12 +12,11 @@ *******************************************************************************/ package org.eclipse.kapua.service.authentication.credential.mfa.shiro; +import javax.inject.Singleton; + import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.authentication.credential.mfa.ScratchCode; import org.eclipse.kapua.service.authentication.credential.mfa.ScratchCodeFactory; -import org.eclipse.kapua.service.authentication.credential.mfa.ScratchCodeListResult; - -import javax.inject.Singleton; /** * {@link ScratchCodeFactory} implementation. @@ -30,11 +29,6 @@ public ScratchCode newEntity(KapuaId scopeId) { return new ScratchCodeImpl(scopeId); } - @Override - public ScratchCodeListResult newListResult() { - return new ScratchCodeListResultImpl(); - } - @Override public ScratchCode newScratchCode(KapuaId scopeId, KapuaId mfaOptionId, String code) { return new ScratchCodeImpl(scopeId, mfaOptionId, code); diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/shiro/ScratchCodeImplJpaRepository.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/shiro/ScratchCodeImplJpaRepository.java index 5f7ff836690..aa3a1251be0 100644 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/shiro/ScratchCodeImplJpaRepository.java +++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/shiro/ScratchCodeImplJpaRepository.java @@ -26,7 +26,7 @@ public class ScratchCodeImplJpaRepository implements ScratchCodeRepository { public ScratchCodeImplJpaRepository(KapuaJpaRepositoryConfiguration jpaRepoConfig) { - super(ScratchCodeImpl.class, ScratchCode.TYPE, () -> new ScratchCodeListResultImpl(), jpaRepoConfig); + super(ScratchCodeImpl.class, ScratchCode.TYPE, () -> new ScratchCodeListResult(), jpaRepoConfig); } @Override diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/shiro/ScratchCodeListResultImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/shiro/ScratchCodeListResultImpl.java deleted file mode 100644 index fc5133dc0dd..00000000000 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/shiro/ScratchCodeListResultImpl.java +++ /dev/null @@ -1,25 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2020, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authentication.credential.mfa.shiro; - -import org.eclipse.kapua.commons.model.query.KapuaListResultImpl; -import org.eclipse.kapua.service.authentication.credential.mfa.ScratchCode; -import org.eclipse.kapua.service.authentication.credential.mfa.ScratchCodeListResult; - -/** - * {@link ScratchCode} list result implementation. - */ -public class ScratchCodeListResultImpl extends KapuaListResultImpl implements ScratchCodeListResult { - - private static final long serialVersionUID = -5154461760797879319L; -} diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/shiro/ScratchCodeServiceImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/shiro/ScratchCodeServiceImpl.java index a460dad2a4b..5fc2e8053a8 100644 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/shiro/ScratchCodeServiceImpl.java +++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/mfa/shiro/ScratchCodeServiceImpl.java @@ -12,6 +12,8 @@ *******************************************************************************/ package org.eclipse.kapua.service.authentication.credential.mfa.shiro; +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.commons.model.domains.Domains; import org.eclipse.kapua.commons.util.ArgumentValidator; @@ -22,13 +24,11 @@ import org.eclipse.kapua.service.authentication.credential.mfa.ScratchCodeRepository; import org.eclipse.kapua.service.authentication.credential.mfa.ScratchCodeService; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; +import org.eclipse.kapua.service.authorization.permission.Permission; import org.eclipse.kapua.storage.TxManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.inject.Singleton; - /** * {@link ScratchCodeService} implementation. */ @@ -39,17 +39,14 @@ public class ScratchCodeServiceImpl implements ScratchCodeService { private final TxManager txManager; private final ScratchCodeRepository scratchCodeRepository; private final AuthorizationService authorizationService; - private final PermissionFactory permissionFactory; public ScratchCodeServiceImpl( AuthorizationService authorizationService, - PermissionFactory permissionFactory, TxManager txManager, ScratchCodeRepository scratchCodeRepository) { this.txManager = txManager; this.scratchCodeRepository = scratchCodeRepository; this.authorizationService = authorizationService; - this.permissionFactory = permissionFactory; } @Override @@ -58,7 +55,7 @@ public ScratchCodeListResult findByMfaOptionId(KapuaId scopeId, KapuaId mfaOptio ArgumentValidator.notNull(scopeId, KapuaEntityAttributes.SCOPE_ID); ArgumentValidator.notNull(mfaOptionId, ScratchCodeImpl_.MFA_OPTION_ID); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.CREDENTIAL, Actions.read, scopeId)); + authorizationService.checkPermission(new Permission(Domains.CREDENTIAL, Actions.read, scopeId)); return txManager.execute(tx -> scratchCodeRepository.findByMfaOptionId(tx, scopeId, mfaOptionId)); } @@ -69,7 +66,7 @@ public void delete(KapuaId scopeId, KapuaId scratchCodeId) throws KapuaException ArgumentValidator.notNull(scopeId, "scratchCode.scopeId"); ArgumentValidator.notNull(scratchCodeId, "scratchCode.id"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.CREDENTIAL, Actions.delete, scopeId)); + authorizationService.checkPermission(new Permission(Domains.CREDENTIAL, Actions.delete, scopeId)); txManager.execute(tx -> scratchCodeRepository.delete(tx, scopeId, scratchCodeId)); } diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/shiro/CredentialCreatorImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/shiro/CredentialCreatorImpl.java deleted file mode 100644 index a821cc05d8f..00000000000 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/shiro/CredentialCreatorImpl.java +++ /dev/null @@ -1,127 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authentication.credential.shiro; - -import org.eclipse.kapua.commons.model.AbstractKapuaEntityCreator; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.authentication.credential.Credential; -import org.eclipse.kapua.service.authentication.credential.CredentialCreator; -import org.eclipse.kapua.service.authentication.credential.CredentialStatus; - -import java.util.Date; - -/** - * {@link CredentialCreator} implementation. - * - * @since 1.0.0 - */ -public class CredentialCreatorImpl extends AbstractKapuaEntityCreator implements CredentialCreator { - - private static final long serialVersionUID = -5020680413729882095L; - - private KapuaId userId; - private String credentialType; - private String credentialKey; - private Date expirationDate; - private CredentialStatus credentialStatus; - - /** - * Constructor. - * - * @param scopeId - * The {@link CredentialCreator#getScopeId()} - * @param userId - * The {@link CredentialCreator#getUserId()} - * @param credentialType - * The {@link CredentialCreator#getCredentialType()} - * @param credentialKey - * The plain {@link CredentialCreator#getCredentialPlainKey()} - * @param credentialStatus - * The {@link CredentialCreator#getCredentialStatus()} - * @param expirationDate - * The {@link CredentialCreator#getExpirationDate()} - * @since 1.0.0 - */ - public CredentialCreatorImpl(KapuaId scopeId, - KapuaId userId, - String credentialType, - String credentialKey, - CredentialStatus credentialStatus, - Date expirationDate) { - super(scopeId); - - this.userId = userId; - this.credentialType = credentialType; - this.credentialKey = credentialKey; - this.credentialStatus = credentialStatus; - this.expirationDate = expirationDate; - } - - /** - * Constructor. - * - * @param scopeId The {@link CredentialCreator#getScopeId()} - * @since 1.0.0 - */ - public CredentialCreatorImpl(KapuaId scopeId) { - super(scopeId); - } - - @Override - public KapuaId getUserId() { - return userId; - } - - public void setUserId(KapuaId userId) { - this.userId = userId; - } - - @Override - public String getCredentialType() { - return credentialType; - } - - public void setCredentialType(String credentialType) { - this.credentialType = credentialType; - } - - @Override - public String getCredentialPlainKey() { - return credentialKey; - } - - @Override - public void setCredentialPlainKey(String credentialKey) { - this.credentialKey = credentialKey; - } - - @Override - public Date getExpirationDate() { - return expirationDate; - } - - @Override - public void setExpirationDate(Date expirationDate) { - this.expirationDate = expirationDate; - } - - @Override - public CredentialStatus getCredentialStatus() { - return credentialStatus; - } - - @Override - public void setCredentialStatus(CredentialStatus credentialStatus) { - this.credentialStatus = credentialStatus; - } -} diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/shiro/CredentialFactoryImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/shiro/CredentialFactoryImpl.java index 0aeb713afb7..e5bc0c40154 100644 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/shiro/CredentialFactoryImpl.java +++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/shiro/CredentialFactoryImpl.java @@ -12,18 +12,16 @@ *******************************************************************************/ package org.eclipse.kapua.service.authentication.credential.shiro; +import java.util.Date; + +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaEntityCloneException; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.authentication.credential.Credential; -import org.eclipse.kapua.service.authentication.credential.CredentialCreator; import org.eclipse.kapua.service.authentication.credential.CredentialFactory; -import org.eclipse.kapua.service.authentication.credential.CredentialListResult; -import org.eclipse.kapua.service.authentication.credential.CredentialQuery; import org.eclipse.kapua.service.authentication.credential.CredentialStatus; -import javax.inject.Singleton; -import java.util.Date; - /** * {@link CredentialFactory} implementation. * @@ -32,37 +30,15 @@ @Singleton public class CredentialFactoryImpl implements CredentialFactory { - @Override - public CredentialCreatorImpl newCreator(KapuaId scopeId, KapuaId userId, String credentialType, String credentialKey, CredentialStatus credentialStatus, Date expirationDate) { - return new CredentialCreatorImpl(scopeId, userId, credentialType, credentialKey, credentialStatus, expirationDate); - } - - @Override - public CredentialListResult newListResult() { - return new CredentialListResultImpl(); - } - @Override public Credential newEntity(KapuaId scopeId) { return new CredentialImpl(scopeId); } - @Override public Credential newCredential(KapuaId scopeId, KapuaId userId, String credentialType, String credentialKey, CredentialStatus credentialStatus, Date expirationDate) { return new CredentialImpl(scopeId, userId, credentialType, credentialKey, credentialStatus, expirationDate); } - @Override - public CredentialQuery newQuery(KapuaId scopeId) { - return new CredentialQueryImpl(scopeId); - } - - @Override - public CredentialCreator newCreator(KapuaId scopeId) { - return new CredentialCreatorImpl(scopeId); - } - - @Override public Credential clone(Credential credential) { try { diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/shiro/CredentialImplJpaRepository.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/shiro/CredentialImplJpaRepository.java index f851f1b30ff..af27a73cacd 100644 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/shiro/CredentialImplJpaRepository.java +++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/shiro/CredentialImplJpaRepository.java @@ -33,11 +33,12 @@ public class CredentialImplJpaRepository /** * Constructor. * - * @param jpaRepoConfig The {@link KapuaJpaRepositoryConfiguration}. + * @param jpaRepoConfig + * The {@link KapuaJpaRepositoryConfiguration}. * @since 2.0.0 */ public CredentialImplJpaRepository(KapuaJpaRepositoryConfiguration jpaRepoConfig) { - super(CredentialImpl.class, Credential.TYPE, CredentialListResultImpl::new, jpaRepoConfig); + super(CredentialImpl.class, Credential.TYPE, CredentialListResult::new, jpaRepoConfig); } @Override diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/shiro/CredentialListResultImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/shiro/CredentialListResultImpl.java deleted file mode 100644 index 28a039e71c5..00000000000 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/shiro/CredentialListResultImpl.java +++ /dev/null @@ -1,28 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authentication.credential.shiro; - -import org.eclipse.kapua.commons.model.query.KapuaListResultImpl; -import org.eclipse.kapua.service.authentication.credential.Credential; -import org.eclipse.kapua.service.authentication.credential.CredentialListResult; - -/** - * {@link CredentialListResult} implementation. - * - * @since 1.0.0 - */ -public class CredentialListResultImpl extends KapuaListResultImpl implements CredentialListResult { - - static final long serialVersionUID = -7949012585401032274L; - -} diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/shiro/CredentialQueryImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/shiro/CredentialQueryImpl.java deleted file mode 100644 index 43a4cd87e62..00000000000 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/shiro/CredentialQueryImpl.java +++ /dev/null @@ -1,44 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authentication.credential.shiro; - -import org.eclipse.kapua.commons.model.query.AbstractKapuaQuery; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.authentication.credential.CredentialQuery; - -/** - * {@link CredentialQuery} implementation. - * - * @since 1.0.0 - */ -public class CredentialQueryImpl extends AbstractKapuaQuery implements CredentialQuery { - - /** - * Constructor. - * - * @since 1.0.0 - */ - public CredentialQueryImpl() { - super(); - } - - /** - * Constructor. - * - * @param scopeId The {@link #getScopeId()}. - * @since 1.0.0 - */ - public CredentialQueryImpl(KapuaId scopeId) { - super(scopeId); - } -} diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/shiro/CredentialServiceImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/shiro/CredentialServiceImpl.java index 27f1258810a..9e61dfac11b 100644 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/shiro/CredentialServiceImpl.java +++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/shiro/CredentialServiceImpl.java @@ -42,7 +42,6 @@ import org.eclipse.kapua.service.authentication.credential.CredentialCreator; import org.eclipse.kapua.service.authentication.credential.CredentialFactory; import org.eclipse.kapua.service.authentication.credential.CredentialListResult; -import org.eclipse.kapua.service.authentication.credential.CredentialQuery; import org.eclipse.kapua.service.authentication.credential.CredentialRepository; import org.eclipse.kapua.service.authentication.credential.CredentialService; import org.eclipse.kapua.service.authentication.credential.handler.CredentialTypeHandler; @@ -50,7 +49,7 @@ import org.eclipse.kapua.service.authentication.shiro.setting.KapuaAuthenticationSettingKeys; import org.eclipse.kapua.service.authentication.user.PasswordResetRequest; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; +import org.eclipse.kapua.service.authorization.permission.Permission; import org.eclipse.kapua.storage.TxManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -67,7 +66,6 @@ public class CredentialServiceImpl extends KapuaConfigurableServiceBase implemen private SecureRandom random; private final CredentialRepository credentialRepository; - private final CredentialFactory credentialFactory; private final KapuaAuthenticationSetting kapuaAuthenticationSetting; private final AccountPasswordLengthProvider accountPasswordLengthProvider; private final PasswordValidator passwordValidator; @@ -78,7 +76,6 @@ public class CredentialServiceImpl extends KapuaConfigurableServiceBase implemen public CredentialServiceImpl( ServiceConfigurationManager serviceConfigurationManager, AuthorizationService authorizationService, - PermissionFactory permissionFactory, TxManager txManager, CredentialRepository credentialRepository, CredentialFactory credentialFactory, @@ -87,10 +84,9 @@ public CredentialServiceImpl( Set availableCredentialAuthenticationType, AccountPasswordLengthProvider accountPasswordLengthProvider, PasswordResetter passwordResetter) { - super(txManager, serviceConfigurationManager, Domains.CREDENTIAL, authorizationService, permissionFactory); + super(txManager, serviceConfigurationManager, Domains.CREDENTIAL, authorizationService); this.credentialRepository = credentialRepository; - this.credentialFactory = credentialFactory; this.kapuaAuthenticationSetting = kapuaAuthenticationSetting; this.accountPasswordLengthProvider = accountPasswordLengthProvider; this.passwordResetter = passwordResetter; @@ -122,7 +118,7 @@ public Credential create(CredentialCreator credentialCreator) credentialTypeHandler.validateCreator(credentialCreator); // Check access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.CREDENTIAL, Actions.write, credentialCreator.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.CREDENTIAL, Actions.write, credentialCreator.getScopeId())); final AtomicReference plainKey = new AtomicReference<>(null); @@ -170,7 +166,7 @@ public Credential update(Credential credential) ArgumentValidator.notNull(credential.getCredentialType(), "credential.credentialType"); // Check access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.CREDENTIAL, Actions.write, credential.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.CREDENTIAL, Actions.write, credential.getScopeId())); final Credential updatedCredential = txManager.execute(tx -> { Credential currentCredential = credentialRepository.find(tx, credential.getScopeId(), credential.getId()) @@ -182,7 +178,7 @@ public Credential update(Credential credential) // Some fields must be updated only by admin users if (tryEditAdminFields(credential, currentCredential)) { - authorizationService.checkPermission(permissionFactory.newPermission(Domains.CREDENTIAL, Actions.write, null)); + authorizationService.checkPermission(new Permission(Domains.CREDENTIAL, Actions.write, null)); } // Passing attributes?? @@ -199,7 +195,7 @@ public Credential find(KapuaId scopeId, KapuaId credentialId) ArgumentValidator.notNull(scopeId, KapuaEntityAttributes.SCOPE_ID); ArgumentValidator.notNull(credentialId, "credentialId"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.CREDENTIAL, Actions.read, scopeId)); + authorizationService.checkPermission(new Permission(Domains.CREDENTIAL, Actions.read, scopeId)); return txManager.execute(tx -> credentialRepository.find(tx, scopeId, credentialId)) .map(cred -> { @@ -215,7 +211,7 @@ public CredentialListResult query(KapuaQuery query) // Argument Validation ArgumentValidator.notNull(query, "query"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.CREDENTIAL, Actions.read, query.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.CREDENTIAL, Actions.read, query.getScopeId())); final CredentialListResult credentials = txManager.execute(tx -> credentialRepository.query(tx, query)); credentials.getItems().forEach(credential -> credential.setCredentialKey(null)); @@ -230,8 +226,7 @@ public long count(KapuaQuery query) // Check Access KapuaLocator locator = KapuaLocator.getInstance(); AuthorizationService authorizationService = locator.getService(AuthorizationService.class); - PermissionFactory permissionFactory = locator.getFactory(PermissionFactory.class); - authorizationService.checkPermission(permissionFactory.newPermission(Domains.CREDENTIAL, Actions.read, query.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.CREDENTIAL, Actions.read, query.getScopeId())); return txManager.execute(tx -> credentialRepository.count(tx, query)); } @@ -242,7 +237,7 @@ public void delete(KapuaId scopeId, KapuaId credentialId) ArgumentValidator.notNull(credentialId, "credential.id"); ArgumentValidator.notNull(scopeId, "credential.scopeId"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.CREDENTIAL, Actions.delete, scopeId)); + authorizationService.checkPermission(new Permission(Domains.CREDENTIAL, Actions.delete, scopeId)); txManager.execute(tx -> credentialRepository.delete(tx, scopeId, credentialId)); } @@ -253,7 +248,7 @@ public CredentialListResult findByUserId(KapuaId scopeId, KapuaId userId) ArgumentValidator.notNull(scopeId, KapuaEntityAttributes.SCOPE_ID); ArgumentValidator.notNull(userId, "userId"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.CREDENTIAL, Actions.read, scopeId)); + authorizationService.checkPermission(new Permission(Domains.CREDENTIAL, Actions.read, scopeId)); // Do find final CredentialListResult credentials = txManager.execute(tx -> credentialRepository.findByUserId(tx, scopeId, userId)); @@ -271,10 +266,10 @@ public CredentialListResult findByUserId(KapuaId scopeId, KapuaId userId, String ArgumentValidator.notNull(availableCredentialAuthenticationType.get(credentialType), "credentialType"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.CREDENTIAL, Actions.read, scopeId)); + authorizationService.checkPermission(new Permission(Domains.CREDENTIAL, Actions.read, scopeId)); // Do find - CredentialQuery credentialQuery = new CredentialQueryImpl(scopeId); + KapuaQuery credentialQuery = new KapuaQuery(scopeId); credentialQuery.setPredicate( credentialQuery.andPredicate( @@ -301,7 +296,7 @@ public Credential findByApiKey(String apiKey) throws KapuaException { String apiKeyPreValue = apiKey.substring(0, preLength).concat(preSeparator); // Build query - KapuaQuery query = new CredentialQueryImpl(); + KapuaQuery query = new KapuaQuery(); query.setPredicate( query.andPredicate( @@ -319,7 +314,7 @@ public Credential findByApiKey(String apiKey) throws KapuaException { ///FIXME: why the permission check here? it does not rollback! // Check Access if (credential != null) { - authorizationService.checkPermission(permissionFactory.newPermission(Domains.CREDENTIAL, Actions.read, credential.getId())); + authorizationService.checkPermission(new Permission(Domains.CREDENTIAL, Actions.read, credential.getId())); credential.setCredentialKey(null); } @@ -332,7 +327,7 @@ public void unlock(KapuaId scopeId, KapuaId credentialId) throws KapuaException ArgumentValidator.notNull(scopeId, KapuaEntityAttributes.SCOPE_ID); ArgumentValidator.notNull(credentialId, "credentialId"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.CREDENTIAL, Actions.write, scopeId)); + authorizationService.checkPermission(new Permission(Domains.CREDENTIAL, Actions.write, scopeId)); txManager.execute(tx -> { Credential credential = credentialRepository.find(tx, scopeId, credentialId) @@ -365,10 +360,7 @@ public void onKapuaEvent(ServiceEvent kapuaEvent) throws KapuaException { } private void deleteCredentialByUserId(KapuaId scopeId, KapuaId userId) throws KapuaException { - KapuaLocator locator = KapuaLocator.getInstance(); - CredentialFactory credentialFactory = locator.getFactory(CredentialFactory.class); - - CredentialQuery query = credentialFactory.newQuery(scopeId); + KapuaQuery query = new KapuaQuery(scopeId); query.setPredicate(query.attributePredicate(CredentialAttributes.USER_ID, userId)); CredentialListResult credentialsToDelete = query(query); @@ -379,10 +371,7 @@ private void deleteCredentialByUserId(KapuaId scopeId, KapuaId userId) throws Ka } private void deleteCredentialByAccountId(KapuaId scopeId, KapuaId accountId) throws KapuaException { - KapuaLocator locator = KapuaLocator.getInstance(); - CredentialFactory credentialFactory = locator.getFactory(CredentialFactory.class); - - CredentialQuery query = credentialFactory.newQuery(accountId); + final KapuaQuery query = new KapuaQuery(accountId); CredentialListResult credentialsToDelete = query(query); @@ -407,7 +396,7 @@ public Credential findWithKey(KapuaId scopeId, KapuaId credentialId) throws Kapu // // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.CREDENTIAL, Actions.read, null)); + authorizationService.checkPermission(new Permission(Domains.CREDENTIAL, Actions.read, null)); return txManager.execute(tx -> credentialRepository.find(tx, scopeId, credentialId)) .orElse(null); @@ -420,8 +409,8 @@ public Credential adminResetUserPassword(KapuaId scopeId, KapuaId userId, Passwo ArgumentValidator.notNull(passwordResetRequest, "passwordResetRequest"); ArgumentValidator.notNull(passwordResetRequest.getNewPassword(), "passwordResetRequest.netPassword"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.CREDENTIAL, Actions.read, scopeId)); - authorizationService.checkPermission(permissionFactory.newPermission(Domains.CREDENTIAL, Actions.write, scopeId)); + authorizationService.checkPermission(new Permission(Domains.CREDENTIAL, Actions.read, scopeId)); + authorizationService.checkPermission(new Permission(Domains.CREDENTIAL, Actions.write, scopeId)); return txManager.execute(tx -> passwordResetter.resetPassword(tx, scopeId, userId, false, passwordResetRequest)); } diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/shiro/PasswordResetRequestImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/shiro/PasswordResetRequestImpl.java deleted file mode 100644 index c4ee3aae4e9..00000000000 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/credential/shiro/PasswordResetRequestImpl.java +++ /dev/null @@ -1,34 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2023, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authentication.credential.shiro; - -import org.eclipse.kapua.service.authentication.user.PasswordResetRequest; - -/** - * The {@link PasswordResetRequest} implementation. - * - * @since 1.0.0 - */ -public class PasswordResetRequestImpl implements PasswordResetRequest { - private String newPassword; - - @Override - public String getNewPassword() { - return newPassword; - } - - @Override - public void setNewPassword(String newPassword) { - this.newPassword = newPassword; - } -} diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/AccessTokenCredentialsImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/AccessTokenCredentialsImpl.java index ed85c4b0091..4e62beabd39 100644 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/AccessTokenCredentialsImpl.java +++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/AccessTokenCredentialsImpl.java @@ -12,20 +12,21 @@ *******************************************************************************/ package org.eclipse.kapua.service.authentication.shiro; -import org.eclipse.kapua.service.authentication.AccessTokenCredentials; -import org.eclipse.kapua.service.authentication.shiro.realm.KapuaAuthenticationToken; +import java.util.Optional; import javax.validation.constraints.NotNull; -import java.util.Optional; + +import org.eclipse.kapua.service.authentication.SessionCredentials; +import org.eclipse.kapua.service.authentication.shiro.realm.KapuaAuthenticationToken; /** - * {@link AccessTokenCredentials} implementation. + * {@link AccessTokenCredentialsImpl} implementation. *

        * This implements also {@link KapuaAuthenticationToken} to allow usage in Apache Shiro. * * @since 1.0.0 */ -public class AccessTokenCredentialsImpl implements AccessTokenCredentials, KapuaAuthenticationToken { +public class AccessTokenCredentialsImpl implements KapuaAuthenticationToken, SessionCredentials { private static final long serialVersionUID = -7549848672967689716L; @@ -34,41 +35,42 @@ public class AccessTokenCredentialsImpl implements AccessTokenCredentials, Kapua /** * Constructor. * - * @param tokenId The credential JWT + * @param tokenId + * The credential JWT * @since 1.0.0 */ public AccessTokenCredentialsImpl(@NotNull String tokenId) { - setTokenId(tokenId); + this.tokenId = tokenId; } /** * Clone constructor. * - * @param accessTokenCredentials The {@link AccessTokenCredentials} to clone. + * @param accessTokenCredentials + * The {@link AccessTokenCredentialsImpl} to clone. * @since 1.5.0 */ - public AccessTokenCredentialsImpl(@NotNull AccessTokenCredentials accessTokenCredentials) { - setTokenId(accessTokenCredentials.getTokenId()); + public AccessTokenCredentialsImpl(@NotNull AccessTokenCredentialsImpl accessTokenCredentials) { + this.tokenId = accessTokenCredentials.getTokenId(); } - @Override public String getTokenId() { return tokenId; } - @Override - public void setTokenId(String tokenId) { + public AccessTokenCredentialsImpl setTokenId(String tokenId) { this.tokenId = tokenId; + return this; } @Override public Object getPrincipal() { - return getTokenId(); + return tokenId; } @Override public Object getCredentials() { - return getTokenId(); + return tokenId; } @Override diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/ApiKeyCredentialsImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/ApiKeyCredentialsImpl.java index 66a37bcc5ad..a54411ac37f 100644 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/ApiKeyCredentialsImpl.java +++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/ApiKeyCredentialsImpl.java @@ -12,11 +12,12 @@ *******************************************************************************/ package org.eclipse.kapua.service.authentication.shiro; -import org.eclipse.kapua.service.authentication.ApiKeyCredentials; -import org.eclipse.kapua.service.authentication.shiro.realm.KapuaAuthenticationToken; +import java.util.Optional; import javax.validation.constraints.NotNull; -import java.util.Optional; + +import org.eclipse.kapua.service.authentication.ApiKeyCredentials; +import org.eclipse.kapua.service.authentication.shiro.realm.KapuaAuthenticationToken; /** * {@link ApiKeyCredentials} implementation. @@ -25,7 +26,7 @@ * * @since 1.0.0 */ -public class ApiKeyCredentialsImpl implements ApiKeyCredentials, KapuaAuthenticationToken { +public class ApiKeyCredentialsImpl implements KapuaAuthenticationToken { private static final long serialVersionUID = -5920944517814926028L; @@ -34,33 +35,29 @@ public class ApiKeyCredentialsImpl implements ApiKeyCredentials, KapuaAuthentica /** * Constructor. * - * @param apiKey The Api Key. + * @param apiKey + * The Api Key. * @since 1.0.0 */ public ApiKeyCredentialsImpl(String apiKey) { - setApiKey(apiKey); + this.apiKey = apiKey; } /** * Clone constructor. * - * @param apiKeyCredentials The {@link ApiKeyCredentials} to clone. + * @param apiKeyCredentials + * The {@link ApiKeyCredentials} to clone. * @since 1.5.0 */ public ApiKeyCredentialsImpl(@NotNull ApiKeyCredentials apiKeyCredentials) { - setApiKey(apiKeyCredentials.getApiKey()); + this.apiKey = apiKeyCredentials.getApiKey(); } - @Override public String getApiKey() { return apiKey; } - @Override - public void setApiKey(String apiKey) { - this.apiKey = apiKey; - } - @Override public Object getPrincipal() { return getApiKey(); diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/AuthenticationModule.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/AuthenticationModule.java index e01bc9e1b2c..1a1dcf9ae15 100644 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/AuthenticationModule.java +++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/AuthenticationModule.java @@ -28,7 +28,6 @@ import org.eclipse.kapua.commons.jpa.KapuaJpaRepositoryConfiguration; import org.eclipse.kapua.commons.jpa.KapuaJpaTxManagerFactory; import org.eclipse.kapua.commons.model.domains.Domains; -import org.eclipse.kapua.commons.service.event.store.api.EventStoreFactory; import org.eclipse.kapua.commons.service.event.store.api.EventStoreRecordRepository; import org.eclipse.kapua.commons.service.event.store.internal.EventStoreServiceImpl; import org.eclipse.kapua.commons.util.qr.QRCodeBuilder; @@ -39,7 +38,6 @@ import org.eclipse.kapua.model.domain.DomainEntry; import org.eclipse.kapua.service.account.AccountService; import org.eclipse.kapua.service.authentication.AuthenticationService; -import org.eclipse.kapua.service.authentication.CredentialsFactory; import org.eclipse.kapua.service.authentication.credential.CredentialFactory; import org.eclipse.kapua.service.authentication.credential.CredentialRepository; import org.eclipse.kapua.service.authentication.credential.CredentialService; @@ -89,7 +87,6 @@ import org.eclipse.kapua.service.authentication.token.shiro.AccessTokenImplJpaRepository; import org.eclipse.kapua.service.authentication.token.shiro.AccessTokenServiceImpl; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; import org.eclipse.kapua.service.user.UserService; import com.google.inject.Provides; @@ -102,7 +99,6 @@ protected void configureModule() { bind(KapuaAuthenticationSetting.class).in(Singleton.class); bind(AuthenticationService.class).to(AuthenticationServiceShiroImpl.class).in(Singleton.class); bind(CredentialFactory.class).to(CredentialFactoryImpl.class).in(Singleton.class); - bind(CredentialsFactory.class).to(CredentialsFactoryImpl.class).in(Singleton.class); bind(MfaOptionFactory.class).to(MfaOptionFactoryImpl.class).in(Singleton.class); bind(ScratchCodeFactory.class).to(ScratchCodeFactoryImpl.class).in(Singleton.class); bind(AccessTokenFactory.class).to(AccessTokenFactoryImpl.class).in(Singleton.class); @@ -139,9 +135,7 @@ public Domain credentialDomain() { public ServiceModule authenticationServiceModule(AccessTokenService accessTokenService, CredentialService credentialService, AuthorizationService authorizationService, - PermissionFactory permissionFactory, KapuaJpaTxManagerFactory txManagerFactory, - EventStoreFactory eventStoreFactory, EventStoreRecordRepository eventStoreRecordRepository, ServiceEventBus serviceEventBus, KapuaAuthenticationSetting kapuaAuthenticationSetting, @@ -154,9 +148,7 @@ public ServiceModule authenticationServiceModule(AccessTokenService accessTokenS new ServiceEventHouseKeeperFactoryImpl( new EventStoreServiceImpl( authorizationService, - permissionFactory, txManagerFactory.create("kapua-authentication"), - eventStoreFactory, eventStoreRecordRepository ), txManagerFactory.create("kapua-authentication"), @@ -204,13 +196,11 @@ AccountPasswordLengthProvider accountPasswordLengthProvider(SystemPasswordLength @Singleton AccessTokenService accessTokenService( AuthorizationService authorizationService, - PermissionFactory permissionFactory, AccessTokenRepository accessTokenRepository, AccessTokenFactory accessTokenFactory, KapuaJpaTxManagerFactory jpaTxManagerFactory) { return new AccessTokenServiceImpl( authorizationService, - permissionFactory, jpaTxManagerFactory.create("kapua-authentication"), accessTokenRepository, accessTokenFactory); @@ -224,7 +214,6 @@ MfaOptionService mfaOptionService( AccountService accountService, ScratchCodeRepository scratchCodeRepository, AuthorizationService authorizationService, - PermissionFactory permissionFactory, UserService userService, KapuaJpaTxManagerFactory jpaTxManagerFactory, KapuaAuthenticationSetting kapuaAuthenticationSetting, @@ -240,7 +229,6 @@ MfaOptionService mfaOptionService( accountService, scratchCodeRepository, authorizationService, - permissionFactory, userService, authenticationUtils, qrCodeBuilder @@ -251,13 +239,10 @@ MfaOptionService mfaOptionService( @Singleton ScratchCodeService scratchCodeService( AuthorizationService authorizationService, - PermissionFactory permissionFactory, ScratchCodeRepository scratchCodeRepository, - KapuaJpaTxManagerFactory jpaTxManagerFactory, - AuthenticationUtils authenticationUtils) { + KapuaJpaTxManagerFactory jpaTxManagerFactory) { return new ScratchCodeServiceImpl( authorizationService, - permissionFactory, jpaTxManagerFactory.create("kapua-authentication"), scratchCodeRepository); } @@ -285,7 +270,6 @@ public ScratchCodeRepository scratchCodeRepository(KapuaJpaRepositoryConfigurati public CredentialService credentialService( Map, ServiceConfigurationManager> serviceConfigurationManagersByServiceClass, AuthorizationService authorizationService, - PermissionFactory permissionFactory, CredentialRepository credentialRepository, CredentialFactory credentialFactory, KapuaJpaTxManagerFactory jpaTxManagerFactory, @@ -296,7 +280,6 @@ public CredentialService credentialService( Set availableCredentialAuthenticationTypes) { return new CredentialServiceImpl(serviceConfigurationManagersByServiceClass.get(CredentialService.class), authorizationService, - permissionFactory, jpaTxManagerFactory.create("kapua-authentication"), credentialRepository, credentialFactory, diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/AuthenticationServiceShiroImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/AuthenticationServiceShiroImpl.java index 4d26e755b39..16687f6933d 100644 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/AuthenticationServiceShiroImpl.java +++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/AuthenticationServiceShiroImpl.java @@ -17,10 +17,10 @@ import java.util.Set; import java.util.UUID; import java.util.stream.Collectors; + import javax.inject.Inject; import javax.inject.Singleton; -import com.google.common.collect.Sets; import org.apache.shiro.SecurityUtils; import org.apache.shiro.ShiroException; import org.apache.shiro.authc.AuthenticationException; @@ -42,6 +42,8 @@ import org.eclipse.kapua.commons.security.KapuaSecurityUtils; import org.eclipse.kapua.commons.security.KapuaSession; import org.eclipse.kapua.commons.util.KapuaDelayUtil; +import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.model.query.predicate.AndPredicate; import org.eclipse.kapua.model.query.predicate.AttributePredicate; import org.eclipse.kapua.service.authentication.AuthenticationCredentials; @@ -65,30 +67,22 @@ import org.eclipse.kapua.service.authentication.token.AccessTokenAttributes; import org.eclipse.kapua.service.authentication.token.AccessTokenCreator; import org.eclipse.kapua.service.authentication.token.AccessTokenFactory; -import org.eclipse.kapua.service.authentication.token.AccessTokenQuery; import org.eclipse.kapua.service.authentication.token.AccessTokenService; import org.eclipse.kapua.service.authentication.token.LoginInfo; import org.eclipse.kapua.service.authorization.access.AccessInfo; import org.eclipse.kapua.service.authorization.access.AccessInfoService; import org.eclipse.kapua.service.authorization.access.AccessPermissionAttributes; -import org.eclipse.kapua.service.authorization.access.AccessPermissionFactory; import org.eclipse.kapua.service.authorization.access.AccessPermissionListResult; -import org.eclipse.kapua.service.authorization.access.AccessPermissionQuery; import org.eclipse.kapua.service.authorization.access.AccessPermissionService; import org.eclipse.kapua.service.authorization.access.AccessRole; import org.eclipse.kapua.service.authorization.access.AccessRoleAttributes; -import org.eclipse.kapua.service.authorization.access.AccessRoleFactory; import org.eclipse.kapua.service.authorization.access.AccessRoleListResult; -import org.eclipse.kapua.service.authorization.access.AccessRoleQuery; import org.eclipse.kapua.service.authorization.access.AccessRoleService; import org.eclipse.kapua.service.authorization.role.RolePermissionAttributes; -import org.eclipse.kapua.service.authorization.role.RolePermissionFactory; import org.eclipse.kapua.service.authorization.role.RolePermissionListResult; -import org.eclipse.kapua.service.authorization.role.RolePermissionQuery; import org.eclipse.kapua.service.authorization.role.RolePermissionService; import org.eclipse.kapua.service.certificate.Certificate; import org.eclipse.kapua.service.certificate.CertificateAttributes; -import org.eclipse.kapua.service.certificate.CertificateFactory; import org.eclipse.kapua.service.certificate.CertificateQuery; import org.eclipse.kapua.service.certificate.CertificateService; import org.eclipse.kapua.service.certificate.CertificateStatus; @@ -109,6 +103,8 @@ import org.slf4j.LoggerFactory; import org.slf4j.MDC; +import com.google.common.collect.Sets; + /** * {@link AuthenticationService} implementation. * @@ -125,15 +121,11 @@ public class AuthenticationServiceShiroImpl implements AuthenticationService { private final AccessTokenService accessTokenService; private final AccessTokenFactory accessTokenFactory; private final CertificateService certificateService; - private final CertificateFactory certificateFactory; private final AccessInfoService accessInfoService; private final AccessRoleService accessRoleService; - private final AccessRoleFactory accessRoleFactory; private final RolePermissionService rolePermissionService; - private final RolePermissionFactory rolePermissionFactory; private final AccessPermissionService accessPermissionService; - private final AccessPermissionFactory accessPermissionFactory; private final UserService userService; @@ -149,14 +141,10 @@ public AuthenticationServiceShiroImpl( AccessTokenService accessTokenService, AccessTokenFactory accessTokenFactory, CertificateService certificateService, - CertificateFactory certificateFactory, AccessInfoService accessInfoService, AccessRoleService accessRoleService, - AccessRoleFactory accessRoleFactory, RolePermissionService rolePermissionService, - RolePermissionFactory rolePermissionFactory, AccessPermissionService accessPermissionService, - AccessPermissionFactory accessPermissionFactory, UserService userService, Set credentialsConverters, KapuaAuthenticationSetting kapuaAuthenticationSetting) { @@ -165,14 +153,10 @@ public AuthenticationServiceShiroImpl( this.accessTokenService = accessTokenService; this.accessTokenFactory = accessTokenFactory; this.certificateService = certificateService; - this.certificateFactory = certificateFactory; this.accessInfoService = accessInfoService; this.accessRoleService = accessRoleService; - this.accessRoleFactory = accessRoleFactory; this.rolePermissionService = rolePermissionService; - this.rolePermissionFactory = rolePermissionFactory; this.accessPermissionService = accessPermissionService; - this.accessPermissionFactory = accessPermissionFactory; this.userService = userService; this.credentialsConverters = credentialsConverters; this.kapuaAuthenticationSetting = kapuaAuthenticationSetting; @@ -187,8 +171,7 @@ public AuthenticationServiceShiroImpl( public AccessToken login(LoginCredentials loginCredentials, boolean enableTrust) throws KapuaException { if (loginCredentials instanceof UsernamePasswordCredentials) { - UsernamePasswordCredentialsImpl usernamePasswordCredentials = UsernamePasswordCredentialsImpl.parse((UsernamePasswordCredentials) loginCredentials); - usernamePasswordCredentials.setTrustMe(enableTrust); + ((UsernamePasswordCredentials) loginCredentials).setTrustMe(enableTrust); } return login(loginCredentials); @@ -371,7 +354,7 @@ public AccessToken findAccessToken(String jwt) throws KapuaException { @Override public AccessToken findRefreshableAccessToken(String tokenId) throws KapuaException { - AccessTokenQuery accessTokenQuery = accessTokenFactory.newQuery(null); + KapuaQuery accessTokenQuery = new KapuaQuery((KapuaId) null); AndPredicate andPredicate = accessTokenQuery.andPredicate( accessTokenQuery.attributePredicate(AccessTokenAttributes.REFRESH_EXPIRES_ON, new java.sql.Timestamp(new Date().getTime()), AttributePredicate.Operator.GREATER_THAN_OR_EQUAL), accessTokenQuery.attributePredicate(AccessTokenAttributes.INVALIDATED_ON, null, AttributePredicate.Operator.IS_NULL), @@ -413,7 +396,7 @@ public AccessToken refreshAccessToken(String tokenId, String refreshToken) throw @Override public LoginInfo getLoginInfo() throws KapuaException { - LoginInfo loginInfo = accessTokenFactory.newLoginInfo(); + LoginInfo loginInfo = new LoginInfo(); // AccessToken AccessToken accessToken = KapuaSecurityUtils.getSession().getAccessToken(); @@ -423,18 +406,19 @@ public LoginInfo getLoginInfo() throws KapuaException { AccessInfo accessInfo = KapuaSecurityUtils.doPrivileged(() -> accessInfoService.findByUserId(accessToken.getScopeId(), accessToken.getUserId())); // AccessRole - AccessRoleQuery accessRoleQuery = accessRoleFactory.newQuery(accessToken.getScopeId()); + final KapuaQuery accessRoleQuery = new KapuaQuery(accessToken.getScopeId()); accessRoleQuery.setPredicate(accessRoleQuery.attributePredicate(AccessRoleAttributes.ACCESS_INFO_ID, accessInfo.getId())); AccessRoleListResult accessRoleListResult = KapuaSecurityUtils.doPrivileged(() -> accessRoleService.query(accessRoleQuery)); // RolePermission - RolePermissionQuery rolePermissionQuery = rolePermissionFactory.newQuery(accessToken.getScopeId()); - rolePermissionQuery.setPredicate(rolePermissionQuery.attributePredicate(RolePermissionAttributes.ROLE_ID, accessRoleListResult.getItems().stream().map(AccessRole::getRoleId).collect(Collectors.toList()))); + final KapuaQuery rolePermissionQuery = new KapuaQuery(accessToken.getScopeId()); + rolePermissionQuery.setPredicate( + rolePermissionQuery.attributePredicate(RolePermissionAttributes.ROLE_ID, accessRoleListResult.getItems().stream().map(AccessRole::getRoleId).collect(Collectors.toList()))); RolePermissionListResult rolePermissions = KapuaSecurityUtils.doPrivileged(() -> rolePermissionService.query(rolePermissionQuery)); loginInfo.setRolePermission(Sets.newHashSet(rolePermissions.getItems())); // AccessPermission - AccessPermissionQuery accessPermissionQuery = accessPermissionFactory.newQuery(accessToken.getScopeId()); + final KapuaQuery accessPermissionQuery = new KapuaQuery(accessToken.getScopeId()); accessPermissionQuery.setPredicate(accessPermissionQuery.attributePredicate(AccessPermissionAttributes.ACCESS_INFO_ID, accessInfo.getId())); AccessPermissionListResult accessPermissions = KapuaSecurityUtils.doPrivileged(() -> accessPermissionService.query(accessPermissionQuery)); loginInfo.setAccessPermission(Sets.newHashSet(accessPermissions.getItems())); @@ -459,10 +443,10 @@ public boolean isAuthenticated() // /** - * Checks if the Shiro {@link Subject} is authenticated or not. - * If {@link Subject#isAuthenticated()} {@code equals true}, {@link KapuaAuthenticationException} is raised. + * Checks if the Shiro {@link Subject} is authenticated or not. If {@link Subject#isAuthenticated()} {@code equals true}, {@link KapuaAuthenticationException} is raised. * - * @throws KapuaAuthenticationException If {@link Subject#isAuthenticated()} {@code equals true} + * @throws KapuaAuthenticationException + * If {@link Subject#isAuthenticated()} {@code equals true} * @since 1.0 */ private void checkCurrentSubjectNotAuthenticated() @@ -478,9 +462,11 @@ private void checkCurrentSubjectNotAuthenticated() /** * Converts am instance of {@link AuthenticationCredentials} to the compatible {@link KapuaAuthenticationToken} to be used in Apache Shiro. * - * @param authenticationCredentials The {@link AuthenticationCredentials} to convert + * @param authenticationCredentials + * The {@link AuthenticationCredentials} to convert * @return The converted {@link KapuaAuthenticationToken}. - * @throws KapuaAuthenticationException if the instance of {@link AuthenticationCredentials} cannot be handled or is are invalid. + * @throws KapuaAuthenticationException + * if the instance of {@link AuthenticationCredentials} cannot be handled or is are invalid. * @since 2.0.0 */ private KapuaAuthenticationToken doMapToShiro(AuthenticationCredentials authenticationCredentials) throws KapuaAuthenticationException { @@ -529,7 +515,8 @@ private void handleTokenLoginException(ShiroException se, Subject currentSubject /** * Create and persist a {@link AccessToken} from the data contained in the Shiro {@link Session} * - * @param session The Shiro {@link Session} from which extract data + * @param session + * The Shiro {@link Session} from which extract data * @return The persisted {@link AccessToken} * @throws KapuaException * @since 1.0 @@ -545,8 +532,10 @@ private AccessToken createAccessToken(Session session) throws KapuaException { /** * Create and persist a {@link AccessToken} from a scopeId and a userId * - * @param scopeId The scopeID - * @param userId The userID + * @param scopeId + * The scopeID + * @param userId + * The userID * @return The persisted {@link AccessToken} * @throws KapuaException * @since 1.0.0 @@ -562,7 +551,7 @@ private AccessToken createAccessToken(KapuaEid scopeId, KapuaEid userId) throws String jwt = generateJwt(scopeId, userId, now, tokenTtl, tokenId); // Persist token - AccessTokenCreator accessTokenCreator = accessTokenFactory.newCreator(scopeId, + AccessTokenCreator accessTokenCreator = new AccessTokenCreator(scopeId, userId, jwt, new Date(now.getTime() + tokenTtl), @@ -583,14 +572,16 @@ private AccessToken createAccessToken(KapuaEid scopeId, KapuaEid userId) throws /** * Creates a trust key if given {@link AuthenticationToken} is a {@link UsernamePasswordCredentials} and if {@link UsernamePasswordCredentials#getTrustMe()} is {@code true} * - * @param shiroAuthenticationToken The {@link AuthenticationToken} extracted {@link LoginCredentials} - * @param accessToken The {@link AccessToken} of this login. + * @param shiroAuthenticationToken + * The {@link AuthenticationToken} extracted {@link LoginCredentials} + * @param accessToken + * The {@link AccessToken} of this login. * @throws KapuaException * @since 2.0.0 */ private void createTrustKey(AuthenticationToken shiroAuthenticationToken, AccessToken accessToken) throws KapuaException { if (shiroAuthenticationToken instanceof UsernamePasswordCredentials) { - UsernamePasswordCredentialsImpl usernamePasswordCredentials = UsernamePasswordCredentialsImpl.parse((UsernamePasswordCredentials) shiroAuthenticationToken); + UsernamePasswordCredentials usernamePasswordCredentials = (UsernamePasswordCredentials) shiroAuthenticationToken; if (usernamePasswordCredentials.getTrustMe()) { String trustKey = KapuaSecurityUtils.doPrivileged(() -> { @@ -639,7 +630,7 @@ private String generateJwt(KapuaEid scopeId, KapuaEid userId, Date now, long ttl String jwt = null; try { - CertificateQuery certificateQuery = certificateFactory.newQuery(scopeId); + CertificateQuery certificateQuery = new CertificateQuery(scopeId); certificateQuery.setPredicate( certificateQuery.andPredicate( certificateQuery.attributePredicate(CertificateAttributes.USAGE_NAME, "JWT"), @@ -670,8 +661,8 @@ private String generateJwt(KapuaEid scopeId, KapuaEid userId, Date now, long ttl *

        * As of 2.1.0, only PASSWORD credentials can be locked. * - * @param authenticationToken The {@link AuthenticationToken} for the login attempt. - * + * @param authenticationToken + * The {@link AuthenticationToken} for the login attempt. * @since 1.1.0 */ private Boolean checkIfCredentialHasJustBeenLocked(AuthenticationToken authenticationToken) throws KapuaException { diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/CredentialsFactoryImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/CredentialsFactoryImpl.java deleted file mode 100644 index a7151beee16..00000000000 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/CredentialsFactoryImpl.java +++ /dev/null @@ -1,58 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authentication.shiro; - -import org.eclipse.kapua.service.authentication.AccessTokenCredentials; -import org.eclipse.kapua.service.authentication.ApiKeyCredentials; -import org.eclipse.kapua.service.authentication.CredentialsFactory; -import org.eclipse.kapua.service.authentication.JwtCredentials; -import org.eclipse.kapua.service.authentication.RefreshTokenCredentials; -import org.eclipse.kapua.service.authentication.UsernamePasswordCredentials; - -import javax.inject.Singleton; - -/** - * {@link CredentialsFactory} factory implementation. - * - * @since 1.0 - * - */ -@Singleton -public class CredentialsFactoryImpl implements CredentialsFactory { - - @Override - public UsernamePasswordCredentials newUsernamePasswordCredentials(String username, String password) { - return new UsernamePasswordCredentialsImpl(username, password); - } - - @Override - public ApiKeyCredentials newApiKeyCredentials(String apiKey) { - return new ApiKeyCredentialsImpl(apiKey); - } - - @Override - public JwtCredentials newJwtCredentials(String accessToken, String idToken) { - return new JwtCredentialsImpl(accessToken, idToken); - } - - @Override - public AccessTokenCredentials newAccessTokenCredentials(String tokenId) { - return new AccessTokenCredentialsImpl(tokenId); - } - - @Override - public RefreshTokenCredentials newRefreshTokenCredentials(String tokenId, String refreshToken) { - return new RefreshTokenCredentialsImpl(tokenId, refreshToken); - } - -} diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/JwtCredentialsImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/JwtCredentialsImpl.java index bfd865e14a3..1463ea12ab9 100644 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/JwtCredentialsImpl.java +++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/JwtCredentialsImpl.java @@ -12,11 +12,12 @@ *******************************************************************************/ package org.eclipse.kapua.service.authentication.shiro; -import org.eclipse.kapua.service.authentication.JwtCredentials; -import org.eclipse.kapua.service.authentication.shiro.realm.KapuaAuthenticationToken; +import java.util.Optional; import javax.validation.constraints.NotNull; -import java.util.Optional; + +import org.eclipse.kapua.service.authentication.JwtCredentials; +import org.eclipse.kapua.service.authentication.shiro.realm.KapuaAuthenticationToken; /** * {@link JwtCredentials} implementation. @@ -25,68 +26,43 @@ * * @since 1.0.0 */ -public class JwtCredentialsImpl implements JwtCredentials, KapuaAuthenticationToken { - - private static final long serialVersionUID = -5920944517814926028L; +public class JwtCredentialsImpl implements KapuaAuthenticationToken { private String accessToken; private String idToken; - /** - * Constructor. - * - * @param accessToken The credential access token - * @param idToken The credential id token. - * @since 1.4.0 - */ - public JwtCredentialsImpl(String accessToken, String idToken) { - setAccessToken(accessToken); - setIdToken(idToken); - } - /** * Clone constructor. * - * @param jwtCredentials The {@link JwtCredentials} to clone + * @param jwtCredentials + * The {@link JwtCredentials} to clone * @since 1.5.0 */ public JwtCredentialsImpl(@NotNull JwtCredentials jwtCredentials) { - setAccessToken(jwtCredentials.getAccessToken()); - setIdToken(jwtCredentials.getIdToken()); + this.accessToken = jwtCredentials.getAccessToken(); + this.idToken = jwtCredentials.getIdToken(); } - @Override public String getAccessToken() { return accessToken; } - @Override - public void setAccessToken(String accessToken) { - this.accessToken = accessToken; - } - - @Override public String getIdToken() { return idToken; } - @Override - public void setIdToken(String idToken) { - this.idToken = idToken; - } - @Override public Object getPrincipal() { - return getAccessToken(); + return this.accessToken; } @Override public Object getCredentials() { - return getAccessToken(); + return this.accessToken; } @Override public Optional getOpenIdToken() { - return Optional.of(getIdToken()); + return Optional.of(this.idToken); } } diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/RefreshTokenCredentialsImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/RefreshTokenCredentialsImpl.java deleted file mode 100644 index 260261dc1cc..00000000000 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/RefreshTokenCredentialsImpl.java +++ /dev/null @@ -1,63 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authentication.shiro; - -import org.apache.shiro.authc.AuthenticationToken; -import org.eclipse.kapua.service.authentication.RefreshTokenCredentials; -import org.eclipse.kapua.service.authentication.token.AccessToken; - -/** - * {@link RefreshTokenCredentials} implementation. - *

        - * This implements also {@link AuthenticationToken} to allow usage in Apache Shiro. - * - * @since 1.0.0 - */ -public class RefreshTokenCredentialsImpl implements RefreshTokenCredentials { - - private String tokenId; - private String refreshToken; - - /** - * Constructor. - * - * @param tokenId The {@link AccessToken#getTokenId()} - * @param refreshToken TThe {@link AccessToken#getRefreshToken()} - * @since 1.0.0 - */ - public RefreshTokenCredentialsImpl(String tokenId, String refreshToken) { - this.tokenId = tokenId; - this.refreshToken = refreshToken; - } - - @Override - public String getTokenId() { - return tokenId; - } - - @Override - public void setTokenId(String tokenId) { - this.tokenId = tokenId; - } - - @Override - public String getRefreshToken() { - return refreshToken; - } - - @Override - public void setRefreshToken(String refreshToken) { - this.refreshToken = refreshToken; - } - -} diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/UsernamePasswordCredentialsImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/UsernamePasswordCredentialsImpl.java index 3eec0a604d7..4b507798fa7 100644 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/UsernamePasswordCredentialsImpl.java +++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/UsernamePasswordCredentialsImpl.java @@ -12,13 +12,14 @@ *******************************************************************************/ package org.eclipse.kapua.service.authentication.shiro; +import java.util.Optional; + +import javax.validation.constraints.NotNull; + import org.checkerframework.checker.nullness.qual.Nullable; import org.eclipse.kapua.service.authentication.UsernamePasswordCredentials; import org.eclipse.kapua.service.authentication.shiro.realm.KapuaAuthenticationToken; -import javax.validation.constraints.NotNull; -import java.util.Optional; - /** * {@link UsernamePasswordCredentials} implementation. *

        @@ -26,7 +27,7 @@ * * @since 1.0.0 */ -public class UsernamePasswordCredentialsImpl implements UsernamePasswordCredentials, KapuaAuthenticationToken { +public class UsernamePasswordCredentialsImpl implements KapuaAuthenticationToken { private static final long serialVersionUID = -7549848672967689716L; @@ -34,52 +35,51 @@ public class UsernamePasswordCredentialsImpl implements UsernamePasswordCredenti private String password; private String authenticationCode; private String trustKey; - private boolean trustMe; + + public String getUsername() { + return username; + } + + public String getPassword() { + return password; + } + + public String getAuthenticationCode() { + return authenticationCode; + } + + public String getTrustKey() { + return trustKey; + } /** * Constructor. * - * @param username The credential username. - * @param password The credential password. + * @param username + * The credential username. + * @param password + * The credential password. * @since 1.0.0 */ public UsernamePasswordCredentialsImpl(@NotNull String username, @NotNull String password) { - setUsername(username); - setPassword(password); + this.username = username; + this.password = password; + this.authenticationCode = null; + this.trustKey = null; } /** * Clone constructor. * - * @param usernamePasswordCredentials The {@link UsernamePasswordCredentials} to clone. + * @param usernamePasswordCredentials + * The {@link UsernamePasswordCredentials} to clone. * @since 1.5.0 */ public UsernamePasswordCredentialsImpl(@NotNull UsernamePasswordCredentials usernamePasswordCredentials) { - setUsername(usernamePasswordCredentials.getUsername()); - setPassword(usernamePasswordCredentials.getPassword()); - setAuthenticationCode(usernamePasswordCredentials.getAuthenticationCode()); - setTrustKey(usernamePasswordCredentials.getTrustKey()); - setTrustMe(usernamePasswordCredentials.getTrustMe()); - } - - @Override - public String getUsername() { - return username; - } - - @Override - public void setUsername(String username) { - this.username = username; - } - - @Override - public String getPassword() { - return password; - } - - @Override - public void setPassword(String password) { - this.password = password; + this.username = usernamePasswordCredentials.getUsername(); + this.password = usernamePasswordCredentials.getPassword(); + this.authenticationCode = usernamePasswordCredentials.getAuthenticationCode(); + this.trustKey = usernamePasswordCredentials.getTrustKey(); } @Override @@ -92,48 +92,17 @@ public Object getCredentials() { return password; } - @Override - public String getAuthenticationCode() { - return authenticationCode; - } - - @Override - public void setAuthenticationCode(String authenticationCode) { - this.authenticationCode = authenticationCode; - } - - @Override - public String getTrustKey() { - return trustKey; - } - - @Override - public void setTrustKey(String trustKey) { - this.trustKey = trustKey; - } - - @Override - public boolean getTrustMe() { - return trustMe; - } - - @Override - public void setTrustMe(boolean trustMe) { - this.trustMe = trustMe; - } - /** * Parses a {@link UsernamePasswordCredentials} into a {@link UsernamePasswordCredentialsImpl}. * - * @param usernamePasswordCredentials The {@link UsernamePasswordCredentials} to parse. + * @param usernamePasswordCredentials + * The {@link UsernamePasswordCredentials} to parse. * @return An instance of {@link UsernamePasswordCredentialsImpl}. * @since 1.5.0 */ public static UsernamePasswordCredentialsImpl parse(@Nullable UsernamePasswordCredentials usernamePasswordCredentials) { return usernamePasswordCredentials != null ? - (usernamePasswordCredentials instanceof UsernamePasswordCredentialsImpl ? - (UsernamePasswordCredentialsImpl) usernamePasswordCredentials : - new UsernamePasswordCredentialsImpl(usernamePasswordCredentials)) + new UsernamePasswordCredentialsImpl(usernamePasswordCredentials) : null; } diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/realm/AccessTokenAuthenticatingRealm.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/realm/AccessTokenAuthenticatingRealm.java index 4f44e823018..347819dbfa5 100644 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/realm/AccessTokenAuthenticatingRealm.java +++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/realm/AccessTokenAuthenticatingRealm.java @@ -31,7 +31,6 @@ import org.eclipse.kapua.locator.KapuaLocator; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.account.Account; -import org.eclipse.kapua.service.authentication.AccessTokenCredentials; import org.eclipse.kapua.service.authentication.shiro.AccessTokenCredentialsImpl; import org.eclipse.kapua.service.authentication.shiro.exceptions.ExpiredAccessTokenException; import org.eclipse.kapua.service.authentication.shiro.exceptions.InvalidatedAccessTokenException; @@ -45,7 +44,6 @@ import org.eclipse.kapua.service.certificate.CertificateAttributes; import org.eclipse.kapua.service.certificate.CertificateStatus; import org.eclipse.kapua.service.certificate.info.CertificateInfo; -import org.eclipse.kapua.service.certificate.info.CertificateInfoFactory; import org.eclipse.kapua.service.certificate.info.CertificateInfoListResult; import org.eclipse.kapua.service.certificate.info.CertificateInfoQuery; import org.eclipse.kapua.service.certificate.info.CertificateInfoService; @@ -63,7 +61,7 @@ import org.slf4j.LoggerFactory; /** - * {@link AccessTokenCredentials} based {@link AuthenticatingRealm} implementation. + * {@link AccessTokenCredentialsImpl} based {@link AuthenticatingRealm} implementation. * * @since 1.0.0 */ @@ -73,7 +71,6 @@ public class AccessTokenAuthenticatingRealm extends KapuaAuthenticatingRealm { * Realm name. */ public static final String REALM_NAME = "accessTokenAuthenticatingRealm"; - private final CertificateInfoFactory certificateInfoFactory = KapuaLocator.getInstance().getFactory(CertificateInfoFactory.class); private final CertificateInfoService certificateInfoService = KapuaLocator.getInstance().getService(CertificateInfoService.class); private final AccessTokenService accessTokenService = KapuaLocator.getInstance().getService(AccessTokenService.class); private final UserService userService = KapuaLocator.getInstance().getService(UserService.class); @@ -110,12 +107,12 @@ protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authent } // Set validator final JwtConsumer jwtConsumer = new JwtConsumerBuilder() - .setVerificationKey(CertificateUtils.stringToCertificate(certificateInfo.getCertificate()).getPublicKey()) // Set public key - .setExpectedIssuer(issuer) // Set expected issuer - .setRequireIssuedAt() // Set require reserved claim: iatp - .setRequireExpirationTime() // Set require reserved claim: exp - .setRequireSubject() // // Set require reserved claim: sub - .build(); + .setVerificationKey(CertificateUtils.stringToCertificate(certificateInfo.getCertificate()).getPublicKey()) // Set public key + .setExpectedIssuer(issuer) // Set expected issuer + .setRequireIssuedAt() // Set require reserved claim: iatp + .setRequireExpirationTime() // Set require reserved claim: exp + .setRequireSubject() // // Set require reserved claim: sub + .build(); // This validates JWT final JwtContext jwtContext = jwtConsumer.process(jwt); jwtClaims = jwtContext.getJwtClaims(); @@ -178,7 +175,6 @@ protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authent accessToken); } - @Override protected void assertCredentialsMatch(AuthenticationToken authcToken, AuthenticationInfo info) throws AuthenticationException { @@ -199,14 +195,13 @@ public boolean supports(AuthenticationToken authenticationToken) { return authenticationToken instanceof AccessTokenCredentialsImpl; } - private CertificateInfo getNearestCertificate(AuthenticationToken authenticationToken) - throws KapuaException, InvalidJwtException, MalformedClaimException { + throws KapuaException, InvalidJwtException, MalformedClaimException { final JwtConsumer jwtConsumerNoValidation = new JwtConsumerBuilder() - .setSkipAllValidators() - .setDisableRequireSignature() - .setSkipSignatureVerification() - .build(); + .setSkipAllValidators() + .setDisableRequireSignature() + .setSkipSignatureVerification() + .build(); final String principal = (String) authenticationToken.getPrincipal(); final String username = jwtConsumerNoValidation.process(principal).getJwtClaims().getSubject(); final String account = jwtConsumerNoValidation.process(principal).getJwtClaims().getClaimValueAsString("sId"); @@ -214,12 +209,12 @@ private CertificateInfo getNearestCertificate(AuthenticationToken authentication final KapuaId accountId = KapuaEid.parseCompactId(account); final User user = KapuaSecurityUtils.doPrivileged(() -> userService.find(accountId, userId)); - final CertificateInfoQuery certificateInfoQuery = certificateInfoFactory.newQuery(user.getScopeId()); + final CertificateInfoQuery certificateInfoQuery = new CertificateInfoQuery(user.getScopeId()); certificateInfoQuery.setPredicate( - certificateInfoQuery.andPredicate( - certificateInfoQuery.attributePredicate(CertificateAttributes.USAGE_NAME, "JWT"), - certificateInfoQuery.attributePredicate(CertificateAttributes.STATUS, CertificateStatus.VALID) - ) + certificateInfoQuery.andPredicate( + certificateInfoQuery.attributePredicate(CertificateAttributes.USAGE_NAME, "JWT"), + certificateInfoQuery.attributePredicate(CertificateAttributes.STATUS, CertificateStatus.VALID) + ) ); certificateInfoQuery.setIncludeInherited(true); @@ -227,7 +222,6 @@ private CertificateInfo getNearestCertificate(AuthenticationToken authentication return getNearestCertificateFromList(certificateInfoList); } - private CertificateInfo getNearestCertificateFromList(CertificateInfoListResult certificateInfoList) throws KapuaException { CertificateInfo result = certificateInfoList.getFirstItem(); for (CertificateInfo certificateInfo : certificateInfoList.getItems()) { @@ -238,14 +232,12 @@ private CertificateInfo getNearestCertificateFromList(CertificateInfoListResult return result; } - private boolean isNearestThat(CertificateInfo certificateInfo, CertificateInfo result) throws KapuaException { final KapuaId certificateInfoScopeId = certificateInfo.getScopeId(); final KapuaId resultScopeId = result.getScopeId(); return isChildOf(certificateInfoScopeId, resultScopeId); } - private boolean isChildOf(KapuaId certificateInfoScopeId, KapuaId resultScopeId) throws KapuaException { final Account certificateInfoAccount = KapuaSecurityUtils.doPrivileged(() -> accountService.find(certificateInfoScopeId)); final Account resultAccount = KapuaSecurityUtils.doPrivileged(() -> accountService.find(resultScopeId)); diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/realm/AccessTokenCredentialsConverter.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/realm/AccessTokenCredentialsConverter.java index b92e2176c04..97bbfcbdf5d 100644 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/realm/AccessTokenCredentialsConverter.java +++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/realm/AccessTokenCredentialsConverter.java @@ -12,15 +12,15 @@ *******************************************************************************/ package org.eclipse.kapua.service.authentication.shiro.realm; -import com.google.common.base.Strings; -import org.eclipse.kapua.service.authentication.AccessTokenCredentials; import org.eclipse.kapua.service.authentication.AuthenticationCredentials; import org.eclipse.kapua.service.authentication.exception.KapuaAuthenticationErrorCodes; import org.eclipse.kapua.service.authentication.exception.KapuaAuthenticationException; import org.eclipse.kapua.service.authentication.shiro.AccessTokenCredentialsImpl; +import com.google.common.base.Strings; + /** - * {@link AccessTokenCredentials} {@link CredentialsConverter} implementation. + * {@link AccessTokenCredentialsImpl} {@link CredentialsConverter} implementation. * * @since 2.0.0 */ @@ -28,7 +28,7 @@ public class AccessTokenCredentialsConverter implements CredentialsConverter { @Override public boolean canProcess(AuthenticationCredentials authenticationCredentials) { - return authenticationCredentials instanceof AccessTokenCredentials; + return authenticationCredentials instanceof AccessTokenCredentialsImpl; } @Override @@ -36,7 +36,7 @@ public KapuaAuthenticationToken convertToShiro(AuthenticationCredentials authent AccessTokenCredentialsImpl accessTokenCredentials = authenticationCredentials instanceof AccessTokenCredentialsImpl ? (AccessTokenCredentialsImpl) authenticationCredentials : - new AccessTokenCredentialsImpl((AccessTokenCredentials) authenticationCredentials); + new AccessTokenCredentialsImpl((AccessTokenCredentialsImpl) authenticationCredentials); if (Strings.isNullOrEmpty(accessTokenCredentials.getTokenId())) { throw new KapuaAuthenticationException(KapuaAuthenticationErrorCodes.INVALID_SESSION_CREDENTIALS); diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/realm/AccessTokenCredentialsMatcher.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/realm/AccessTokenCredentialsMatcher.java index 2d182d7d659..f0483b501ff 100644 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/realm/AccessTokenCredentialsMatcher.java +++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/realm/AccessTokenCredentialsMatcher.java @@ -19,14 +19,13 @@ import org.eclipse.kapua.commons.security.KapuaSecurityUtils; import org.eclipse.kapua.locator.KapuaLocator; import org.eclipse.kapua.model.query.SortOrder; -import org.eclipse.kapua.service.authentication.AccessTokenCredentials; +import org.eclipse.kapua.service.authentication.shiro.AccessTokenCredentialsImpl; import org.eclipse.kapua.service.authentication.shiro.exceptions.JwtCertificateNotFoundException; import org.eclipse.kapua.service.authentication.shiro.setting.KapuaAuthenticationSetting; import org.eclipse.kapua.service.authentication.shiro.setting.KapuaAuthenticationSettingKeys; import org.eclipse.kapua.service.certificate.CertificateAttributes; import org.eclipse.kapua.service.certificate.CertificateStatus; import org.eclipse.kapua.service.certificate.info.CertificateInfo; -import org.eclipse.kapua.service.certificate.info.CertificateInfoFactory; import org.eclipse.kapua.service.certificate.info.CertificateInfoQuery; import org.eclipse.kapua.service.certificate.info.CertificateInfoService; import org.eclipse.kapua.service.certificate.util.CertificateUtils; @@ -37,7 +36,7 @@ import org.slf4j.LoggerFactory; /** - * {@link AccessTokenCredentials} {@link CredentialsMatcher} implementation. + * {@link AccessTokenCredentialsImpl} {@link CredentialsMatcher} implementation. * * @since 1.0.0 */ @@ -46,7 +45,6 @@ public class AccessTokenCredentialsMatcher implements CredentialsMatcher { private static final Logger LOG = LoggerFactory.getLogger(AccessTokenCredentialsMatcher.class); private final CertificateInfoService certificateInfoService = KapuaLocator.getInstance().getService(CertificateInfoService.class); - private final CertificateInfoFactory certificateInfoFactory = KapuaLocator.getInstance().getFactory(CertificateInfoFactory.class); private final KapuaAuthenticationSetting kapuaAuthenticationSetting = KapuaLocator.getInstance().getComponent(KapuaAuthenticationSetting.class); @Override @@ -57,7 +55,7 @@ public boolean doCredentialsMatch(AuthenticationToken authenticationToken, Authe try { String issuer = kapuaAuthenticationSetting.getString(KapuaAuthenticationSettingKeys.AUTHENTICATION_SESSION_JWT_ISSUER); - CertificateInfoQuery certificateInfoQuery = certificateInfoFactory.newQuery(null); + CertificateInfoQuery certificateInfoQuery = new CertificateInfoQuery(); certificateInfoQuery.setPredicate( certificateInfoQuery.andPredicate( certificateInfoQuery.attributePredicate(CertificateAttributes.USAGE_NAME, "JWT"), diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/realm/JwtAuthenticatingRealm.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/realm/JwtAuthenticatingRealm.java index 9f5c3ac444c..4904ac67045 100644 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/realm/JwtAuthenticatingRealm.java +++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/realm/JwtAuthenticatingRealm.java @@ -13,7 +13,8 @@ *******************************************************************************/ package org.eclipse.kapua.service.authentication.shiro.realm; -import com.google.common.base.Strings; +import javax.json.JsonObject; + import org.apache.shiro.SecurityUtils; import org.apache.shiro.ShiroException; import org.apache.shiro.authc.AuthenticationException; @@ -44,7 +45,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.json.JsonObject; +import com.google.common.base.Strings; /** * {@link ApiKeyCredentials} based {@link AuthenticatingRealm} implementation. @@ -193,9 +194,11 @@ public boolean supports(AuthenticationToken authenticationToken) { /** * Extract the subject information * - * @param jwt the token to use + * @param jwt + * the token to use * @return the subject, never returns {@code null} - * @throws ShiroException in case the subject could not be extracted + * @throws ShiroException + * in case the subject could not be extracted * @since 1.0.0 */ private String extractExternalId(String jwt) { @@ -217,7 +220,8 @@ private String extractExternalId(String jwt) { /** * Extract the external username information * - * @param jwt the token to use. + * @param jwt + * the token to use. * @return the external username. * @since 2.0.0 */ @@ -236,7 +240,8 @@ private String extractExternalUsername(String jwt) { /** * Extract the external username * - * @param userInfo the userInfo to use. + * @param userInfo + * the userInfo to use. * @return the external username. * @since 2.0.0 */ @@ -254,12 +259,13 @@ private String extractExternalUsername(JsonObject userInfo) { /** * Tries to resolve {@link User#getExternalUsername()} using the {@link OpenIDService#getUserInfo(String)} resource. * - * @param jwtCredentials The {@link JwtCredentials}. + * @param jwtCredentials + * The {@link JwtCredentials}. * @return The updated user. * @throws KapuaException * @since 2.0.0 */ - private User resolveExternalUsernameWithOpenIdProvider(JwtCredentials jwtCredentials) throws KapuaException { + private User resolveExternalUsernameWithOpenIdProvider(JwtCredentialsImpl jwtCredentials) throws KapuaException { // Ask to the OpenId Provider the user's info JsonObject userInfo = openIDService.getUserInfo(jwtCredentials.getAccessToken()); @@ -287,7 +293,8 @@ private User resolveExternalUsernameWithOpenIdProvider(JwtCredentials jwtCredent /** * Updates the given {@link User}. * - * @param user The user to update. + * @param user + * The user to update. * @return The updated user. * @throws KapuaException * @since 2.0.0 diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/realm/JwtCredentialsMatcher.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/realm/JwtCredentialsMatcher.java index 3c6b49daac9..37909351d25 100644 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/realm/JwtCredentialsMatcher.java +++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/realm/JwtCredentialsMatcher.java @@ -13,22 +13,21 @@ *******************************************************************************/ package org.eclipse.kapua.service.authentication.shiro.realm; +import javax.validation.constraints.NotNull; + import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.credential.CredentialsMatcher; +import org.eclipse.kapua.plugin.sso.openid.JwtProcessor; import org.eclipse.kapua.service.authentication.credential.Credential; import org.eclipse.kapua.service.authentication.shiro.JwtCredentialsImpl; -import org.eclipse.kapua.plugin.sso.openid.JwtProcessor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.validation.constraints.NotNull; - /** * {@link JwtCredentialsMatcher} credential matcher implementation * * @since 1.0 - * */ public class JwtCredentialsMatcher implements CredentialsMatcher { diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/realm/UserPassCredentialsMatcher.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/realm/UserPassCredentialsMatcher.java index 8f37cd1d8b8..042073a9b23 100644 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/realm/UserPassCredentialsMatcher.java +++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/shiro/realm/UserPassCredentialsMatcher.java @@ -12,6 +12,14 @@ *******************************************************************************/ package org.eclipse.kapua.service.authentication.shiro.realm; +import java.io.UnsupportedEncodingException; +import java.security.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; +import java.security.spec.InvalidKeySpecException; + +import javax.crypto.NoSuchPaddingException; + import org.apache.shiro.ShiroException; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; @@ -20,7 +28,6 @@ import org.eclipse.kapua.KapuaRuntimeException; import org.eclipse.kapua.locator.KapuaLocator; import org.eclipse.kapua.service.authentication.ApiKeyCredentials; -import org.eclipse.kapua.service.authentication.UsernamePasswordCredentials; import org.eclipse.kapua.service.authentication.credential.Credential; import org.eclipse.kapua.service.authentication.credential.cache.CacheMetric; import org.eclipse.kapua.service.authentication.credential.cache.CachedPasswordMatcher; @@ -29,19 +36,13 @@ import org.eclipse.kapua.service.authentication.credential.handler.shiro.PasswordCredentialTypeHandler; import org.eclipse.kapua.service.authentication.credential.mfa.MfaOptionService; import org.eclipse.kapua.service.authentication.shiro.AuthenticationServiceShiroImpl; +import org.eclipse.kapua.service.authentication.shiro.UsernamePasswordCredentialsImpl; import org.eclipse.kapua.service.authentication.shiro.setting.KapuaAuthenticationSetting; import org.eclipse.kapua.service.authentication.shiro.setting.KapuaAuthenticationSettingKeys; import org.eclipse.kapua.service.user.User; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.crypto.NoSuchPaddingException; -import java.io.UnsupportedEncodingException; -import java.security.InvalidAlgorithmParameterException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.spec.InvalidKeySpecException; - /** * {@link ApiKeyCredentials} {@link CredentialsMatcher} implementation. * @@ -77,7 +78,7 @@ public UserPassCredentialsMatcher() { @Override public boolean doCredentialsMatch(AuthenticationToken authenticationToken, AuthenticationInfo authenticationInfo) { // Token data - UsernamePasswordCredentials token = (UsernamePasswordCredentials) authenticationToken; + UsernamePasswordCredentialsImpl token = (UsernamePasswordCredentialsImpl) authenticationToken; String tokenUsername = token.getUsername(); String tokenPassword = token.getPassword(); String tokenAuthenticationCode = token.getAuthenticationCode(); diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/token/shiro/AccessTokenCreatorImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/token/shiro/AccessTokenCreatorImpl.java deleted file mode 100644 index 3bee25a8045..00000000000 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/token/shiro/AccessTokenCreatorImpl.java +++ /dev/null @@ -1,119 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authentication.token.shiro; - -import java.util.Date; - -import org.eclipse.kapua.commons.model.AbstractKapuaEntityCreator; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.authentication.token.AccessToken; -import org.eclipse.kapua.service.authentication.token.AccessTokenCreator; - -/** - * Access token implementation - * - * @since 1.0 - * - */ -public class AccessTokenCreatorImpl extends AbstractKapuaEntityCreator implements AccessTokenCreator { - - private static final long serialVersionUID = -27718046815190710L; - - private String tokenId; - private KapuaId userId; - private Date expiresOn; - private String refreshToken; - private Date refreshExpiresOn; - private String tokenIdentifier; - - /** - * Constructor - * - * @param scopeId - */ - protected AccessTokenCreatorImpl(KapuaId scopeId) { - super(scopeId); - } - - @Override - public String getTokenId() { - return tokenId; - } - - @Override - public void setTokenId(String tokenId) { - this.tokenId = tokenId; - - } - - @Override - public KapuaId getUserId() { - return userId; - } - - @Override - public void setUserId(KapuaId userId) { - this.userId = userId; - } - - @Override - public Date getExpiresOn() { - return expiresOn; - } - - @Override - public void setExpiresOn(Date expiresOn) { - this.expiresOn = expiresOn; - } - - @Override - public String getRefreshToken() { - return refreshToken; - } - - @Override - public void setRefreshToken(String refreshToken) { - this.refreshToken = refreshToken; - - } - - @Override - public Date getRefreshExpiresOn() { - return refreshExpiresOn; - } - - @Override - public void setRefreshExpiresOn(Date refreshExpiresOn) { - this.refreshExpiresOn = refreshExpiresOn; - } - - /** - * Get the token identifier - * - * @since 2.0 - */ - public String getTokenIdentifier() { - return tokenIdentifier; - } - - /** - * Sets the token identifier - * - * @param tokenId the token id to set - * @since 2.0 - */ - public void setTokenIdentifier(String tokenId) { - this.tokenIdentifier=tokenId; - } - -} diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/token/shiro/AccessTokenFactoryImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/token/shiro/AccessTokenFactoryImpl.java index 4f884bc8c4e..1005acbbba5 100644 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/token/shiro/AccessTokenFactoryImpl.java +++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/token/shiro/AccessTokenFactoryImpl.java @@ -12,17 +12,12 @@ *******************************************************************************/ package org.eclipse.kapua.service.authentication.token.shiro; +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaEntityCloneException; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.authentication.token.AccessToken; -import org.eclipse.kapua.service.authentication.token.AccessTokenCreator; import org.eclipse.kapua.service.authentication.token.AccessTokenFactory; -import org.eclipse.kapua.service.authentication.token.AccessTokenListResult; -import org.eclipse.kapua.service.authentication.token.AccessTokenQuery; -import org.eclipse.kapua.service.authentication.token.LoginInfo; - -import javax.inject.Singleton; -import java.util.Date; /** * {@link AccessTokenFactory} implementation. @@ -32,40 +27,11 @@ @Singleton public class AccessTokenFactoryImpl implements AccessTokenFactory { - @Override - public AccessTokenCreatorImpl newCreator(KapuaId scopeId, KapuaId userId, String tokenId, Date expiresOn, String refreshToken, Date refreshExpiresOn, String tokenIdentifier) { - AccessTokenCreatorImpl accessTokenCreator = new AccessTokenCreatorImpl(scopeId); - - accessTokenCreator.setUserId(userId); - accessTokenCreator.setTokenId(tokenId); - accessTokenCreator.setExpiresOn(expiresOn); - accessTokenCreator.setRefreshToken(refreshToken); - accessTokenCreator.setRefreshExpiresOn(refreshExpiresOn); - accessTokenCreator.setTokenIdentifier(tokenIdentifier); - - return accessTokenCreator; - } - @Override public AccessToken newEntity(KapuaId scopeId) { return new AccessTokenImpl(scopeId); } - @Override - public AccessTokenCreator newCreator(KapuaId scopeId) { - return new AccessTokenCreatorImpl(scopeId); - } - - @Override - public AccessTokenQuery newQuery(KapuaId scopeId) { - return new AccessTokenQueryImpl(scopeId); - } - - @Override - public AccessTokenListResult newListResult() { - return new AccessTokenListResultImpl(); - } - @Override public AccessToken clone(AccessToken accessToken) { try { @@ -74,10 +40,4 @@ public AccessToken clone(AccessToken accessToken) { throw new KapuaEntityCloneException(e, AccessToken.TYPE, accessToken); } } - - @Override - public LoginInfo newLoginInfo() { - return new LoginInfoImpl(); - } - } diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/token/shiro/AccessTokenImplJpaRepository.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/token/shiro/AccessTokenImplJpaRepository.java index 810b05c6ebe..27ba8c7ac7d 100644 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/token/shiro/AccessTokenImplJpaRepository.java +++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/token/shiro/AccessTokenImplJpaRepository.java @@ -12,6 +12,8 @@ *******************************************************************************/ package org.eclipse.kapua.service.authentication.token.shiro; +import java.util.Optional; + import org.eclipse.kapua.commons.jpa.KapuaJpaRepositoryConfiguration; import org.eclipse.kapua.commons.jpa.KapuaUpdatableEntityJpaRepository; import org.eclipse.kapua.model.id.KapuaId; @@ -21,13 +23,12 @@ import org.eclipse.kapua.service.authentication.token.AccessTokenRepository; import org.eclipse.kapua.storage.TxContext; -import java.util.Optional; - public class AccessTokenImplJpaRepository extends KapuaUpdatableEntityJpaRepository implements AccessTokenRepository { + public AccessTokenImplJpaRepository(KapuaJpaRepositoryConfiguration jpaRepoConfig) { - super(AccessTokenImpl.class, AccessToken.TYPE, () -> new AccessTokenListResultImpl(), jpaRepoConfig); + super(AccessTokenImpl.class, AccessToken.TYPE, () -> new AccessTokenListResult(), jpaRepoConfig); } @Override diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/token/shiro/AccessTokenListResultImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/token/shiro/AccessTokenListResultImpl.java deleted file mode 100644 index b420d1ac5e9..00000000000 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/token/shiro/AccessTokenListResultImpl.java +++ /dev/null @@ -1,28 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authentication.token.shiro; - -import org.eclipse.kapua.commons.model.query.KapuaListResultImpl; -import org.eclipse.kapua.service.authentication.token.AccessToken; -import org.eclipse.kapua.service.authentication.token.AccessTokenListResult; - -/** - * Access token list result implementation. - * - * @since 1.0 - * - */ -public class AccessTokenListResultImpl extends KapuaListResultImpl implements AccessTokenListResult { - private static final long serialVersionUID = -2596004122285166444L; - -} diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/token/shiro/AccessTokenQueryImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/token/shiro/AccessTokenQueryImpl.java deleted file mode 100644 index 2b7d7f7c9aa..00000000000 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/token/shiro/AccessTokenQueryImpl.java +++ /dev/null @@ -1,45 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authentication.token.shiro; - -import org.eclipse.kapua.commons.model.query.AbstractKapuaQuery; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.authentication.token.AccessTokenQuery; - -/** - * {@link AccessTokenQuery} implementation. - * - * @since 1.0.0 - */ -public class AccessTokenQueryImpl extends AbstractKapuaQuery implements AccessTokenQuery { - - /** - * Constructor. - * - * @since 1.0.0 - */ - private AccessTokenQueryImpl() { - super(); - } - - /** - * Constructor. - * - * @param scopeId The {@link #getScopeId()}. - * @since 1.0.0 - */ - public AccessTokenQueryImpl(KapuaId scopeId) { - this(); - setScopeId(scopeId); - } -} diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/token/shiro/AccessTokenServiceImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/token/shiro/AccessTokenServiceImpl.java index 1a4c4d1d105..ad579ba93c2 100644 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/token/shiro/AccessTokenServiceImpl.java +++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/token/shiro/AccessTokenServiceImpl.java @@ -12,6 +12,11 @@ *******************************************************************************/ package org.eclipse.kapua.service.authentication.token.shiro; +import java.util.Date; +import java.util.Optional; + +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaEntityNotFoundException; import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.commons.model.domains.Domains; @@ -26,19 +31,14 @@ import org.eclipse.kapua.service.authentication.token.AccessTokenCreator; import org.eclipse.kapua.service.authentication.token.AccessTokenFactory; import org.eclipse.kapua.service.authentication.token.AccessTokenListResult; -import org.eclipse.kapua.service.authentication.token.AccessTokenQuery; import org.eclipse.kapua.service.authentication.token.AccessTokenRepository; import org.eclipse.kapua.service.authentication.token.AccessTokenService; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; +import org.eclipse.kapua.service.authorization.permission.Permission; import org.eclipse.kapua.storage.TxManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.inject.Singleton; -import java.util.Date; -import java.util.Optional; - /** * {@link AccessTokenService} implementation. * @@ -49,19 +49,16 @@ public class AccessTokenServiceImpl implements AccessTokenService { private static final Logger LOGGER = LoggerFactory.getLogger(AccessTokenServiceImpl.class); private final AuthorizationService authorizationService; - private final PermissionFactory permissionFactory; private final TxManager txManager; private final AccessTokenRepository accessTokenRepository; private final AccessTokenFactory accessTokenFactory; public AccessTokenServiceImpl( AuthorizationService authorizationService, - PermissionFactory permissionFactory, TxManager txManager, AccessTokenRepository accessTokenRepository, AccessTokenFactory accessTokenFactory) { this.authorizationService = authorizationService; - this.permissionFactory = permissionFactory; this.txManager = txManager; this.accessTokenRepository = accessTokenRepository; this.accessTokenFactory = accessTokenFactory; @@ -78,7 +75,7 @@ public AccessToken create(AccessTokenCreator accessTokenCreator) throws KapuaExc ArgumentValidator.notNull(accessTokenCreator.getTokenIdentifier(), "accessTokenCreator.tokenIdentifier"); // Check access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.ACCESS_TOKEN, Actions.write, accessTokenCreator.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.ACCESS_TOKEN, Actions.write, accessTokenCreator.getScopeId())); // Do create AccessToken at = accessTokenFactory.newEntity(accessTokenCreator.getScopeId()); @@ -100,7 +97,7 @@ public AccessToken update(AccessToken accessToken) throws KapuaException { ArgumentValidator.notNull(accessToken.getUserId(), "accessToken.userId"); ArgumentValidator.notNull(accessToken.getExpiresOn(), "accessToken.expiresOn"); // Check access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.ACCESS_TOKEN, Actions.write, accessToken.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.ACCESS_TOKEN, Actions.write, accessToken.getScopeId())); return txManager.execute(tx -> { // Check existence if (!accessTokenRepository.find(tx, accessToken.getScopeId(), accessToken.getId()).isPresent()) { @@ -117,7 +114,7 @@ public AccessToken find(KapuaId scopeId, KapuaId accessTokenId) throws KapuaExce ArgumentValidator.notNull(scopeId, KapuaEntityAttributes.SCOPE_ID); ArgumentValidator.notNull(accessTokenId, KapuaEntityAttributes.ENTITY_ID); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.ACCESS_TOKEN, Actions.read, scopeId)); + authorizationService.checkPermission(new Permission(Domains.ACCESS_TOKEN, Actions.read, scopeId)); // Do find return txManager.execute(tx -> accessTokenRepository.find(tx, scopeId, accessTokenId)) .orElse(null); @@ -128,7 +125,7 @@ public AccessTokenListResult query(KapuaQuery query) throws KapuaException { // Argument Validation ArgumentValidator.notNull(query, "query"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.ACCESS_TOKEN, Actions.read, query.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.ACCESS_TOKEN, Actions.read, query.getScopeId())); // Do query return txManager.execute(tx -> accessTokenRepository.query(tx, query)); } @@ -138,7 +135,7 @@ public long count(KapuaQuery query) throws KapuaException { // Argument Validation ArgumentValidator.notNull(query, "query"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.ACCESS_TOKEN, Actions.read, query.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.ACCESS_TOKEN, Actions.read, query.getScopeId())); // Do count return txManager.execute(tx -> accessTokenRepository.count(tx, query)); } @@ -149,7 +146,7 @@ public void delete(KapuaId scopeId, KapuaId accessTokenId) throws KapuaException ArgumentValidator.notNull(scopeId, KapuaEntityAttributes.SCOPE_ID); ArgumentValidator.notNull(accessTokenId, KapuaEntityAttributes.ENTITY_ID); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.ACCESS_TOKEN, Actions.delete, scopeId)); + authorizationService.checkPermission(new Permission(Domains.ACCESS_TOKEN, Actions.delete, scopeId)); // Check existence txManager.execute(tx -> { if (!accessTokenRepository.find(tx, scopeId, accessTokenId).isPresent()) { @@ -166,9 +163,9 @@ public AccessTokenListResult findByUserId(KapuaId scopeId, KapuaId userId) throw ArgumentValidator.notNull(scopeId, KapuaEntityAttributes.SCOPE_ID); ArgumentValidator.notNull(userId, "userId"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.ACCESS_TOKEN, Actions.read, scopeId)); + authorizationService.checkPermission(new Permission(Domains.ACCESS_TOKEN, Actions.read, scopeId)); // Build query - AccessTokenQuery query = new AccessTokenQueryImpl(scopeId); + final KapuaQuery query = new KapuaQuery(scopeId); query.setPredicate(query.attributePredicate(AccessTokenAttributes.USER_ID, userId)); // Do query return query(query); @@ -182,7 +179,7 @@ public AccessToken findByTokenId(String tokenId) throws KapuaException { Optional accessToken = txManager.execute(tx -> accessTokenRepository.findByTokenId(tx, tokenId)); // Check Access if (accessToken.isPresent()) { - authorizationService.checkPermission(permissionFactory.newPermission(Domains.ACCESS_TOKEN, Actions.read, accessToken.get().getScopeId())); + authorizationService.checkPermission(new Permission(Domains.ACCESS_TOKEN, Actions.read, accessToken.get().getScopeId())); } return accessToken @@ -195,7 +192,7 @@ public void invalidate(KapuaId scopeId, KapuaId accessTokenId) throws KapuaExcep ArgumentValidator.notNull(scopeId, KapuaEntityAttributes.SCOPE_ID); ArgumentValidator.notNull(accessTokenId, KapuaEntityAttributes.ENTITY_ID); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.ACCESS_TOKEN, Actions.write, scopeId)); + authorizationService.checkPermission(new Permission(Domains.ACCESS_TOKEN, Actions.write, scopeId)); // Do find txManager.execute(tx -> accessTokenRepository.find(tx, scopeId, accessTokenId) @@ -223,7 +220,7 @@ public void onKapuaEvent(ServiceEvent kapuaEvent) throws KapuaException { private void deleteAccessTokenByUserId(KapuaId scopeId, KapuaId userId) throws KapuaException { - AccessTokenQuery query = new AccessTokenQueryImpl(scopeId); + final KapuaQuery query = new KapuaQuery(scopeId); query.setPredicate(query.attributePredicate(AccessTokenAttributes.USER_ID, userId)); AccessTokenListResult accessTokensToDelete = query(query); @@ -235,7 +232,7 @@ private void deleteAccessTokenByUserId(KapuaId scopeId, KapuaId userId) throws K private void deleteAccessTokenByAccountId(KapuaId scopeId, KapuaId accountId) throws KapuaException { - AccessTokenQuery query = new AccessTokenQueryImpl(accountId); + final KapuaQuery query = new KapuaQuery(scopeId); AccessTokenListResult accessTokensToDelete = query(query); diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/token/shiro/LoginInfoImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/token/shiro/LoginInfoImpl.java deleted file mode 100644 index 6e61424393d..00000000000 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/token/shiro/LoginInfoImpl.java +++ /dev/null @@ -1,58 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2019, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authentication.token.shiro; - -import java.util.Set; - -import org.eclipse.kapua.service.authentication.token.AccessToken; -import org.eclipse.kapua.service.authentication.token.LoginInfo; -import org.eclipse.kapua.service.authorization.access.AccessPermission; -import org.eclipse.kapua.service.authorization.role.RolePermission; - -public class LoginInfoImpl implements LoginInfo { - - private AccessToken accessToken; - private Set rolePermissions; - private Set accessPermissions; - - @Override - public AccessToken getAccessToken() { - return accessToken; - } - - @Override - public void setAccessToken(AccessToken accessToken) { - this.accessToken = accessToken; - } - - @Override - public Set getRolePermission() { - return rolePermissions; - } - - @Override - public void setRolePermission(Set rolePermissions) { - this.rolePermissions = rolePermissions; - } - - @Override - public Set getAccessPermission() { - return accessPermissions; - } - - @Override - public void setAccessPermission(Set accessPermissions) { - this.accessPermissions = accessPermissions; - } - -} diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/user/shiro/PasswordChangeRequestImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/user/shiro/PasswordChangeRequestImpl.java deleted file mode 100644 index 674197716b4..00000000000 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/user/shiro/PasswordChangeRequestImpl.java +++ /dev/null @@ -1,44 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2023, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authentication.user.shiro; - -import org.eclipse.kapua.service.authentication.user.PasswordChangeRequest; - -public class PasswordChangeRequestImpl implements PasswordChangeRequest { - private String newPassword; - private String currentPassword; - - - @Override - public String getCurrentPassword() { - return currentPassword; - } - - - @Override - public void setCurrentPassword(String currentPassword) { - this.currentPassword = currentPassword; - } - - - @Override - public String getNewPassword() { - return newPassword; - } - - - @Override - public void setNewPassword(String newPassword) { - this.newPassword = newPassword; - } -} diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/user/shiro/UserCredentialsFactoryImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/user/shiro/UserCredentialsFactoryImpl.java deleted file mode 100644 index 221cf4164a2..00000000000 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/user/shiro/UserCredentialsFactoryImpl.java +++ /dev/null @@ -1,34 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2023, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authentication.user.shiro; - -import org.eclipse.kapua.service.authentication.credential.shiro.PasswordResetRequestImpl; -import org.eclipse.kapua.service.authentication.user.PasswordChangeRequest; -import org.eclipse.kapua.service.authentication.user.PasswordResetRequest; -import org.eclipse.kapua.service.authentication.user.UserCredentialsFactory; - -import javax.inject.Singleton; - -@Singleton -public class UserCredentialsFactoryImpl implements UserCredentialsFactory { - @Override - public PasswordChangeRequest newPasswordChangeRequest() { - return new PasswordChangeRequestImpl(); - } - - - @Override - public PasswordResetRequest newPasswordResetRequest() { - return new PasswordResetRequestImpl(); - } -} diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/user/shiro/UserCredentialsModule.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/user/shiro/UserCredentialsModule.java index a5571aaa77e..97d666bdf62 100644 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/user/shiro/UserCredentialsModule.java +++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/user/shiro/UserCredentialsModule.java @@ -12,28 +12,26 @@ *******************************************************************************/ package org.eclipse.kapua.service.authentication.user.shiro; -import com.google.inject.Module; -import com.google.inject.Provides; +import java.util.Set; + +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaRuntimeException; import org.eclipse.kapua.commons.core.AbstractKapuaModule; import org.eclipse.kapua.commons.jpa.KapuaJpaTxManagerFactory; import org.eclipse.kapua.service.authentication.AuthenticationService; -import org.eclipse.kapua.service.authentication.CredentialsFactory; -import org.eclipse.kapua.service.authentication.credential.CredentialFactory; import org.eclipse.kapua.service.authentication.credential.CredentialRepository; import org.eclipse.kapua.service.authentication.credential.handler.CredentialTypeHandler; import org.eclipse.kapua.service.authentication.credential.handler.shiro.PasswordCredentialTypeHandler; import org.eclipse.kapua.service.authentication.credential.shiro.PasswordResetter; import org.eclipse.kapua.service.authentication.credential.shiro.PasswordResetterImpl; import org.eclipse.kapua.service.authentication.credential.shiro.PasswordValidator; -import org.eclipse.kapua.service.authentication.user.UserCredentialsFactory; import org.eclipse.kapua.service.authentication.user.UserCredentialsService; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; import org.eclipse.kapua.service.user.UserService; -import javax.inject.Singleton; -import java.util.Set; +import com.google.inject.Module; +import com.google.inject.Provides; /** * {@code kapua-security-shiro} {@link Module} implementation. @@ -44,7 +42,6 @@ public class UserCredentialsModule extends AbstractKapuaModule { @Override protected void configureModule() { - bind(UserCredentialsFactory.class).to(UserCredentialsFactoryImpl.class); } @Provides @@ -72,24 +69,14 @@ PasswordResetter passwordResetter( UserCredentialsService userCredentialsService( AuthenticationService authenticationService, AuthorizationService authorizationService, - PermissionFactory permissionFactory, - UserCredentialsFactory userCredentialsFactory, - CredentialsFactory credentialsFactory, - CredentialFactory credentialFactory, KapuaJpaTxManagerFactory txManagerFactory, UserService userService, - CredentialRepository credentialRepository, PasswordResetter passwordResetter) { return new UserCredentialsServiceImpl( authenticationService, authorizationService, - permissionFactory, - userCredentialsFactory, - credentialsFactory, - credentialFactory, txManagerFactory.create("kapua-authorization"), userService, - credentialRepository, passwordResetter); } } diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/user/shiro/UserCredentialsServiceImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/user/shiro/UserCredentialsServiceImpl.java index 02fb1d6110a..736484acd7b 100644 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/user/shiro/UserCredentialsServiceImpl.java +++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authentication/user/shiro/UserCredentialsServiceImpl.java @@ -12,6 +12,10 @@ *******************************************************************************/ package org.eclipse.kapua.service.authentication.user.shiro; +import java.util.Optional; + +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaEntityNotFoundException; import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.KapuaIllegalArgumentException; @@ -21,27 +25,20 @@ import org.eclipse.kapua.model.domain.Actions; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.authentication.AuthenticationService; -import org.eclipse.kapua.service.authentication.CredentialsFactory; import org.eclipse.kapua.service.authentication.UsernamePasswordCredentials; import org.eclipse.kapua.service.authentication.credential.Credential; -import org.eclipse.kapua.service.authentication.credential.CredentialFactory; -import org.eclipse.kapua.service.authentication.credential.CredentialRepository; import org.eclipse.kapua.service.authentication.credential.shiro.PasswordResetter; import org.eclipse.kapua.service.authentication.exception.KapuaAuthenticationErrorCodes; import org.eclipse.kapua.service.authentication.exception.KapuaAuthenticationException; import org.eclipse.kapua.service.authentication.user.PasswordChangeRequest; import org.eclipse.kapua.service.authentication.user.PasswordResetRequest; -import org.eclipse.kapua.service.authentication.user.UserCredentialsFactory; import org.eclipse.kapua.service.authentication.user.UserCredentialsService; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; +import org.eclipse.kapua.service.authorization.permission.Permission; import org.eclipse.kapua.service.user.User; import org.eclipse.kapua.service.user.UserService; import org.eclipse.kapua.storage.TxManager; -import javax.inject.Singleton; -import java.util.Optional; - /** * {@link UserCredentialsService} implementation. * @@ -49,35 +46,23 @@ */ @Singleton public class UserCredentialsServiceImpl implements UserCredentialsService { + private final AuthenticationService authenticationService; private final AuthorizationService authorizationService; - private final PermissionFactory permissionFactory; - private final UserCredentialsFactory userCredentialsFactory; - private final CredentialsFactory credentialsFactory; - private final CredentialFactory credentialFactory; private final TxManager txManager; private final UserService userService; - private final CredentialRepository credentialRepository; private final PasswordResetter passwordResetter; public UserCredentialsServiceImpl( AuthenticationService authenticationService, - AuthorizationService authorizationService, PermissionFactory permissionFactory, - UserCredentialsFactory userCredentialsFactory, CredentialsFactory credentialsFactory, - CredentialFactory credentialFactory, + AuthorizationService authorizationService, TxManager txManager, UserService userService, - CredentialRepository credentialRepository, PasswordResetter passwordResetter) { this.authenticationService = authenticationService; this.authorizationService = authorizationService; - this.permissionFactory = permissionFactory; - this.userCredentialsFactory = userCredentialsFactory; - this.credentialsFactory = credentialsFactory; - this.credentialFactory = credentialFactory; this.txManager = txManager; this.userService = userService; - this.credentialRepository = credentialRepository; this.passwordResetter = passwordResetter; } @@ -91,13 +76,13 @@ public Credential changePassword(KapuaId scopeId, KapuaId userId, PasswordChange final User user = Optional.ofNullable(KapuaSecurityUtils.doPrivileged(() -> userService.find(scopeId, userId)) ).orElseThrow(() -> new KapuaEntityNotFoundException(User.TYPE, userId)); return txManager.execute(tx -> { - final UsernamePasswordCredentials usernamePasswordCredentials = credentialsFactory.newUsernamePasswordCredentials(user.getName(), passwordChangeRequest.getCurrentPassword()); + final UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials(user.getName(), passwordChangeRequest.getCurrentPassword()); try { authenticationService.verifyCredentials(usernamePasswordCredentials); } catch (KapuaAuthenticationException e) { throw new KapuaAuthenticationException(KapuaAuthenticationErrorCodes.INCORRECT_CURRENT_PASSWORD); } - final PasswordResetRequest passwordResetRequest = userCredentialsFactory.newPasswordResetRequest(); + final PasswordResetRequest passwordResetRequest = new PasswordResetRequest(); passwordResetRequest.setNewPassword(passwordChangeRequest.getNewPassword()); try { return passwordResetter.resetPassword(tx, scopeId, userId, true, passwordResetRequest); @@ -107,7 +92,6 @@ public Credential changePassword(KapuaId scopeId, KapuaId userId, PasswordChange }); } - @Override public Credential resetPassword(KapuaId scopeId, KapuaId credentialId, PasswordResetRequest passwordResetRequest) throws KapuaException { // Argument Validation @@ -116,7 +100,7 @@ public Credential resetPassword(KapuaId scopeId, KapuaId credentialId, PasswordR ArgumentValidator.notNull(passwordResetRequest.getNewPassword(), "passwordResetRequest.newPassword"); // Check accessauth - authorizationService.checkPermission(permissionFactory.newPermission(Domains.CREDENTIAL, Actions.write, scopeId)); + authorizationService.checkPermission(new Permission(Domains.CREDENTIAL, Actions.write, scopeId)); return txManager.execute(tx -> passwordResetter.resetPassword(tx, scopeId, credentialId, passwordResetRequest)); } diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessInfoCreatorImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessInfoCreatorImpl.java deleted file mode 100644 index 6a941e9faf0..00000000000 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessInfoCreatorImpl.java +++ /dev/null @@ -1,97 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authorization.access.shiro; - -import org.eclipse.kapua.commons.model.AbstractKapuaEntityCreator; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.authorization.access.AccessInfo; -import org.eclipse.kapua.service.authorization.access.AccessInfoCreator; -import org.eclipse.kapua.service.authorization.permission.Permission; - -import java.util.HashSet; -import java.util.Set; - -/** - * Access info creator service implementation. - * - * @since 1.0 - */ -public class AccessInfoCreatorImpl extends AbstractKapuaEntityCreator implements AccessInfoCreator { - - private static final long serialVersionUID = 972154225756734130L; - - private KapuaId userId; - private Set roleIds; - private Set permissions; - - /** - * Constructor - * - * @param accessInfo - */ - @SuppressWarnings({"rawtypes", "unchecked"}) - public AccessInfoCreatorImpl(AccessInfoCreator accessInfo) { - super((AbstractKapuaEntityCreator) accessInfo); - - setUserId(accessInfo.getUserId()); - setRoleIds(accessInfo.getRoleIds()); - setPermissions(accessInfo.getPermissions()); - } - - /** - * Constructor - * - * @param scopeId - */ - public AccessInfoCreatorImpl(KapuaId scopeId) { - super(scopeId); - } - - @Override - public void setUserId(KapuaId userId) { - this.userId = userId; - } - - @Override - public KapuaId getUserId() { - return userId; - } - - @Override - public void setRoleIds(Set roleIds) { - this.roleIds = roleIds; - } - - @Override - public Set getRoleIds() { - if (roleIds == null) { - roleIds = new HashSet<>(); - } - return roleIds; - } - - @Override - public void setPermissions(Set permissions) { - this.permissions = permissions; - - } - - @Override - public Set getPermissions() { - if (permissions == null) { - permissions = new HashSet<>(); - } - return permissions; - } - -} diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessInfoFactoryImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessInfoFactoryImpl.java index e98d2993560..09043c27cd8 100644 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessInfoFactoryImpl.java +++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessInfoFactoryImpl.java @@ -12,15 +12,12 @@ *******************************************************************************/ package org.eclipse.kapua.service.authorization.access.shiro; +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaEntityCloneException; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.authorization.access.AccessInfo; -import org.eclipse.kapua.service.authorization.access.AccessInfoCreator; import org.eclipse.kapua.service.authorization.access.AccessInfoFactory; -import org.eclipse.kapua.service.authorization.access.AccessInfoListResult; -import org.eclipse.kapua.service.authorization.access.AccessInfoQuery; - -import javax.inject.Singleton; /** * {@link AccessInfoFactory} implementation. @@ -35,21 +32,6 @@ public AccessInfo newEntity(KapuaId scopeId) { return new AccessInfoImpl(); } - @Override - public AccessInfoCreator newCreator(KapuaId scopeId) { - return new AccessInfoCreatorImpl(scopeId); - } - - @Override - public AccessInfoQuery newQuery(KapuaId scopeId) { - return new AccessInfoQueryImpl(scopeId); - } - - @Override - public AccessInfoListResult newListResult() { - return new AccessInfoListResultImpl(); - } - @Override public AccessInfo clone(AccessInfo accessInfo) { try { diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessInfoImplJpaRepository.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessInfoImplJpaRepository.java index 0c9934bbec5..709335bcbb2 100644 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessInfoImplJpaRepository.java +++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessInfoImplJpaRepository.java @@ -12,6 +12,8 @@ *******************************************************************************/ package org.eclipse.kapua.service.authorization.access.shiro; +import java.util.Optional; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.commons.jpa.KapuaJpaRepositoryConfiguration; import org.eclipse.kapua.commons.jpa.KapuaUpdatableEntityJpaRepository; @@ -22,13 +24,12 @@ import org.eclipse.kapua.service.authorization.access.AccessInfoRepository; import org.eclipse.kapua.storage.TxContext; -import java.util.Optional; - public class AccessInfoImplJpaRepository extends KapuaUpdatableEntityJpaRepository implements AccessInfoRepository { + public AccessInfoImplJpaRepository(KapuaJpaRepositoryConfiguration jpaRepoConfig) { - super(AccessInfoImpl.class, AccessInfo.TYPE, () -> new AccessInfoListResultImpl(), jpaRepoConfig); + super(AccessInfoImpl.class, AccessInfo.TYPE, () -> new AccessInfoListResult(), jpaRepoConfig); } @Override diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessInfoListResultImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessInfoListResultImpl.java deleted file mode 100644 index 8f8cf15910a..00000000000 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessInfoListResultImpl.java +++ /dev/null @@ -1,28 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authorization.access.shiro; - -import org.eclipse.kapua.commons.model.query.KapuaListResultImpl; -import org.eclipse.kapua.service.authorization.access.AccessInfo; -import org.eclipse.kapua.service.authorization.access.AccessInfoListResult; - -/** - * Access info list result implementation. - * - * @since 1.0 - * - */ -public class AccessInfoListResultImpl extends KapuaListResultImpl implements AccessInfoListResult { - - static final long serialVersionUID = 2231053707705207563L; -} diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessInfoQueryImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessInfoQueryImpl.java deleted file mode 100644 index 2bf8c254ce0..00000000000 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessInfoQueryImpl.java +++ /dev/null @@ -1,45 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authorization.access.shiro; - -import org.eclipse.kapua.commons.model.query.AbstractKapuaQuery; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.authorization.access.AccessInfoQuery; - -/** - * {@link AccessInfoQuery} implementation. - * - * @since 1.0.0 - */ -public class AccessInfoQueryImpl extends AbstractKapuaQuery implements AccessInfoQuery { - - /** - * Constructor. - * - * @since 1.0.0 - */ - public AccessInfoQueryImpl() { - super(); - } - - /** - * Constructor. - * - * @param scopeId The {@link #getScopeId()}. - * @since 1.0.0 - */ - public AccessInfoQueryImpl(KapuaId scopeId) { - this(); - setScopeId(scopeId); - } -} diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessInfoServiceImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessInfoServiceImpl.java index cd226537484..f25263904d7 100644 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessInfoServiceImpl.java +++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessInfoServiceImpl.java @@ -12,6 +12,8 @@ *******************************************************************************/ package org.eclipse.kapua.service.authorization.access.shiro; +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaEntityNotFoundException; import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.commons.model.domains.Domains; @@ -24,21 +26,17 @@ import org.eclipse.kapua.service.authorization.access.AccessInfo; import org.eclipse.kapua.service.authorization.access.AccessInfoAttributes; import org.eclipse.kapua.service.authorization.access.AccessInfoCreator; -import org.eclipse.kapua.service.authorization.access.AccessInfoFactory; import org.eclipse.kapua.service.authorization.access.AccessInfoListResult; -import org.eclipse.kapua.service.authorization.access.AccessInfoQuery; import org.eclipse.kapua.service.authorization.access.AccessInfoRepository; import org.eclipse.kapua.service.authorization.access.AccessInfoService; import org.eclipse.kapua.service.authorization.access.AccessPermission; import org.eclipse.kapua.service.authorization.access.AccessPermissionCreator; -import org.eclipse.kapua.service.authorization.access.AccessPermissionFactory; import org.eclipse.kapua.service.authorization.access.AccessPermissionRepository; import org.eclipse.kapua.service.authorization.access.AccessRole; import org.eclipse.kapua.service.authorization.access.AccessRoleCreator; import org.eclipse.kapua.service.authorization.access.AccessRoleFactory; import org.eclipse.kapua.service.authorization.access.AccessRoleRepository; import org.eclipse.kapua.service.authorization.permission.Permission; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; import org.eclipse.kapua.service.authorization.permission.shiro.PermissionValidator; import org.eclipse.kapua.service.authorization.role.Role; import org.eclipse.kapua.service.authorization.role.RoleRepository; @@ -46,8 +44,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.inject.Singleton; - /** * {@link AccessInfoService} implementation based on JPA. * @@ -58,38 +54,29 @@ public class AccessInfoServiceImpl implements AccessInfoService { private static final Logger LOGGER = LoggerFactory.getLogger(AccessInfoServiceImpl.class); private final AuthorizationService authorizationService; - private final PermissionFactory permissionFactory; private final TxManager txManager; private final RoleRepository roleRepository; private final AccessRoleRepository accessRoleRepository; private final AccessRoleFactory accessRoleFactory; private final AccessInfoRepository accessInfoRepository; - private final AccessInfoFactory accessInfoFactory; private final AccessPermissionRepository accessPermissionRepository; - private final AccessPermissionFactory accessPermissionFactory; private final PermissionValidator permissionValidator; public AccessInfoServiceImpl(AuthorizationService authorizationService, - PermissionFactory permissionFactory, - TxManager txManager, - RoleRepository roleRepository, - AccessRoleFactory accessRoleFactory, - AccessRoleRepository accessRoleRepository, - AccessInfoRepository accessInfoRepository, - AccessInfoFactory accessInfoFactory, - AccessPermissionRepository accessPermissionRepository, - AccessPermissionFactory accessPermissionFactory, - PermissionValidator permissionValidator) { + TxManager txManager, + RoleRepository roleRepository, + AccessRoleFactory accessRoleFactory, + AccessRoleRepository accessRoleRepository, + AccessInfoRepository accessInfoRepository, + AccessPermissionRepository accessPermissionRepository, + PermissionValidator permissionValidator) { this.authorizationService = authorizationService; - this.permissionFactory = permissionFactory; this.txManager = txManager; this.roleRepository = roleRepository; this.accessRoleFactory = accessRoleFactory; this.accessRoleRepository = accessRoleRepository; this.accessInfoRepository = accessInfoRepository; - this.accessInfoFactory = accessInfoFactory; this.accessPermissionRepository = accessPermissionRepository; - this.accessPermissionFactory = accessPermissionFactory; this.permissionValidator = permissionValidator; } @@ -98,7 +85,7 @@ public AccessInfo create(AccessInfoCreator accessInfoCreator) throws KapuaException { ArgumentValidator.notNull(accessInfoCreator, "accessInfoCreator"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.ACCESS_INFO, Actions.write, accessInfoCreator.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.ACCESS_INFO, Actions.write, accessInfoCreator.getScopeId())); // If permission are created out of the access info scope, check that the current user has the permission on the external scopeId. if (accessInfoCreator.getPermissions() != null) { for (Permission p : accessInfoCreator.getPermissions()) { @@ -125,7 +112,7 @@ public AccessInfo create(AccessInfoCreator accessInfoCreator) if (!accessInfoCreator.getPermissions().isEmpty()) { for (Permission p : accessInfoCreator.getPermissions()) { - AccessPermissionCreator accessPermissionCreator = accessPermissionFactory.newCreator(accessInfoCreator.getScopeId()); + AccessPermissionCreator accessPermissionCreator = new AccessPermissionCreator(accessInfoCreator.getScopeId()); accessPermissionCreator.setAccessInfoId(accessInfo.getId()); accessPermissionCreator.setPermission(p); @@ -140,7 +127,7 @@ public AccessInfo create(AccessInfoCreator accessInfoCreator) if (!accessInfoCreator.getRoleIds().isEmpty()) { for (KapuaId roleId : accessInfoCreator.getRoleIds()) { - AccessRoleCreator accessRoleCreator = accessRoleFactory.newCreator(accessInfoCreator.getScopeId()); + AccessRoleCreator accessRoleCreator = new AccessRoleCreator(accessInfoCreator.getScopeId()); accessRoleCreator.setAccessInfoId(accessInfo.getId()); accessRoleCreator.setRoleId(roleId); @@ -163,7 +150,7 @@ public AccessInfo find(KapuaId scopeId, KapuaId accessInfoId) ArgumentValidator.notNull(scopeId, "accountId"); ArgumentValidator.notNull(accessInfoId, "accessInfoId"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.ACCESS_INFO, Actions.read, scopeId)); + authorizationService.checkPermission(new Permission(Domains.ACCESS_INFO, Actions.read, scopeId)); return txManager.execute(tx -> accessInfoRepository.find(tx, scopeId, accessInfoId)) .orElse(null); @@ -174,7 +161,7 @@ public AccessInfo findByUserId(KapuaId scopeId, KapuaId userId) throws KapuaExce ArgumentValidator.notNull(scopeId, "accountId"); ArgumentValidator.notNull(userId, "userId"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.ACCESS_INFO, Actions.read, scopeId)); + authorizationService.checkPermission(new Permission(Domains.ACCESS_INFO, Actions.read, scopeId)); return txManager.execute(tx -> accessInfoRepository.findByUserId(tx, scopeId, userId)) .orElse(null); @@ -185,7 +172,7 @@ public AccessInfoListResult query(KapuaQuery query) throws KapuaException { ArgumentValidator.notNull(query, "query"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.ACCESS_INFO, Actions.read, query.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.ACCESS_INFO, Actions.read, query.getScopeId())); return txManager.execute(tx -> accessInfoRepository.query(tx, query)); } @@ -195,7 +182,7 @@ public long count(KapuaQuery query) throws KapuaException { ArgumentValidator.notNull(query, "query"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.ACCESS_INFO, Actions.read, query.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.ACCESS_INFO, Actions.read, query.getScopeId())); return txManager.execute(tx -> accessInfoRepository.count(tx, query)); } @@ -203,7 +190,7 @@ public long count(KapuaQuery query) @Override public void delete(KapuaId scopeId, KapuaId accessInfoId) throws KapuaException { // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.ACCESS_INFO, Actions.delete, scopeId)); + authorizationService.checkPermission(new Permission(Domains.ACCESS_INFO, Actions.delete, scopeId)); txManager.execute(tx -> accessInfoRepository.delete(tx, scopeId, accessInfoId)); } @@ -223,7 +210,7 @@ public void onKapuaEvent(ServiceEvent kapuaEvent) throws KapuaException { } private void deleteAccessInfoByUserId(KapuaId scopeId, KapuaId userId) throws KapuaException { - AccessInfoQuery query = accessInfoFactory.newQuery(scopeId); + final KapuaQuery query = new KapuaQuery(scopeId); query.setPredicate(query.attributePredicate(AccessInfoAttributes.USER_ID, userId)); AccessInfoListResult accessInfosToDelete = query(query); @@ -234,7 +221,7 @@ private void deleteAccessInfoByUserId(KapuaId scopeId, KapuaId userId) throws Ka } private void deleteAccessInfoByAccountId(KapuaId scopeId, KapuaId accountId) throws KapuaException { - AccessInfoQuery query = accessInfoFactory.newQuery(accountId); + final KapuaQuery query = new KapuaQuery(scopeId); AccessInfoListResult accessInfosToDelete = query(query); diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessPermissionCreatorImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessPermissionCreatorImpl.java deleted file mode 100644 index 758b71ffdd3..00000000000 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessPermissionCreatorImpl.java +++ /dev/null @@ -1,58 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authorization.access.shiro; - -import org.eclipse.kapua.commons.model.AbstractKapuaEntityCreator; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.authorization.access.AccessPermission; -import org.eclipse.kapua.service.authorization.access.AccessPermissionCreator; -import org.eclipse.kapua.service.authorization.permission.Permission; - -/** - * {@link AccessPermission} creator implementation. - * - * @since 1.0.0 - */ -public class AccessPermissionCreatorImpl extends AbstractKapuaEntityCreator implements AccessPermissionCreator { - - private static final long serialVersionUID = 972154225756734130L; - - private KapuaId accessInfo; - private Permission permission; - - /** - * Constructor - * - * @param scopeId - */ - public AccessPermissionCreatorImpl(KapuaId scopeId) { - super(scopeId); - } - - public KapuaId getAccessInfoId() { - return accessInfo; - } - - public void setAccessInfoId(KapuaId accessInfo) { - this.accessInfo = accessInfo; - } - - @SuppressWarnings("unchecked") - public Permission getPermission() { - return permission; - } - - public void setPermission(Permission permission) { - this.permission = permission; - } -} diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessPermissionFactoryImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessPermissionFactoryImpl.java index 581f01ac3e4..9d85d6a7fc3 100644 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessPermissionFactoryImpl.java +++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessPermissionFactoryImpl.java @@ -12,14 +12,11 @@ *******************************************************************************/ package org.eclipse.kapua.service.authorization.access.shiro; +import javax.inject.Singleton; + import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.authorization.access.AccessPermission; -import org.eclipse.kapua.service.authorization.access.AccessPermissionCreator; import org.eclipse.kapua.service.authorization.access.AccessPermissionFactory; -import org.eclipse.kapua.service.authorization.access.AccessPermissionListResult; -import org.eclipse.kapua.service.authorization.access.AccessPermissionQuery; - -import javax.inject.Singleton; /** * {@link AccessPermissionFactory} implementation. @@ -34,21 +31,6 @@ public AccessPermission newEntity(KapuaId scopeId) { return new AccessPermissionImpl(scopeId); } - @Override - public AccessPermissionCreator newCreator(KapuaId scopeId) { - return new AccessPermissionCreatorImpl(scopeId); - } - - @Override - public AccessPermissionQuery newQuery(KapuaId scopeId) { - return new AccessPermissionQueryImpl(scopeId); - } - - @Override - public AccessPermissionListResult newListResult() { - return new AccessPermissionListResultImpl(); - } - @Override public AccessPermission clone(AccessPermission accessPermission) { return new AccessPermissionImpl(accessPermission); diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessPermissionImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessPermissionImpl.java index 4b2054d3429..b734c647332 100644 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessPermissionImpl.java +++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessPermissionImpl.java @@ -12,13 +12,6 @@ *******************************************************************************/ package org.eclipse.kapua.service.authorization.access.shiro; -import org.eclipse.kapua.commons.model.AbstractKapuaEntity; -import org.eclipse.kapua.commons.model.id.KapuaEid; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.authorization.access.AccessPermission; -import org.eclipse.kapua.service.authorization.permission.Permission; -import org.eclipse.kapua.service.authorization.permission.shiro.PermissionImpl; - import javax.persistence.AttributeOverride; import javax.persistence.AttributeOverrides; import javax.persistence.Column; @@ -26,6 +19,13 @@ import javax.persistence.Entity; import javax.persistence.Table; +import org.eclipse.kapua.commons.model.AbstractKapuaEntity; +import org.eclipse.kapua.commons.model.id.KapuaEid; +import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.service.authorization.access.AccessPermission; +import org.eclipse.kapua.service.authorization.permission.Permission; +import org.eclipse.kapua.service.authorization.permission.shiro.PermissionImpl; + /** * {@link AccessPermission} implementation. * @@ -58,7 +58,8 @@ protected AccessPermissionImpl() { /** * Constructor. * - * @param scopeId The scope {@link KapuaId} to set into the {@link AccessPermission} + * @param scopeId + * The scope {@link KapuaId} to set into the {@link AccessPermission} * @since 1.0.0 */ public AccessPermissionImpl(KapuaId scopeId) { @@ -92,14 +93,16 @@ public KapuaId getAccessInfoId() { public void setPermission(Permission permission) { PermissionImpl permissionImpl = null; if (permission != null) { - permissionImpl = permission instanceof PermissionImpl ? (PermissionImpl) permission : new PermissionImpl(permission); + permissionImpl = new PermissionImpl(permission); } this.permission = permissionImpl; } @Override public Permission getPermission() { - return permission != null ? permission : new PermissionImpl(null, null, null, null); + return permission != null + ? new Permission(permission.getDomain(), permission.getAction(), permission.getTargetScopeId(), permission.getGroupId(), permission.getForwardable()) + : new Permission(null, null, null); } @Override diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessPermissionImplJpaRepository.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessPermissionImplJpaRepository.java index 89b00901402..9d0c9d8f17c 100644 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessPermissionImplJpaRepository.java +++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessPermissionImplJpaRepository.java @@ -12,6 +12,15 @@ *******************************************************************************/ package org.eclipse.kapua.service.authorization.access.shiro; +import java.util.List; +import java.util.stream.Collectors; + +import javax.persistence.EntityManager; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaDelete; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Root; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.commons.jpa.JpaAwareTxContext; import org.eclipse.kapua.commons.jpa.KapuaEntityJpaRepository; @@ -19,33 +28,25 @@ import org.eclipse.kapua.commons.model.id.KapuaEid; import org.eclipse.kapua.model.domain.Actions; import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.service.authorization.access.AccessPermission; import org.eclipse.kapua.service.authorization.access.AccessPermissionAttributes; import org.eclipse.kapua.service.authorization.access.AccessPermissionListResult; -import org.eclipse.kapua.service.authorization.access.AccessPermissionQuery; import org.eclipse.kapua.service.authorization.access.AccessPermissionRepository; import org.eclipse.kapua.service.authorization.permission.shiro.PermissionImpl_; import org.eclipse.kapua.storage.TxContext; -import javax.persistence.EntityManager; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaDelete; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Root; -import java.util.List; -import java.util.stream.Collectors; - public class AccessPermissionImplJpaRepository extends KapuaEntityJpaRepository implements AccessPermissionRepository { public AccessPermissionImplJpaRepository(KapuaJpaRepositoryConfiguration configuration) { - super(AccessPermissionImpl.class, AccessPermission.TYPE, () -> new AccessPermissionListResultImpl(), configuration); + super(AccessPermissionImpl.class, AccessPermission.TYPE, () -> new AccessPermissionListResult(), configuration); } @Override public AccessPermissionListResult findByAccessInfoId(TxContext tx, KapuaId scopeId, KapuaId accessInfoId) throws KapuaException { - AccessPermissionQuery query = new AccessPermissionQueryImpl(scopeId); + final KapuaQuery query = new KapuaQuery(scopeId); query.setPredicate(query.attributePredicate(AccessPermissionAttributes.ACCESS_INFO_ID, accessInfoId)); return this.query(tx, query); } @@ -72,7 +73,7 @@ public AccessPermissionListResult deleteAllByDomainAndAction(TxContext tx, Strin deleteQuery.where(deleteRoot.get(AccessPermissionImpl_.id).in(resultList.stream().map(r -> r.getId()).map(KapuaEid::parseKapuaId).collect(Collectors.toList()))); em.createQuery(deleteQuery).executeUpdate(); } - final AccessPermissionListResultImpl res = new AccessPermissionListResultImpl(); + final AccessPermissionListResult res = new AccessPermissionListResult(); res.addItems(resultList); return res; } diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessPermissionListResultImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessPermissionListResultImpl.java deleted file mode 100644 index 0a12dd615f8..00000000000 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessPermissionListResultImpl.java +++ /dev/null @@ -1,28 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authorization.access.shiro; - -import org.eclipse.kapua.commons.model.query.KapuaListResultImpl; -import org.eclipse.kapua.service.authorization.access.AccessPermission; -import org.eclipse.kapua.service.authorization.access.AccessPermissionListResult; - -/** - * {@link AccessPermission} list result implementation. - * - * @since 1.0.0 - * - */ -public class AccessPermissionListResultImpl extends KapuaListResultImpl implements AccessPermissionListResult { - - private static final long serialVersionUID = -7673771564266332772L; -} diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessPermissionQueryImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessPermissionQueryImpl.java deleted file mode 100644 index bd8bfaf7d0e..00000000000 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessPermissionQueryImpl.java +++ /dev/null @@ -1,45 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authorization.access.shiro; - -import org.eclipse.kapua.commons.model.query.AbstractKapuaQuery; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.authorization.access.AccessPermissionQuery; - -/** - * {@link AccessPermissionQuery} implementation. - * - * @since 1.0.0 - */ -public class AccessPermissionQueryImpl extends AbstractKapuaQuery implements AccessPermissionQuery { - - /** - * Constructor. - * - * @since 1.0.0 - */ - public AccessPermissionQueryImpl() { - super(); - } - - /** - * Constructor. - * - * @param scopeId The {@link #getScopeId()}. - * @since 1.0.0 - */ - public AccessPermissionQueryImpl(KapuaId scopeId) { - this(); - setScopeId(scopeId); - } -} diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessPermissionServiceImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessPermissionServiceImpl.java index 95831541558..73f9b7697a9 100644 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessPermissionServiceImpl.java +++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessPermissionServiceImpl.java @@ -12,6 +12,14 @@ *******************************************************************************/ package org.eclipse.kapua.service.authorization.access.shiro; +import java.util.AbstractMap; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import javax.inject.Inject; +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaEntityNotFoundException; import org.eclipse.kapua.KapuaEntityUniquenessException; import org.eclipse.kapua.KapuaException; @@ -28,21 +36,12 @@ import org.eclipse.kapua.service.authorization.access.AccessPermissionAttributes; import org.eclipse.kapua.service.authorization.access.AccessPermissionCreator; import org.eclipse.kapua.service.authorization.access.AccessPermissionListResult; -import org.eclipse.kapua.service.authorization.access.AccessPermissionQuery; import org.eclipse.kapua.service.authorization.access.AccessPermissionRepository; import org.eclipse.kapua.service.authorization.access.AccessPermissionService; import org.eclipse.kapua.service.authorization.permission.Permission; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; import org.eclipse.kapua.service.authorization.permission.shiro.PermissionValidator; import org.eclipse.kapua.storage.TxManager; -import javax.inject.Inject; -import javax.inject.Singleton; -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - /** * {@link AccessPermission} service implementation. * @@ -52,7 +51,6 @@ public class AccessPermissionServiceImpl implements AccessPermissionService { private final AuthorizationService authorizationService; - private final PermissionFactory permissionFactory; private final TxManager txManager; private final AccessPermissionRepository accessPermissionRepository; private final AccessInfoRepository accessInfoRepository; @@ -61,13 +59,11 @@ public class AccessPermissionServiceImpl implements AccessPermissionService { @Inject public AccessPermissionServiceImpl( AuthorizationService authorizationService, - PermissionFactory permissionFactory, TxManager txManager, AccessPermissionRepository accessPermissionRepository, AccessInfoRepository accessInfoRepository, PermissionValidator permissionValidator) { this.authorizationService = authorizationService; - this.permissionFactory = permissionFactory; this.txManager = txManager; this.accessPermissionRepository = accessPermissionRepository; this.accessInfoRepository = accessInfoRepository; @@ -82,7 +78,7 @@ public AccessPermission create(AccessPermissionCreator accessPermissionCreator) ArgumentValidator.notNull(accessPermissionCreator.getAccessInfoId(), "accessPermissionCreator.accessInfoId"); ArgumentValidator.notNull(accessPermissionCreator.getPermission(), "accessPermissionCreator.permission"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.ACCESS_INFO, Actions.write, accessPermissionCreator.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.ACCESS_INFO, Actions.write, accessPermissionCreator.getScopeId())); // If permission are created out of the access permission scope, check that the current user has the permission on the external scopeId. final Permission permission = accessPermissionCreator.getPermission(); if (permission.getTargetScopeId() == null || !permission.getTargetScopeId().equals(accessPermissionCreator.getScopeId())) { @@ -93,7 +89,7 @@ public AccessPermission create(AccessPermissionCreator accessPermissionCreator) return txManager.execute(tx -> { // Check duplicates - AccessPermissionQuery query = new AccessPermissionQueryImpl(accessPermissionCreator.getScopeId()); + KapuaQuery query = new KapuaQuery(accessPermissionCreator.getScopeId()); query.setPredicate( query.andPredicate( query.attributePredicate(KapuaEntityAttributes.SCOPE_ID, accessPermissionCreator.getScopeId()), @@ -135,7 +131,7 @@ public void delete(KapuaId scopeId, KapuaId accessPermissionId) throws KapuaExce ArgumentValidator.notNull(accessPermissionId, KapuaEntityAttributes.ENTITY_ID); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.ACCESS_INFO, Actions.delete, scopeId)); + authorizationService.checkPermission(new Permission(Domains.ACCESS_INFO, Actions.delete, scopeId)); txManager.execute(tx -> accessPermissionRepository.delete(tx, scopeId, accessPermissionId)); } @@ -146,7 +142,7 @@ public AccessPermission find(KapuaId scopeId, KapuaId accessPermissionId) ArgumentValidator.notNull(scopeId, KapuaEntityAttributes.SCOPE_ID); ArgumentValidator.notNull(accessPermissionId, KapuaEntityAttributes.ENTITY_ID); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.ACCESS_INFO, Actions.read, scopeId)); + authorizationService.checkPermission(new Permission(Domains.ACCESS_INFO, Actions.read, scopeId)); return txManager.execute(tx -> accessPermissionRepository.find(tx, scopeId, accessPermissionId)) .orElse(null); } @@ -157,7 +153,7 @@ public AccessPermissionListResult findByAccessInfoId(KapuaId scopeId, KapuaId ac ArgumentValidator.notNull(scopeId, KapuaEntityAttributes.SCOPE_ID); ArgumentValidator.notNull(accessInfoId, "accessInfoId"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.ACCESS_INFO, + authorizationService.checkPermission(new Permission(Domains.ACCESS_INFO, Actions.read, scopeId)); return txManager.execute(tx -> accessPermissionRepository.findByAccessInfoId(tx, scopeId, accessInfoId)); @@ -168,7 +164,7 @@ public AccessPermissionListResult query(KapuaQuery query) throws KapuaException { ArgumentValidator.notNull(query, "query"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.ACCESS_INFO, Actions.read, query.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.ACCESS_INFO, Actions.read, query.getScopeId())); return txManager.execute(tx -> accessPermissionRepository.query(tx, query)); } @@ -177,7 +173,7 @@ public long count(KapuaQuery query) throws KapuaException { ArgumentValidator.notNull(query, "query"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.ACCESS_INFO, Actions.read, query.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.ACCESS_INFO, Actions.read, query.getScopeId())); return txManager.execute(tx -> accessPermissionRepository.count(tx, query)); } } diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessRoleCreatorImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessRoleCreatorImpl.java deleted file mode 100644 index abfb6941875..00000000000 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessRoleCreatorImpl.java +++ /dev/null @@ -1,62 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authorization.access.shiro; - -import org.eclipse.kapua.commons.model.AbstractKapuaEntityCreator; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.authorization.access.AccessRole; -import org.eclipse.kapua.service.authorization.access.AccessRoleCreator; - -/** - * {@link AccessRole} creator implementation. - * - * @since 1.0.0 - * - */ -public class AccessRoleCreatorImpl extends AbstractKapuaEntityCreator implements AccessRoleCreator { - - private static final long serialVersionUID = 972154225756734130L; - - private KapuaId accessInfo; - private KapuaId roleId; - - /** - * Constructor - * - * @param scopeId - */ - public AccessRoleCreatorImpl(KapuaId scopeId) { - super(scopeId); - } - - @Override - public KapuaId getAccessInfoId() { - return accessInfo; - } - - @Override - public void setAccessInfoId(KapuaId accessInfo) { - this.accessInfo = accessInfo; - } - - @Override - public KapuaId getRoleId() { - return roleId; - } - - @Override - public void setRoleId(KapuaId roleId) { - this.roleId = roleId; - } - -} diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessRoleFactoryImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessRoleFactoryImpl.java index cb12d7f2f8c..86a41a20f51 100644 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessRoleFactoryImpl.java +++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessRoleFactoryImpl.java @@ -12,15 +12,12 @@ *******************************************************************************/ package org.eclipse.kapua.service.authorization.access.shiro; +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaEntityCloneException; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.authorization.access.AccessRole; -import org.eclipse.kapua.service.authorization.access.AccessRoleCreator; import org.eclipse.kapua.service.authorization.access.AccessRoleFactory; -import org.eclipse.kapua.service.authorization.access.AccessRoleListResult; -import org.eclipse.kapua.service.authorization.access.AccessRoleQuery; - -import javax.inject.Singleton; /** * {@link AccessRoleFactory} implementation. @@ -35,21 +32,6 @@ public AccessRole newEntity(KapuaId scopeId) { return new AccessRoleImpl(scopeId); } - @Override - public AccessRoleCreator newCreator(KapuaId scopeId) { - return new AccessRoleCreatorImpl(scopeId); - } - - @Override - public AccessRoleQuery newQuery(KapuaId scopeId) { - return new AccessRoleQueryImpl(scopeId); - } - - @Override - public AccessRoleListResult newListResult() { - return new AccessRoleListResultImpl(); - } - @Override public AccessRole clone(AccessRole accessRole) { try { diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessRoleImplJpaRepository.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessRoleImplJpaRepository.java index d3d208507e9..b9346e504cc 100644 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessRoleImplJpaRepository.java +++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessRoleImplJpaRepository.java @@ -25,8 +25,9 @@ public class AccessRoleImplJpaRepository extends KapuaEntityJpaRepository implements AccessRoleRepository { + public AccessRoleImplJpaRepository(KapuaJpaRepositoryConfiguration configuration) { - super(AccessRoleImpl.class, AccessRole.TYPE, () -> new AccessRoleListResultImpl(), configuration); + super(AccessRoleImpl.class, AccessRole.TYPE, () -> new AccessRoleListResult(), configuration); } @Override diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessRoleListResultImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessRoleListResultImpl.java deleted file mode 100644 index 34d3db38048..00000000000 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessRoleListResultImpl.java +++ /dev/null @@ -1,28 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authorization.access.shiro; - -import org.eclipse.kapua.commons.model.query.KapuaListResultImpl; -import org.eclipse.kapua.service.authorization.access.AccessRole; -import org.eclipse.kapua.service.authorization.access.AccessRoleListResult; - -/** - * {@link AccessRole} list result implementation. - * - * @since 1.0.0 - * - */ -public class AccessRoleListResultImpl extends KapuaListResultImpl implements AccessRoleListResult { - - private static final long serialVersionUID = 2406073775830391702L; -} diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessRoleQueryImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessRoleQueryImpl.java deleted file mode 100644 index 30d4a79ca4c..00000000000 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessRoleQueryImpl.java +++ /dev/null @@ -1,45 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authorization.access.shiro; - -import org.eclipse.kapua.commons.model.query.AbstractKapuaQuery; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.authorization.access.AccessRoleQuery; - -/** - * {@link AccessRoleQuery} implementation. - * - * @since 1.0.0 - */ -public class AccessRoleQueryImpl extends AbstractKapuaQuery implements AccessRoleQuery { - - /** - * Constructor. - * - * @since 1.0.0 - */ - public AccessRoleQueryImpl() { - super(); - } - - /** - * Constructor. - * - * @param scopeId The {@link #getScopeId()}. - * @since 1.0.0 - */ - public AccessRoleQueryImpl(KapuaId scopeId) { - this(); - setScopeId(scopeId); - } -} diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessRoleServiceImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessRoleServiceImpl.java index bd32f1e561e..70e11de7f0c 100644 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessRoleServiceImpl.java +++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/AccessRoleServiceImpl.java @@ -12,6 +12,9 @@ *******************************************************************************/ package org.eclipse.kapua.service.authorization.access.shiro; +import javax.inject.Inject; +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaDuplicateNameException; import org.eclipse.kapua.KapuaEntityNotFoundException; import org.eclipse.kapua.KapuaException; @@ -28,18 +31,14 @@ import org.eclipse.kapua.service.authorization.access.AccessRoleAttributes; import org.eclipse.kapua.service.authorization.access.AccessRoleCreator; import org.eclipse.kapua.service.authorization.access.AccessRoleListResult; -import org.eclipse.kapua.service.authorization.access.AccessRoleQuery; import org.eclipse.kapua.service.authorization.access.AccessRoleRepository; import org.eclipse.kapua.service.authorization.access.AccessRoleService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; +import org.eclipse.kapua.service.authorization.permission.Permission; import org.eclipse.kapua.service.authorization.role.Role; import org.eclipse.kapua.service.authorization.role.RolePermissionAttributes; import org.eclipse.kapua.service.authorization.role.RoleRepository; import org.eclipse.kapua.storage.TxManager; -import javax.inject.Inject; -import javax.inject.Singleton; - /** * {@link AccessRoleService} implementation. * @@ -53,7 +52,6 @@ public class AccessRoleServiceImpl implements AccessRoleService { private final AccessInfoRepository accessInfoRepository; private final AccessRoleRepository accessRoleRepository; private final AuthorizationService authorizationService; - private final PermissionFactory permissionFactory; @Inject public AccessRoleServiceImpl( @@ -61,14 +59,12 @@ public AccessRoleServiceImpl( RoleRepository roleRepository, AccessInfoRepository accessInfoRepository, AccessRoleRepository accessRoleRepository, - AuthorizationService authorizationService, - PermissionFactory permissionFactory) { + AuthorizationService authorizationService) { this.txManager = txManager; this.roleRepository = roleRepository; this.accessInfoRepository = accessInfoRepository; this.accessRoleRepository = accessRoleRepository; this.authorizationService = authorizationService; - this.permissionFactory = permissionFactory; } @Override @@ -78,7 +74,7 @@ public AccessRole create(AccessRoleCreator accessRoleCreator) ArgumentValidator.notNull(accessRoleCreator.getAccessInfoId(), "accessRoleCreator.accessInfoId"); ArgumentValidator.notNull(accessRoleCreator.getRoleId(), "accessRoleCreator.roleId"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.ACCESS_INFO, Actions.write, accessRoleCreator.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.ACCESS_INFO, Actions.write, accessRoleCreator.getScopeId())); return txManager.execute(tx -> { // Check that AccessInfo exists @@ -90,7 +86,7 @@ public AccessRole create(AccessRoleCreator accessRoleCreator) .orElseThrow(() -> new KapuaEntityNotFoundException(Role.TYPE, accessRoleCreator.getRoleId())); // Check that Role is not already assigned - AccessRoleQuery query = new AccessRoleQueryImpl(accessRoleCreator.getScopeId()); + final KapuaQuery query = new KapuaQuery(accessRoleCreator.getScopeId()); query.setPredicate( query.andPredicate( query.attributePredicate(AccessRoleAttributes.ACCESS_INFO_ID, accessRoleCreator.getAccessInfoId()), @@ -116,7 +112,7 @@ public AccessRole find(KapuaId scopeId, KapuaId accessRoleId) ArgumentValidator.notNull(scopeId, KapuaEntityAttributes.SCOPE_ID); ArgumentValidator.notNull(accessRoleId, KapuaEntityAttributes.ENTITY_ID); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.ACCESS_INFO, Actions.read, scopeId)); + authorizationService.checkPermission(new Permission(Domains.ACCESS_INFO, Actions.read, scopeId)); // Do find return txManager.execute(tx -> accessRoleRepository.find(tx, scopeId, accessRoleId)) .orElse(null); @@ -129,7 +125,7 @@ public AccessRoleListResult findByAccessInfoId(KapuaId scopeId, KapuaId accessIn ArgumentValidator.notNull(accessInfoId, "accessInfoId"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.ACCESS_INFO, Actions.read, scopeId)); + authorizationService.checkPermission(new Permission(Domains.ACCESS_INFO, Actions.read, scopeId)); // Check cache return txManager.execute(tx -> accessRoleRepository.findByAccessInfoId(tx, scopeId, accessInfoId)); @@ -140,7 +136,7 @@ public AccessRoleListResult query(KapuaQuery query) throws KapuaException { ArgumentValidator.notNull(query, "query"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.ACCESS_INFO, Actions.read, query.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.ACCESS_INFO, Actions.read, query.getScopeId())); // Do query return txManager.execute(tx -> accessRoleRepository.query(tx, query)); } @@ -150,7 +146,7 @@ public long count(KapuaQuery query) throws KapuaException { ArgumentValidator.notNull(query, "query"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.ACCESS_INFO, Actions.read, query.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.ACCESS_INFO, Actions.read, query.getScopeId())); // Do count return txManager.execute(tx -> accessRoleRepository.count(tx, query)); } @@ -162,7 +158,7 @@ public void delete(KapuaId scopeId, KapuaId accessRoleId) ArgumentValidator.notNull(accessRoleId, KapuaEntityAttributes.ENTITY_ID); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.ACCESS_INFO, Actions.delete, scopeId)); + authorizationService.checkPermission(new Permission(Domains.ACCESS_INFO, Actions.delete, scopeId)); // Do delete txManager.execute(tx -> accessRoleRepository.delete(tx, scopeId, accessRoleId)); } diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/CachingAccessPermissionRepository.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/CachingAccessPermissionRepository.java index 1bd6c57aaf3..c03e7e96c34 100644 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/CachingAccessPermissionRepository.java +++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/access/shiro/CachingAccessPermissionRepository.java @@ -17,16 +17,17 @@ import org.eclipse.kapua.commons.storage.KapuaEntityRepositoryCachingWrapper; import org.eclipse.kapua.model.domain.Actions; import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.service.authorization.access.AccessPermission; import org.eclipse.kapua.service.authorization.access.AccessPermissionAttributes; import org.eclipse.kapua.service.authorization.access.AccessPermissionListResult; -import org.eclipse.kapua.service.authorization.access.AccessPermissionQuery; import org.eclipse.kapua.service.authorization.access.AccessPermissionRepository; import org.eclipse.kapua.storage.TxContext; public class CachingAccessPermissionRepository extends KapuaEntityRepositoryCachingWrapper implements AccessPermissionRepository { + private final AccessPermissionRepository wrapped; public CachingAccessPermissionRepository(AccessPermissionRepository wrapped, EntityCache entityCache) { @@ -56,7 +57,7 @@ public AccessPermissionListResult findByAccessInfoId(TxContext tx, KapuaId scope AccessPermissionListResult listResult = (AccessPermissionListResult) entityCache.getList(scopeId, accessInfoId); if (listResult == null) { // Build query - AccessPermissionQuery query = new AccessPermissionQueryImpl(scopeId); + final KapuaQuery query = new KapuaQuery(scopeId); query.setPredicate(query.attributePredicate(AccessPermissionAttributes.ACCESS_INFO_ID, accessInfoId)); listResult = wrapped.findByAccessInfoId(tx, scopeId, accessInfoId); diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/domain/shiro/DomainCreatorImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/domain/shiro/DomainCreatorImpl.java deleted file mode 100644 index 864f7c13005..00000000000 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/domain/shiro/DomainCreatorImpl.java +++ /dev/null @@ -1,89 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authorization.domain.shiro; - -import org.eclipse.kapua.commons.model.AbstractKapuaEntityCreator; -import org.eclipse.kapua.model.domain.Actions; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.authorization.domain.Domain; -import org.eclipse.kapua.service.authorization.domain.DomainCreator; - -import java.util.Set; - -/** - * {@link DomainCreator} implementation - * - * @since 1.0.0 - */ -public class DomainCreatorImpl extends AbstractKapuaEntityCreator implements DomainCreator { - - private static final long serialVersionUID = -4676187845961673421L; - - private String name; - - private String serviceName; - private Set actions; - private boolean groupable; - - /** - * Constructor - * - * @param name The name to set for this {@link DomainCreator}. - * @since 1.0.0 - */ - public DomainCreatorImpl(String name) { - super((KapuaId) null); - - setName(name); - } - - @Override - public void setName(String name) { - this.name = name; - } - - public void setServiceName(String serviceName) { - this.serviceName = serviceName; - } - - @Override - public String getName() { - return name; - } - - @Override - public String getServiceName() { - return serviceName; - } - - @Override - public Set getActions() { - return actions; - } - - @Override - public void setActions(Set actions) { - this.actions = actions; - } - - @Override - public boolean getGroupable() { - return groupable; - } - - @Override - public void setGroupable(boolean groupable) { - this.groupable = groupable; - } - -} diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/domain/shiro/DomainFactoryImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/domain/shiro/DomainFactoryImpl.java index 39a0344bb18..746d0c9d0f0 100644 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/domain/shiro/DomainFactoryImpl.java +++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/domain/shiro/DomainFactoryImpl.java @@ -12,15 +12,11 @@ *******************************************************************************/ package org.eclipse.kapua.service.authorization.domain.shiro; -import org.apache.commons.lang.NotImplementedException; +import javax.inject.Singleton; + import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.authorization.domain.Domain; -import org.eclipse.kapua.service.authorization.domain.DomainCreator; import org.eclipse.kapua.service.authorization.domain.DomainFactory; -import org.eclipse.kapua.service.authorization.domain.DomainListResult; -import org.eclipse.kapua.service.authorization.domain.DomainQuery; - -import javax.inject.Singleton; /** * {@link DomainFactory} implementation. @@ -30,31 +26,11 @@ @Singleton public class DomainFactoryImpl implements DomainFactory { - @Override - public DomainCreator newCreator(String name) { - return new DomainCreatorImpl(name); - } - - @Override - public DomainListResult newListResult() { - return new DomainListResultImpl(); - } - - @Override - public DomainQuery newQuery(KapuaId scopeId) { - return new DomainQueryImpl(scopeId); - } - @Override public Domain newEntity(KapuaId scopeId) { return new DomainImpl(scopeId); } - @Override - public DomainCreator newCreator(KapuaId scopeId) { - throw new NotImplementedException(); - } - @Override public Domain clone(Domain domain) { return new DomainImpl(domain); diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/domain/shiro/DomainImplJpaRepository.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/domain/shiro/DomainImplJpaRepository.java index 26495442aa7..913362d1077 100644 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/domain/shiro/DomainImplJpaRepository.java +++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/domain/shiro/DomainImplJpaRepository.java @@ -12,6 +12,8 @@ *******************************************************************************/ package org.eclipse.kapua.service.authorization.domain.shiro; +import java.util.Optional; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.commons.jpa.KapuaEntityJpaRepository; import org.eclipse.kapua.commons.jpa.KapuaJpaRepositoryConfiguration; @@ -22,13 +24,12 @@ import org.eclipse.kapua.service.authorization.domain.DomainRepository; import org.eclipse.kapua.storage.TxContext; -import java.util.Optional; - public class DomainImplJpaRepository extends KapuaEntityJpaRepository implements DomainRepository { + public DomainImplJpaRepository(KapuaJpaRepositoryConfiguration configuration) { - super(DomainImpl.class, Domain.TYPE, () -> new DomainListResultImpl(), configuration); + super(DomainImpl.class, Domain.TYPE, () -> new DomainListResult(), configuration); } @Override diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/domain/shiro/DomainListResultImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/domain/shiro/DomainListResultImpl.java deleted file mode 100644 index f1f34c3fddf..00000000000 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/domain/shiro/DomainListResultImpl.java +++ /dev/null @@ -1,27 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authorization.domain.shiro; - -import org.eclipse.kapua.commons.model.query.KapuaListResultImpl; -import org.eclipse.kapua.service.authorization.domain.Domain; -import org.eclipse.kapua.service.authorization.domain.DomainListResult; - -/** - * {@link DomainListResult} implementation. - * - * @since 1.0.0 - */ -public class DomainListResultImpl extends KapuaListResultImpl implements DomainListResult { - - private static final long serialVersionUID = -5086830452591857912L; -} diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/domain/shiro/DomainQueryImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/domain/shiro/DomainQueryImpl.java deleted file mode 100644 index 4c0b3e8d134..00000000000 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/domain/shiro/DomainQueryImpl.java +++ /dev/null @@ -1,44 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authorization.domain.shiro; - -import org.eclipse.kapua.commons.model.query.AbstractKapuaNamedQuery; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.authorization.domain.DomainQuery; - -/** - * {@link DomainQuery} implementation. - * - * @since 1.0.0 - */ -public class DomainQueryImpl extends AbstractKapuaNamedQuery implements DomainQuery { - - /** - * Constructor. - * - * @since 1.0.0 - */ - public DomainQueryImpl() { - super(); - } - - /** - * Constructor. - * - * @param scopeId The {@link #getScopeId()}. - * @since 1.5.0 - */ - public DomainQueryImpl(KapuaId scopeId) { - super(scopeId); - } -} diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/domain/shiro/DomainRegistryServiceImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/domain/shiro/DomainRegistryServiceImpl.java index cb72c92222f..016e9a84d2e 100644 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/domain/shiro/DomainRegistryServiceImpl.java +++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/domain/shiro/DomainRegistryServiceImpl.java @@ -12,6 +12,10 @@ *******************************************************************************/ package org.eclipse.kapua.service.authorization.domain.shiro; +import java.util.Optional; + +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.commons.model.domains.Domains; import org.eclipse.kapua.commons.util.ArgumentValidator; @@ -22,19 +26,14 @@ import org.eclipse.kapua.service.authorization.AuthorizationService; import org.eclipse.kapua.service.authorization.domain.Domain; import org.eclipse.kapua.service.authorization.domain.DomainCreator; -import org.eclipse.kapua.service.authorization.domain.DomainFactory; import org.eclipse.kapua.service.authorization.domain.DomainListResult; -import org.eclipse.kapua.service.authorization.domain.DomainQuery; import org.eclipse.kapua.service.authorization.domain.DomainRegistryService; import org.eclipse.kapua.service.authorization.domain.DomainRepository; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; +import org.eclipse.kapua.service.authorization.permission.Permission; import org.eclipse.kapua.storage.TxManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.inject.Singleton; -import java.util.Optional; - /** * {@link DomainRegistryService} implementation. * @@ -46,22 +45,16 @@ public class DomainRegistryServiceImpl implements DomainRegistryService { private static final Logger LOGGER = LoggerFactory.getLogger(DomainRegistryServiceImpl.class); private final AuthorizationService authorizationService; - private final PermissionFactory permissionFactory; private final TxManager txManager; private final DomainRepository domainRepository; - private final DomainFactory domainFactory; public DomainRegistryServiceImpl( AuthorizationService authorizationService, - PermissionFactory permissionFactory, TxManager txManager, - DomainRepository domainRepository, - DomainFactory domainFactory) { + DomainRepository domainRepository) { this.authorizationService = authorizationService; - this.permissionFactory = permissionFactory; this.txManager = txManager; this.domainRepository = domainRepository; - this.domainFactory = domainFactory; } @Override @@ -72,7 +65,7 @@ public Domain create(DomainCreator domainCreator) ArgumentValidator.notNull(domainCreator.getActions(), "domainCreator.actions"); ArgumentValidator.notEmptyOrNull(domainCreator.getServiceName(), "domainCreator.serviceName"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DOMAIN, Actions.write, null)); + authorizationService.checkPermission(new Permission(Domains.DOMAIN, Actions.write, null)); Domain domain = new DomainImpl(); domain.setName(domainCreator.getName()); @@ -90,7 +83,7 @@ public Domain create(DomainCreator domainCreator) public void delete(KapuaId scopeId, KapuaId domainId) throws KapuaException { ArgumentValidator.notNull(domainId, "domainId"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DOMAIN, Actions.delete, null)); + authorizationService.checkPermission(new Permission(Domains.DOMAIN, Actions.delete, null)); txManager.execute(tx -> domainRepository.delete(tx, scopeId, domainId)); } @@ -100,7 +93,7 @@ public Domain find(KapuaId scopeId, KapuaId domainId) throws KapuaException { ArgumentValidator.notNull(domainId, "domainId"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DOMAIN, Actions.read, KapuaId.ANY)); + authorizationService.checkPermission(new Permission(Domains.DOMAIN, Actions.read, KapuaId.ANY)); return txManager.execute(tx -> domainRepository.find(tx, scopeId, domainId)) .orElse(null); @@ -114,7 +107,7 @@ public Domain findByName(String name) // Do find final Optional foundDomain = txManager.execute(tx -> domainRepository.findByName(tx, KapuaId.ANY, name)); if (foundDomain.isPresent()) { - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DOMAIN, Actions.read, KapuaId.ANY)); + authorizationService.checkPermission(new Permission(Domains.DOMAIN, Actions.read, KapuaId.ANY)); } return foundDomain .orElse(null); @@ -125,7 +118,7 @@ public DomainListResult query(KapuaQuery query) throws KapuaException { ArgumentValidator.notNull(query, "query"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DOMAIN, Actions.read, KapuaId.ANY)); + authorizationService.checkPermission(new Permission(Domains.DOMAIN, Actions.read, KapuaId.ANY)); return txManager.execute(tx -> domainRepository.query(tx, query)); } @@ -135,7 +128,7 @@ public long count(KapuaQuery query) throws KapuaException { ArgumentValidator.notNull(query, "query"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.DOMAIN, Actions.read, KapuaId.ANY)); + authorizationService.checkPermission(new Permission(Domains.DOMAIN, Actions.read, KapuaId.ANY)); return txManager.execute(tx -> domainRepository.count(tx, query)); } @@ -152,7 +145,7 @@ public void onKapuaEvent(ServiceEvent kapuaEvent) throws KapuaException { } private void deleteDomainByAccountId(KapuaId accountId) throws KapuaException { - DomainQuery query = domainFactory.newQuery(accountId); + KapuaQuery query = new KapuaQuery(accountId); DomainListResult domainsToDelete = query(query); diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/domain/shiro/DomainsAligner.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/domain/shiro/DomainsAligner.java index 9b4bf945953..01c20935ee0 100644 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/domain/shiro/DomainsAligner.java +++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/domain/shiro/DomainsAligner.java @@ -12,11 +12,22 @@ *******************************************************************************/ package org.eclipse.kapua.service.authorization.domain.shiro; +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +import javax.inject.Inject; +import javax.inject.Named; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.commons.security.KapuaSecurityUtils; import org.eclipse.kapua.locator.initializers.KapuaInitializingMethod; import org.eclipse.kapua.model.domain.Actions; import org.eclipse.kapua.model.domain.Domain; +import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.service.authorization.access.AccessPermissionRepository; import org.eclipse.kapua.service.authorization.domain.DomainRepository; import org.eclipse.kapua.service.authorization.role.RolePermissionRepository; @@ -25,16 +36,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.inject.Inject; -import javax.inject.Named; -import java.util.ArrayList; -import java.util.EnumSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.stream.Collectors; - public class DomainsAligner { + private final TxManager txManager; private final DomainRepository domainRepository; private final AccessPermissionRepository accessPermissionRepository; @@ -44,10 +47,10 @@ public class DomainsAligner { @Inject public DomainsAligner(@Named("authorizationTxManager") - TxManager txManager, - DomainRepository domainRepository, - AccessPermissionRepository accessPermissionRepository, RolePermissionRepository rolePermissionRepository, - Set knownDomains) { + TxManager txManager, + DomainRepository domainRepository, + AccessPermissionRepository accessPermissionRepository, RolePermissionRepository rolePermissionRepository, + Set knownDomains) { this.txManager = txManager; this.domainRepository = domainRepository; this.accessPermissionRepository = accessPermissionRepository; @@ -65,7 +68,7 @@ public void populate() { try { KapuaSecurityUtils.doPrivileged(() -> { txManager.execute(tx -> { - final List dbDomainEntries = domainRepository.query(tx, new DomainQueryImpl()).getItems(); + final List dbDomainEntries = domainRepository.query(tx, new KapuaQuery()).getItems(); logger.info("Found {} domain declarations in database", dbDomainEntries.size()); for (final org.eclipse.kapua.service.authorization.domain.Domain dbDomainEntry : dbDomainEntries) { @@ -87,7 +90,7 @@ public void populate() { //Align them! alignDomains(tx, dbDomainEntry, wiredDomain); } -// createMissingDomains(tx, declaredDomainsNotInDb, knownDomainsByName); + // createMissingDomains(tx, declaredDomainsNotInDb, knownDomainsByName); logger.info("Domain alignment complete!"); return null; }); diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/group/shiro/GroupCreatorImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/group/shiro/GroupCreatorImpl.java deleted file mode 100644 index bd09d40240e..00000000000 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/group/shiro/GroupCreatorImpl.java +++ /dev/null @@ -1,45 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authorization.group.shiro; - -import org.eclipse.kapua.commons.model.AbstractKapuaNamedEntityCreator; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.authorization.domain.DomainCreator; -import org.eclipse.kapua.service.authorization.group.Group; -import org.eclipse.kapua.service.authorization.group.GroupCreator; - -/** - * {@link GroupCreator} implementation. - * - * @since 1.0.0 - */ -public class GroupCreatorImpl extends AbstractKapuaNamedEntityCreator implements GroupCreator { - - private static final long serialVersionUID = -4676187845961673421L; - - /** - * Constructor - * - * @param scopeId The scope id to set. - * @param name The name to set for this {@link DomainCreator}. - * @since 1.0.0 - */ - public GroupCreatorImpl(KapuaId scopeId, String name) { - super(scopeId); - setName(name); - } - - public GroupCreatorImpl(KapuaId scopeId) { - super(scopeId); - } -} diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/group/shiro/GroupFactoryImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/group/shiro/GroupFactoryImpl.java index a0ac8e5cdae..713da386c91 100644 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/group/shiro/GroupFactoryImpl.java +++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/group/shiro/GroupFactoryImpl.java @@ -12,15 +12,12 @@ *******************************************************************************/ package org.eclipse.kapua.service.authorization.group.shiro; +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaEntityCloneException; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.authorization.group.Group; -import org.eclipse.kapua.service.authorization.group.GroupCreator; import org.eclipse.kapua.service.authorization.group.GroupFactory; -import org.eclipse.kapua.service.authorization.group.GroupListResult; -import org.eclipse.kapua.service.authorization.group.GroupQuery; - -import javax.inject.Singleton; /** * {@link GroupFactory} implementation. @@ -30,35 +27,11 @@ @Singleton public class GroupFactoryImpl implements GroupFactory { - @Override - public GroupCreator newCreator(KapuaId scopeId, String name) { - GroupCreator creator = newCreator(scopeId); - - creator.setName(name); - - return creator; - } - @Override public Group newEntity(KapuaId scopeId) { return new GroupImpl(scopeId); } - @Override - public GroupListResult newListResult() { - return new GroupListResultImpl(); - } - - @Override - public GroupQuery newQuery(KapuaId scopeId) { - return new GroupQueryImpl(scopeId); - } - - @Override - public GroupCreator newCreator(KapuaId scopeId) { - return new GroupCreatorImpl(scopeId); - } - @Override public Group clone(Group group) { try { diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/group/shiro/GroupImplJpaRepository.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/group/shiro/GroupImplJpaRepository.java index 5783607f062..0b33cdf6a36 100644 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/group/shiro/GroupImplJpaRepository.java +++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/group/shiro/GroupImplJpaRepository.java @@ -21,8 +21,9 @@ public class GroupImplJpaRepository extends KapuaNamedEntityJpaRepository implements GroupRepository { + public GroupImplJpaRepository(KapuaJpaRepositoryConfiguration jpaRepoConfig) { - super(GroupImpl.class, Group.TYPE, () -> new GroupListResultImpl(), jpaRepoConfig); + super(GroupImpl.class, Group.TYPE, () -> new GroupListResult(), jpaRepoConfig); } } diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/group/shiro/GroupListResultImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/group/shiro/GroupListResultImpl.java deleted file mode 100644 index a9b06f298ff..00000000000 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/group/shiro/GroupListResultImpl.java +++ /dev/null @@ -1,27 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authorization.group.shiro; - -import org.eclipse.kapua.commons.model.query.KapuaListResultImpl; -import org.eclipse.kapua.service.authorization.group.Group; -import org.eclipse.kapua.service.authorization.group.GroupListResult; - -/** - * {@link GroupListResult} implementation. - * - * @since 1.0.0 - */ -public class GroupListResultImpl extends KapuaListResultImpl implements GroupListResult { - - private static final long serialVersionUID = 791258978210911362L; -} diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/group/shiro/GroupMatchPredicateImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/group/shiro/GroupMatchPredicateImpl.java deleted file mode 100644 index d99618d07a1..00000000000 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/group/shiro/GroupMatchPredicateImpl.java +++ /dev/null @@ -1,37 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2017, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authorization.group.shiro; - -import org.eclipse.kapua.commons.model.query.predicate.AbstractMatchPredicate; -import org.eclipse.kapua.service.authorization.group.GroupAttributes; -import org.eclipse.kapua.service.authorization.group.GroupMatchPredicate; - -import java.util.Arrays; - -public class GroupMatchPredicateImpl extends AbstractMatchPredicate implements GroupMatchPredicate { - - /** - * Constructor. - * - * @param matchTerm - * @since 2.1.0 - */ - public GroupMatchPredicateImpl(T matchTerm) { - this.attributeNames = Arrays.asList( - GroupAttributes.DESCRIPTION, - GroupAttributes.NAME - ); - this.matchTerm = matchTerm; - } - -} diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/group/shiro/GroupQueryImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/group/shiro/GroupQueryImpl.java deleted file mode 100644 index 809a08a6564..00000000000 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/group/shiro/GroupQueryImpl.java +++ /dev/null @@ -1,41 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authorization.group.shiro; - -import org.eclipse.kapua.commons.model.query.AbstractKapuaNamedQuery; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.authorization.group.GroupMatchPredicate; -import org.eclipse.kapua.service.authorization.group.GroupQuery; - -/** - * {@link GroupQuery} implementation. - * - * @since 1.0.0 - */ -public class GroupQueryImpl extends AbstractKapuaNamedQuery implements GroupQuery { - - /** - * Constructor. - * - * @param scopeId The {@link #getScopeId()}. - * @since 1.0.0 - */ - public GroupQueryImpl(KapuaId scopeId) { - super(scopeId); - } - - @Override - public GroupMatchPredicate matchPredicate(T matchTerm) { - return new GroupMatchPredicateImpl<>(matchTerm); - } -} diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/group/shiro/GroupServiceImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/group/shiro/GroupServiceImpl.java index 4b64a1ae5c6..037b1c4b01b 100644 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/group/shiro/GroupServiceImpl.java +++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/group/shiro/GroupServiceImpl.java @@ -12,6 +12,9 @@ *******************************************************************************/ package org.eclipse.kapua.service.authorization.group.shiro; +import javax.inject.Inject; +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaDuplicateNameException; import org.eclipse.kapua.KapuaEntityNotFoundException; import org.eclipse.kapua.KapuaException; @@ -30,14 +33,11 @@ import org.eclipse.kapua.service.authorization.group.GroupQuery; import org.eclipse.kapua.service.authorization.group.GroupRepository; import org.eclipse.kapua.service.authorization.group.GroupService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; +import org.eclipse.kapua.service.authorization.permission.Permission; import org.eclipse.kapua.storage.TxManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.inject.Inject; -import javax.inject.Singleton; - /** * {@link GroupService} implementation. * @@ -47,7 +47,6 @@ public class GroupServiceImpl extends KapuaConfigurableServiceBase implements GroupService { private static final Logger LOG = LoggerFactory.getLogger(GroupServiceImpl.class); - private final PermissionFactory permissionFactory; private final AuthorizationService authorizationService; private final TxManager txManager; private final GroupRepository groupRepository; @@ -55,20 +54,19 @@ public class GroupServiceImpl extends KapuaConfigurableServiceBase implements Gr /** * Injectable constructor * - * @param permissionFactory The {@link PermissionFactory} instance. - * @param authorizationService The {@link AuthorizationService} instance. - * @param serviceConfigurationManager The {@link ServiceConfigurationManager} instance. + * @param authorizationService + * The {@link AuthorizationService} instance. + * @param serviceConfigurationManager + * The {@link ServiceConfigurationManager} instance. * @param txManager * @param groupRepository * @since 2.0.0 */ @Inject - public GroupServiceImpl(PermissionFactory permissionFactory, - AuthorizationService authorizationService, - ServiceConfigurationManager serviceConfigurationManager, - TxManager txManager, GroupRepository groupRepository) { - super(txManager, serviceConfigurationManager, Domains.GROUP, authorizationService, permissionFactory); - this.permissionFactory = permissionFactory; + public GroupServiceImpl(AuthorizationService authorizationService, + ServiceConfigurationManager serviceConfigurationManager, + TxManager txManager, GroupRepository groupRepository) { + super(txManager, serviceConfigurationManager, Domains.GROUP, authorizationService); this.authorizationService = authorizationService; this.txManager = txManager; this.groupRepository = groupRepository; @@ -81,7 +79,7 @@ public Group create(GroupCreator groupCreator) throws KapuaException { ArgumentValidator.notNull(groupCreator.getScopeId(), "roleCreator.scopeId"); ArgumentValidator.validateEntityName(groupCreator.getName(), "groupCreator.name"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.GROUP, Actions.write, groupCreator.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.GROUP, Actions.write, groupCreator.getScopeId())); return txManager.execute(tx -> { // Check entity limit serviceConfigurationManager.checkAllowedEntities(tx, groupCreator.getScopeId(), "Groups"); @@ -105,7 +103,7 @@ public Group update(Group group) throws KapuaException { ArgumentValidator.notNull(group.getScopeId(), "group.scopeId"); ArgumentValidator.validateEntityName(group.getName(), "group.name"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.GROUP, Actions.write, group.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.GROUP, Actions.write, group.getScopeId())); return txManager.execute(tx -> { // Check existence if (!groupRepository.find(tx, group.getScopeId(), group.getId()).isPresent()) { @@ -126,7 +124,7 @@ public void delete(KapuaId scopeId, KapuaId groupId) throws KapuaException { ArgumentValidator.notNull(scopeId, "scopeId"); ArgumentValidator.notNull(groupId, "groupId"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.GROUP, Actions.delete, scopeId)); + authorizationService.checkPermission(new Permission(Domains.GROUP, Actions.delete, scopeId)); txManager.execute(tx -> groupRepository.delete(tx, scopeId, groupId)); } @@ -137,7 +135,7 @@ public Group find(KapuaId scopeId, KapuaId groupId) throws KapuaException { ArgumentValidator.notNull(scopeId, "scopeId"); ArgumentValidator.notNull(groupId, "groupId"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.GROUP, Actions.read, scopeId)); + authorizationService.checkPermission(new Permission(Domains.GROUP, Actions.read, scopeId)); // Do find return txManager.execute(tx -> groupRepository.find(tx, scopeId, groupId)) .orElse(null); @@ -148,7 +146,7 @@ public GroupListResult query(KapuaQuery query) throws KapuaException { // Argument validation ArgumentValidator.notNull(query, "query"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.GROUP, Actions.read, query.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.GROUP, Actions.read, query.getScopeId())); // Do query return txManager.execute(tx -> groupRepository.query(tx, query)); } @@ -158,7 +156,7 @@ public long count(KapuaQuery query) throws KapuaException { // Argument validation ArgumentValidator.notNull(query, "query"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.GROUP, Actions.read, query.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.GROUP, Actions.read, query.getScopeId())); // Do count return txManager.execute(tx -> groupRepository.count(tx, query)); } @@ -176,7 +174,7 @@ public void onKapuaEvent(ServiceEvent kapuaEvent) throws KapuaException { } private void deleteGroupByAccountId(KapuaId scopeId, KapuaId accountId) throws KapuaException { - GroupQuery query = new GroupQueryImpl(accountId); + GroupQuery query = new GroupQuery(accountId); GroupListResult groupsToDelete = query(query); diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/permission/shiro/PermissionFactoryImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/permission/shiro/PermissionFactoryImpl.java deleted file mode 100644 index 8703bd62ce6..00000000000 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/permission/shiro/PermissionFactoryImpl.java +++ /dev/null @@ -1,31 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authorization.permission.shiro; - -import org.eclipse.kapua.model.domain.Actions; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.authorization.permission.Permission; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; - -import javax.inject.Singleton; - -/** - * {@link PermissionFactory} implementation. - */ -@Singleton -public class PermissionFactoryImpl implements PermissionFactory { - @Override - public Permission newPermission(String domain, Actions action, KapuaId targetScopeId, KapuaId groupId, boolean forwardable) { - return new PermissionImpl(domain, action, targetScopeId, groupId, forwardable); - } -} diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/permission/shiro/PermissionImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/permission/shiro/PermissionImpl.java index 2749ba47981..c8dde734c11 100644 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/permission/shiro/PermissionImpl.java +++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/permission/shiro/PermissionImpl.java @@ -12,10 +12,7 @@ *******************************************************************************/ package org.eclipse.kapua.service.authorization.permission.shiro; -import org.eclipse.kapua.commons.model.id.KapuaEid; -import org.eclipse.kapua.model.domain.Actions; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.authorization.permission.Permission; +import java.io.Serializable; import javax.persistence.AttributeOverride; import javax.persistence.AttributeOverrides; @@ -25,7 +22,11 @@ import javax.persistence.Embedded; import javax.persistence.EnumType; import javax.persistence.Enumerated; -import java.io.Serializable; + +import org.eclipse.kapua.commons.model.id.KapuaEid; +import org.eclipse.kapua.model.domain.Actions; +import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.service.authorization.permission.Permission; /** * {@link Permission} implementation. @@ -34,22 +35,21 @@ */ @Embeddable public class PermissionImpl -// extends -// WildcardPermission + // extends + // WildcardPermission implements - Permission -// , org.apache.shiro.authz.Permission - , Serializable { - + // , org.apache.shiro.authz.Permission + Serializable { private static final long serialVersionUID = 1480557438886065675L; -// -// //TODO: FIXME: REMOVE: A service in a jpa class? Behaviour should not be part of a data class! -// @Transient -// private final AccountService accountService = KapuaLocator.getInstance().getService(AccountService.class); -// //TODO: FIXME: REMOVE: A service in a jpa class? Behaviour should not be part of a data class! -// @Transient -// private final DomainRegistryService domainService = KapuaLocator.getInstance().getService(DomainRegistryService.class); + + // + // //TODO: FIXME: REMOVE: A service in a jpa class? Behaviour should not be part of a data class! + // @Transient + // private final AccountService accountService = KapuaLocator.getInstance().getService(AccountService.class); + // //TODO: FIXME: REMOVE: A service in a jpa class? Behaviour should not be part of a data class! + // @Transient + // private final DomainRegistryService domainService = KapuaLocator.getInstance().getService(DomainRegistryService.class); @Basic @Column(name = "domain", nullable = true, updatable = false) @@ -87,7 +87,8 @@ protected PermissionImpl() { /** * Constructor. * - * @param permission The {@link Permission} to parse. + * @param permission + * The {@link Permission} to parse. * @since 1.0.0 */ public PermissionImpl(Permission permission) { @@ -101,10 +102,14 @@ public PermissionImpl(Permission permission) { /** * Constructor. * - * @param domain The {@link Permission#getDomain()}. - * @param action The {@link Permission#getAction()}. - * @param targetScopeId The {@link Permission#getTargetScopeId()}. - * @param groupId The {@link Permission#getGroupId()}. + * @param domain + * The {@link Permission#getDomain()}. + * @param action + * The {@link Permission#getAction()}. + * @param targetScopeId + * The {@link Permission#getTargetScopeId()}. + * @param groupId + * The {@link Permission#getGroupId()}. * @since 1.0.0 */ public PermissionImpl(String domain, Actions action, KapuaId targetScopeId, KapuaId groupId) { @@ -114,11 +119,16 @@ public PermissionImpl(String domain, Actions action, KapuaId targetScopeId, Kapu /** * Constructor. * - * @param domain The {@link Permission#getDomain()}. - * @param action The {@link Permission#getAction()}. - * @param targetScopeId The {@link Permission#getTargetScopeId()}. - * @param groupId The {@link Permission#getGroupId()}. - * @param forwardable Whether the {@link Permission} is {@link Permission#getForwardable()} + * @param domain + * The {@link Permission#getDomain()}. + * @param action + * The {@link Permission#getAction()}. + * @param targetScopeId + * The {@link Permission#getTargetScopeId()}. + * @param groupId + * The {@link Permission#getGroupId()}. + * @param forwardable + * Whether the {@link Permission} is {@link Permission#getForwardable()} * @since 1.0.0 */ public PermissionImpl(String domain, Actions action, KapuaId targetScopeId, KapuaId groupId, boolean forwardable) { @@ -131,52 +141,42 @@ public PermissionImpl(String domain, Actions action, KapuaId targetScopeId, Kapu } - @Override public void setDomain(String domain) { this.domain = domain; } - @Override public String getDomain() { return domain; } - @Override public void setAction(Actions action) { this.action = action; } - @Override public Actions getAction() { return action; } - @Override public void setTargetScopeId(KapuaId targetScopeId) { this.targetScopeId = KapuaEid.parseKapuaId(targetScopeId); } - @Override public KapuaId getTargetScopeId() { return targetScopeId; } - @Override public void setGroupId(KapuaId groupId) { this.groupId = KapuaEid.parseKapuaId(groupId); } - @Override public KapuaId getGroupId() { return groupId; } - @Override public boolean getForwardable() { return forwardable; } - @Override public void setForwardable(boolean forwardable) { this.forwardable = forwardable; } diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/permission/shiro/PermissionValidator.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/permission/shiro/PermissionValidator.java index 8bf3d742c02..1999f264982 100644 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/permission/shiro/PermissionValidator.java +++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/permission/shiro/PermissionValidator.java @@ -12,9 +12,15 @@ *******************************************************************************/ package org.eclipse.kapua.service.authorization.permission.shiro; -import com.google.common.collect.Sets; +import java.util.Set; + +import javax.inject.Inject; +import javax.validation.constraints.NotNull; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.KapuaIllegalArgumentException; +import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.service.authorization.domain.Domain; import org.eclipse.kapua.service.authorization.domain.DomainFactory; import org.eclipse.kapua.service.authorization.domain.DomainListResult; @@ -22,9 +28,7 @@ import org.eclipse.kapua.service.authorization.permission.Permission; import org.eclipse.kapua.service.authorization.permission.PermissionAttributes; -import javax.inject.Inject; -import javax.validation.constraints.NotNull; -import java.util.Set; +import com.google.common.collect.Sets; public class PermissionValidator { @@ -43,7 +47,7 @@ public void validatePermission(@NotNull Permission permission) throws KapuaExcep public void validatePermissions(@NotNull Set permissions) throws KapuaException { if (!permissions.isEmpty()) { - DomainListResult domains = domainService.query(domainFactory.newQuery(null)); + DomainListResult domains = domainService.query(new KapuaQuery((KapuaId) null)); for (Permission p : permissions) { if (p.getDomain() != null) { diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/role/shiro/RoleCreatorImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/role/shiro/RoleCreatorImpl.java deleted file mode 100644 index 1a60cde28c9..00000000000 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/role/shiro/RoleCreatorImpl.java +++ /dev/null @@ -1,58 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authorization.role.shiro; - -import org.eclipse.kapua.commons.model.AbstractKapuaNamedEntityCreator; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.authorization.permission.Permission; -import org.eclipse.kapua.service.authorization.role.Role; -import org.eclipse.kapua.service.authorization.role.RoleCreator; - -import java.util.HashSet; -import java.util.Set; - -/** - * {@link RoleCreator} implementation. - * - * @since 1.0.0 - */ -public class RoleCreatorImpl extends AbstractKapuaNamedEntityCreator implements RoleCreator { - - private static final long serialVersionUID = 972154225756734130L; - - private Set permissions; - - /** - * Constructor - * - * @param scopeId The scope {@link KapuaId} - * @since 1.0.0 - */ - public RoleCreatorImpl(KapuaId scopeId) { - super(scopeId); - } - - @Override - public void setPermissions(Set permissions) { - this.permissions = permissions; - } - - @Override - public Set getPermissions() { - if (permissions == null) { - permissions = new HashSet<>(); - } - return permissions; - } - -} diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/role/shiro/RoleFactoryImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/role/shiro/RoleFactoryImpl.java index 29443481b8e..fc6e5168e7e 100644 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/role/shiro/RoleFactoryImpl.java +++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/role/shiro/RoleFactoryImpl.java @@ -12,16 +12,13 @@ *******************************************************************************/ package org.eclipse.kapua.service.authorization.role.shiro; +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaEntityCloneException; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.authorization.role.Role; -import org.eclipse.kapua.service.authorization.role.RoleCreator; import org.eclipse.kapua.service.authorization.role.RoleFactory; -import org.eclipse.kapua.service.authorization.role.RoleListResult; import org.eclipse.kapua.service.authorization.role.RolePermission; -import org.eclipse.kapua.service.authorization.role.RoleQuery; - -import javax.inject.Singleton; /** * {@link RoleFactory} implementation. @@ -36,21 +33,6 @@ public Role newEntity(KapuaId scopeId) { return new RoleImpl(scopeId); } - @Override - public RoleCreator newCreator(KapuaId scopeId) { - return new RoleCreatorImpl(scopeId); - } - - @Override - public RoleQuery newQuery(KapuaId scopeId) { - return new RoleQueryImpl(scopeId); - } - - @Override - public RoleListResult newListResult() { - return new RoleListResultImpl(); - } - @Override public RolePermission newRolePermission() { return new RolePermissionImpl(); diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/role/shiro/RoleImplJpaRepository.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/role/shiro/RoleImplJpaRepository.java index d02d4aae0dd..cf780b0dd28 100644 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/role/shiro/RoleImplJpaRepository.java +++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/role/shiro/RoleImplJpaRepository.java @@ -21,8 +21,9 @@ public class RoleImplJpaRepository extends KapuaNamedEntityJpaRepository implements RoleRepository { + public RoleImplJpaRepository(KapuaJpaRepositoryConfiguration jpaRepoConfig) { - super(RoleImpl.class, Role.TYPE, () -> new RoleListResultImpl(), jpaRepoConfig); + super(RoleImpl.class, Role.TYPE, () -> new RoleListResult(), jpaRepoConfig); } } diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/role/shiro/RoleListResultImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/role/shiro/RoleListResultImpl.java deleted file mode 100644 index b61c8834bd6..00000000000 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/role/shiro/RoleListResultImpl.java +++ /dev/null @@ -1,28 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authorization.role.shiro; - -import org.eclipse.kapua.commons.model.query.KapuaListResultImpl; -import org.eclipse.kapua.service.authorization.role.Role; -import org.eclipse.kapua.service.authorization.role.RoleListResult; - -/** - * Role list result implementation. - * - * @since 1.0 - * - */ -public class RoleListResultImpl extends KapuaListResultImpl implements RoleListResult { - - private static final long serialVersionUID = -5902522234186399802L; -} diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/role/shiro/RoleMatchPredicateImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/role/shiro/RoleMatchPredicateImpl.java deleted file mode 100644 index a9d67a14ce7..00000000000 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/role/shiro/RoleMatchPredicateImpl.java +++ /dev/null @@ -1,35 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2017, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authorization.role.shiro; - -import org.eclipse.kapua.commons.model.query.predicate.AbstractMatchPredicate; -import org.eclipse.kapua.service.authorization.role.RoleAttributes; -import org.eclipse.kapua.service.authorization.role.RoleMatchPredicate; -import java.util.Arrays; - -public class RoleMatchPredicateImpl extends AbstractMatchPredicate implements RoleMatchPredicate { - - /** - * Constructor. - * - * @param matchTerm - * @since 2.1.0 - */ - public RoleMatchPredicateImpl(T matchTerm) { - this.attributeNames = Arrays.asList( - RoleAttributes.DESCRIPTION, - RoleAttributes.NAME - ); - this.matchTerm = matchTerm; - } -} diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/role/shiro/RolePermissionCreatorImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/role/shiro/RolePermissionCreatorImpl.java deleted file mode 100644 index 698bd0c1385..00000000000 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/role/shiro/RolePermissionCreatorImpl.java +++ /dev/null @@ -1,58 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authorization.role.shiro; - -import org.eclipse.kapua.commons.model.AbstractKapuaEntityCreator; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.authorization.permission.Permission; -import org.eclipse.kapua.service.authorization.role.RolePermission; -import org.eclipse.kapua.service.authorization.role.RolePermissionCreator; - -/** - * Role creator service implementation. - * - * @since 1.0 - */ -public class RolePermissionCreatorImpl extends AbstractKapuaEntityCreator implements RolePermissionCreator { - - private static final long serialVersionUID = 972154225756734130L; - - private KapuaId roleId; - private Permission permission; - - /** - * Costructor - * - * @param scopeId - */ - public RolePermissionCreatorImpl(KapuaId scopeId) { - super(scopeId); - } - - public KapuaId getRoleId() { - return roleId; - } - - public void setRoleId(KapuaId roleId) { - this.roleId = roleId; - } - - @SuppressWarnings("unchecked") - public Permission getPermission() { - return permission; - } - - public void setPermission(Permission permission) { - this.permission = permission; - } -} diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/role/shiro/RolePermissionFactoryImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/role/shiro/RolePermissionFactoryImpl.java index d145edff977..f7604cef62e 100644 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/role/shiro/RolePermissionFactoryImpl.java +++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/role/shiro/RolePermissionFactoryImpl.java @@ -12,14 +12,11 @@ *******************************************************************************/ package org.eclipse.kapua.service.authorization.role.shiro; +import javax.inject.Singleton; + import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.authorization.role.RolePermission; -import org.eclipse.kapua.service.authorization.role.RolePermissionCreator; import org.eclipse.kapua.service.authorization.role.RolePermissionFactory; -import org.eclipse.kapua.service.authorization.role.RolePermissionListResult; -import org.eclipse.kapua.service.authorization.role.RolePermissionQuery; - -import javax.inject.Singleton; /** * {@link RolePermissionFactory} implementation. @@ -34,21 +31,6 @@ public RolePermission newEntity(KapuaId scopeId) { return new RolePermissionImpl(scopeId); } - @Override - public RolePermissionCreator newCreator(KapuaId scopeId) { - return new RolePermissionCreatorImpl(scopeId); - } - - @Override - public RolePermissionQuery newQuery(KapuaId scopeId) { - return new RolePermissionQueryImpl(scopeId); - } - - @Override - public RolePermissionListResult newListResult() { - return new RolePermissionListResultImpl(); - } - @Override public RolePermission clone(RolePermission rolePermission) { return new RolePermissionImpl(rolePermission); diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/role/shiro/RolePermissionImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/role/shiro/RolePermissionImpl.java index 46c545f1390..483cbbc989e 100644 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/role/shiro/RolePermissionImpl.java +++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/role/shiro/RolePermissionImpl.java @@ -12,13 +12,7 @@ *******************************************************************************/ package org.eclipse.kapua.service.authorization.role.shiro; -import org.eclipse.kapua.commons.model.AbstractKapuaEntity; -import org.eclipse.kapua.commons.model.id.KapuaEid; -import org.eclipse.kapua.commons.security.KapuaSecurityUtils; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.authorization.permission.Permission; -import org.eclipse.kapua.service.authorization.permission.shiro.PermissionImpl; -import org.eclipse.kapua.service.authorization.role.RolePermission; +import java.util.Date; import javax.persistence.AttributeOverride; import javax.persistence.AttributeOverrides; @@ -27,7 +21,14 @@ import javax.persistence.Entity; import javax.persistence.PreUpdate; import javax.persistence.Table; -import java.util.Date; + +import org.eclipse.kapua.commons.model.AbstractKapuaEntity; +import org.eclipse.kapua.commons.model.id.KapuaEid; +import org.eclipse.kapua.commons.security.KapuaSecurityUtils; +import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.service.authorization.permission.Permission; +import org.eclipse.kapua.service.authorization.permission.shiro.PermissionImpl; +import org.eclipse.kapua.service.authorization.role.RolePermission; /** * {@link RolePermission} implementation. @@ -61,7 +62,8 @@ protected RolePermissionImpl() { /** * Constructor. * - * @param scopeId The scope {@link KapuaId} to set into the {@link RolePermission} + * @param scopeId + * The scope {@link KapuaId} to set into the {@link RolePermission} * @since 1.0.0 */ public RolePermissionImpl(KapuaId scopeId) { @@ -71,8 +73,10 @@ public RolePermissionImpl(KapuaId scopeId) { /** * Constructor. * - * @param scopeId The scope {@link KapuaId} to set into the {@link RolePermission} - * @param permission The {@link Permission} to set into the {@link RolePermission} + * @param scopeId + * The scope {@link KapuaId} to set into the {@link RolePermission} + * @param permission + * The {@link Permission} to set into the {@link RolePermission} * @since 1.0.0 */ public RolePermissionImpl(KapuaId scopeId, Permission permission) { @@ -109,14 +113,16 @@ public KapuaId getRoleId() { public void setPermission(Permission permission) { PermissionImpl permissionImpl = null; if (permission != null) { - permissionImpl = permission instanceof PermissionImpl ? (PermissionImpl) permission : new PermissionImpl(permission); + permissionImpl = new PermissionImpl(permission); } this.permission = permissionImpl; } @Override public Permission getPermission() { - return permission != null ? permission : new PermissionImpl(null, null, null, null); + return permission != null + ? new Permission(permission.getDomain(), permission.getAction(), permission.getTargetScopeId(), permission.getGroupId(), permission.getForwardable()) + : new Permission(null, null, null); } @Override diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/role/shiro/RolePermissionImplJpaRepository.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/role/shiro/RolePermissionImplJpaRepository.java index 28e6c5da932..dd3f1229ee5 100644 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/role/shiro/RolePermissionImplJpaRepository.java +++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/role/shiro/RolePermissionImplJpaRepository.java @@ -12,6 +12,15 @@ *******************************************************************************/ package org.eclipse.kapua.service.authorization.role.shiro; +import java.util.List; +import java.util.stream.Collectors; + +import javax.persistence.EntityManager; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaDelete; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Root; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.commons.jpa.JpaAwareTxContext; import org.eclipse.kapua.commons.jpa.KapuaEntityJpaRepository; @@ -25,20 +34,12 @@ import org.eclipse.kapua.service.authorization.role.RolePermissionRepository; import org.eclipse.kapua.storage.TxContext; -import javax.persistence.EntityManager; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaDelete; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Root; -import java.util.List; -import java.util.stream.Collectors; - public class RolePermissionImplJpaRepository extends KapuaEntityJpaRepository implements RolePermissionRepository { public RolePermissionImplJpaRepository(KapuaJpaRepositoryConfiguration configuration) { - super(RolePermissionImpl.class, RolePermission.TYPE, () -> new RolePermissionListResultImpl(), configuration); + super(RolePermissionImpl.class, RolePermission.TYPE, () -> new RolePermissionListResult(), configuration); } @Override @@ -70,7 +71,7 @@ public RolePermissionListResult deleteAllByDomainAndAction(TxContext tx, String deleteQuery.where(deleteRoot.get(RolePermissionImpl_.id).in(resultList.stream().map(r -> r.getId()).map(KapuaEid::parseKapuaId).collect(Collectors.toList()))); em.createQuery(deleteQuery).executeUpdate(); } - final RolePermissionListResultImpl res = new RolePermissionListResultImpl(); + final RolePermissionListResult res = new RolePermissionListResult(); res.addItems(resultList); return res; } diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/role/shiro/RolePermissionListResultImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/role/shiro/RolePermissionListResultImpl.java deleted file mode 100644 index 210f4d786ac..00000000000 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/role/shiro/RolePermissionListResultImpl.java +++ /dev/null @@ -1,28 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authorization.role.shiro; - -import org.eclipse.kapua.commons.model.query.KapuaListResultImpl; -import org.eclipse.kapua.service.authorization.role.RolePermission; -import org.eclipse.kapua.service.authorization.role.RolePermissionListResult; - -/** - * {@link RolePermission} list result implementation. - * - * @since 1.0.0 - * - */ -public class RolePermissionListResultImpl extends KapuaListResultImpl implements RolePermissionListResult { - - private static final long serialVersionUID = -4732941050197499090L; -} diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/role/shiro/RolePermissionQueryImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/role/shiro/RolePermissionQueryImpl.java deleted file mode 100644 index babba275acf..00000000000 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/role/shiro/RolePermissionQueryImpl.java +++ /dev/null @@ -1,45 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authorization.role.shiro; - -import org.eclipse.kapua.commons.model.query.AbstractKapuaQuery; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.authorization.role.RolePermissionQuery; - -/** - * {@link RolePermissionQuery} implementation. - * - * @since 1.0.0 - */ -public class RolePermissionQueryImpl extends AbstractKapuaQuery implements RolePermissionQuery { - - /** - * Constructor. - * - * @since 1.0.0 - */ - public RolePermissionQueryImpl() { - super(); - } - - /** - * Constructor. - * - * @param scopeId The {@link #getScopeId()}. - * @since 1.0.0 - */ - public RolePermissionQueryImpl(KapuaId scopeId) { - this(); - setScopeId(scopeId); - } -} diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/role/shiro/RolePermissionServiceImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/role/shiro/RolePermissionServiceImpl.java index d1a5e863dcd..1e14a2007e0 100644 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/role/shiro/RolePermissionServiceImpl.java +++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/role/shiro/RolePermissionServiceImpl.java @@ -12,6 +12,13 @@ *******************************************************************************/ package org.eclipse.kapua.service.authorization.role.shiro; +import java.util.AbstractMap; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaEntityNotFoundException; import org.eclipse.kapua.KapuaEntityUniquenessException; import org.eclipse.kapua.KapuaErrorCodes; @@ -24,25 +31,17 @@ import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.service.authorization.AuthorizationService; import org.eclipse.kapua.service.authorization.permission.Permission; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; import org.eclipse.kapua.service.authorization.permission.shiro.PermissionValidator; import org.eclipse.kapua.service.authorization.role.Role; import org.eclipse.kapua.service.authorization.role.RolePermission; import org.eclipse.kapua.service.authorization.role.RolePermissionAttributes; import org.eclipse.kapua.service.authorization.role.RolePermissionCreator; import org.eclipse.kapua.service.authorization.role.RolePermissionListResult; -import org.eclipse.kapua.service.authorization.role.RolePermissionQuery; import org.eclipse.kapua.service.authorization.role.RolePermissionRepository; import org.eclipse.kapua.service.authorization.role.RolePermissionService; import org.eclipse.kapua.service.authorization.role.RoleRepository; import org.eclipse.kapua.storage.TxManager; -import javax.inject.Singleton; -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - /** * {@link RolePermission} service implementation. * @@ -52,19 +51,18 @@ public class RolePermissionServiceImpl implements RolePermissionService { private final AuthorizationService authorizationService; - private final PermissionFactory permissionFactory; private final TxManager txManager; private final RoleRepository roleRepository; private final RolePermissionRepository rolePermissionRepository; private final PermissionValidator permissionValidator; public RolePermissionServiceImpl( - AuthorizationService authorizationService, PermissionFactory permissionFactory, TxManager txManager, + AuthorizationService authorizationService, + TxManager txManager, RoleRepository roleRepository, RolePermissionRepository rolePermissionRepository, PermissionValidator permissionValidator) { this.authorizationService = authorizationService; - this.permissionFactory = permissionFactory; this.txManager = txManager; this.roleRepository = roleRepository; this.rolePermissionRepository = rolePermissionRepository; @@ -78,7 +76,7 @@ public RolePermission create(RolePermissionCreator rolePermissionCreator) ArgumentValidator.notNull(rolePermissionCreator.getRoleId(), "rolePermissionCreator.roleId"); ArgumentValidator.notNull(rolePermissionCreator.getPermission(), "rolePermissionCreator.permission"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.ROLE, Actions.write, rolePermissionCreator.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.ROLE, Actions.write, rolePermissionCreator.getScopeId())); return txManager.execute(tx -> { // Check role existence @@ -92,7 +90,7 @@ public RolePermission create(RolePermissionCreator rolePermissionCreator) authorizationService.checkPermission(permission); } // Check duplicates - RolePermissionQuery query = new RolePermissionQueryImpl(rolePermissionCreator.getScopeId()); + KapuaQuery query = new KapuaQuery(rolePermissionCreator.getScopeId()); query.setPredicate( query.andPredicate( query.attributePredicate(KapuaEntityAttributes.SCOPE_ID, rolePermissionCreator.getScopeId()), @@ -131,7 +129,7 @@ public void delete(KapuaId scopeId, KapuaId rolePermissionId) throws KapuaExcept ArgumentValidator.notNull(rolePermissionId, KapuaEntityAttributes.ENTITY_ID); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.ROLE, Actions.delete, scopeId)); + authorizationService.checkPermission(new Permission(Domains.ROLE, Actions.delete, scopeId)); if (KapuaId.ONE.equals(rolePermissionId)) { throw new KapuaException(KapuaErrorCodes.PERMISSION_DELETE_NOT_ALLOWED); @@ -145,7 +143,7 @@ public RolePermission find(KapuaId scopeId, KapuaId rolePermissionId) ArgumentValidator.notNull(scopeId, KapuaEntityAttributes.SCOPE_ID); ArgumentValidator.notNull(rolePermissionId, KapuaEntityAttributes.ENTITY_ID); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.ROLE, Actions.read, scopeId)); + authorizationService.checkPermission(new Permission(Domains.ROLE, Actions.read, scopeId)); return txManager.execute(tx -> rolePermissionRepository.find(tx, scopeId, rolePermissionId)) .orElse(null); @@ -157,7 +155,7 @@ public RolePermissionListResult findByRoleId(KapuaId scopeId, KapuaId roleId) ArgumentValidator.notNull(scopeId, KapuaEntityAttributes.SCOPE_ID); ArgumentValidator.notNull(roleId, KapuaEntityAttributes.ENTITY_ID); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.ROLE, Actions.read, scopeId)); + authorizationService.checkPermission(new Permission(Domains.ROLE, Actions.read, scopeId)); return txManager.execute(tx -> rolePermissionRepository.findByRoleId(tx, scopeId, roleId)); } @@ -167,7 +165,7 @@ public RolePermissionListResult query(KapuaQuery query) throws KapuaException { ArgumentValidator.notNull(query, "query"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.ROLE, Actions.read, query.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.ROLE, Actions.read, query.getScopeId())); return txManager.execute(tx -> rolePermissionRepository.query(tx, query)); } @@ -177,7 +175,7 @@ public long count(KapuaQuery query) throws KapuaException { ArgumentValidator.notNull(query, "query"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.ROLE, Actions.read, query.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.ROLE, Actions.read, query.getScopeId())); return txManager.execute(tx -> rolePermissionRepository.count(tx, query)); } diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/role/shiro/RoleQueryImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/role/shiro/RoleQueryImpl.java deleted file mode 100644 index 45a19a65914..00000000000 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/role/shiro/RoleQueryImpl.java +++ /dev/null @@ -1,52 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authorization.role.shiro; - -import org.eclipse.kapua.commons.model.query.AbstractKapuaNamedQuery; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.authorization.role.RoleMatchPredicate; -import org.eclipse.kapua.service.authorization.role.RoleQuery; - -/** - * {@link RoleQuery} implementation. - * - * @since 1.0.0 - */ -public class RoleQueryImpl extends AbstractKapuaNamedQuery implements RoleQuery { - - /** - * Constructor. - * - * @since 1.0.0 - */ - public RoleQueryImpl() { - super(); - } - - /** - * Constructor. - * - * @param scopeId The {@link #getScopeId()}. - * @since 1.0.0 - */ - public RoleQueryImpl(KapuaId scopeId) { - this(); - setScopeId(scopeId); - } - - @Override - public RoleMatchPredicate matchPredicate(T matchTerm) { - return new RoleMatchPredicateImpl<>(matchTerm); - } - -} diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/role/shiro/RoleServiceImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/role/shiro/RoleServiceImpl.java index 3fac5c50337..0d1ceacf48e 100644 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/role/shiro/RoleServiceImpl.java +++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/role/shiro/RoleServiceImpl.java @@ -12,6 +12,12 @@ *******************************************************************************/ package org.eclipse.kapua.service.authorization.role.shiro; +import java.util.List; +import java.util.stream.Collectors; + +import javax.inject.Inject; +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaDuplicateNameException; import org.eclipse.kapua.KapuaEntityNotFoundException; import org.eclipse.kapua.KapuaErrorCodes; @@ -29,16 +35,13 @@ import org.eclipse.kapua.service.authorization.access.AccessInfo; import org.eclipse.kapua.service.authorization.access.AccessInfoFactory; import org.eclipse.kapua.service.authorization.access.AccessInfoListResult; -import org.eclipse.kapua.service.authorization.access.AccessInfoQuery; import org.eclipse.kapua.service.authorization.access.AccessInfoService; import org.eclipse.kapua.service.authorization.access.AccessRole; import org.eclipse.kapua.service.authorization.access.AccessRoleAttributes; import org.eclipse.kapua.service.authorization.access.AccessRoleFactory; import org.eclipse.kapua.service.authorization.access.AccessRoleListResult; -import org.eclipse.kapua.service.authorization.access.AccessRoleQuery; import org.eclipse.kapua.service.authorization.access.AccessRoleService; import org.eclipse.kapua.service.authorization.permission.Permission; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; import org.eclipse.kapua.service.authorization.permission.shiro.PermissionValidator; import org.eclipse.kapua.service.authorization.role.Role; import org.eclipse.kapua.service.authorization.role.RoleCreator; @@ -54,11 +57,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.inject.Inject; -import javax.inject.Singleton; -import java.util.List; -import java.util.stream.Collectors; - /** * {@link RoleService} implementation. * @@ -80,21 +78,21 @@ public class RoleServiceImpl extends KapuaConfigurableServiceBase implements Rol public AccessInfoService accessInfoService; - /** * Injectable constructor * - * @param permissionFactory The {@link PermissionFactory} instance. - * @param authorizationService The {@link AuthorizationService} instance. - * @param rolePermissionFactory The {@link RolePermissionFactory} instance. - * @param serviceConfigurationManager The {@link ServiceConfigurationManager} instance. + * @param authorizationService + * The {@link AuthorizationService} instance. + * @param rolePermissionFactory + * The {@link RolePermissionFactory} instance. + * @param serviceConfigurationManager + * The {@link ServiceConfigurationManager} instance. * @param txManager * @param roleRepository * @param rolePermissionRepository */ @Inject public RoleServiceImpl( - PermissionFactory permissionFactory, AuthorizationService authorizationService, RolePermissionFactory rolePermissionFactory, AccessRoleFactory accessRoleFactory, @@ -106,7 +104,7 @@ public RoleServiceImpl( RoleRepository roleRepository, RolePermissionRepository rolePermissionRepository, PermissionValidator permissionValidator) { - super(txManager, serviceConfigurationManager, Domains.ROLE, authorizationService, permissionFactory); + super(txManager, serviceConfigurationManager, Domains.ROLE, authorizationService); this.rolePermissionFactory = rolePermissionFactory; this.accessRoleFactory = accessRoleFactory; this.accessInfoFactory = accessInfoFactory; @@ -125,7 +123,7 @@ public Role create(RoleCreator roleCreator) throws KapuaException { ArgumentValidator.validateEntityName(roleCreator.getName(), "roleCreator.name"); ArgumentValidator.notNull(roleCreator.getPermissions(), "roleCreator.permissions"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.ROLE, Actions.write, roleCreator.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.ROLE, Actions.write, roleCreator.getScopeId())); return txManager.execute(tx -> { // Check entity limit @@ -159,7 +157,7 @@ public Role create(RoleCreator roleCreator) throws KapuaException { if (!roleCreator.getPermissions().isEmpty()) { for (Permission p : roleCreator.getPermissions()) { - RolePermissionCreator rolePermissionCreator = rolePermissionFactory.newCreator(roleCreator.getScopeId()); + RolePermissionCreator rolePermissionCreator = new RolePermissionCreator(roleCreator.getScopeId()); rolePermissionCreator.setRoleId(createdRole.getId()); rolePermissionCreator.setPermission(p); @@ -183,7 +181,7 @@ public Role update(Role role) throws KapuaException { ArgumentValidator.notNull(role.getScopeId(), "role.scopeId"); ArgumentValidator.validateEntityName(role.getName(), "role.name"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.ROLE, Actions.write, role.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.ROLE, Actions.write, role.getScopeId())); return txManager.execute(tx -> { // Check existence @@ -204,7 +202,7 @@ public void delete(KapuaId scopeId, KapuaId roleId) throws KapuaException { ArgumentValidator.notNull(scopeId, "scopeId"); ArgumentValidator.notNull(roleId, "roleId"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.ROLE, Actions.delete, scopeId)); + authorizationService.checkPermission(new Permission(Domains.ROLE, Actions.delete, scopeId)); if (roleId.equals(KapuaId.ONE)) { throw new KapuaException(KapuaErrorCodes.ADMIN_ROLE_DELETED_ERROR); @@ -219,7 +217,7 @@ public Role find(KapuaId scopeId, KapuaId roleId) throws KapuaException { ArgumentValidator.notNull(scopeId, "scopeId"); ArgumentValidator.notNull(roleId, "roleId"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.ROLE, Actions.read, scopeId)); + authorizationService.checkPermission(new Permission(Domains.ROLE, Actions.read, scopeId)); // Do find return txManager.execute(tx -> roleRepository.find(tx, scopeId, roleId)) .orElse(null); @@ -230,7 +228,7 @@ public RoleListResult query(KapuaQuery query) throws KapuaException { // Argument validation ArgumentValidator.notNull(query, "query"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.ROLE, Actions.read, query.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.ROLE, Actions.read, query.getScopeId())); // Do query return txManager.execute(tx -> roleRepository.query(tx, query)); } @@ -240,7 +238,7 @@ public long count(KapuaQuery query) throws KapuaException { // Argument validation ArgumentValidator.notNull(query, "query"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.ROLE, Actions.read, query.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.ROLE, Actions.read, query.getScopeId())); // Do count return txManager.execute(tx -> roleRepository.count(tx, query)); } @@ -259,7 +257,7 @@ public void onKapuaEvent(ServiceEvent kapuaEvent) throws KapuaException { private void deleteRoleByAccountId(KapuaId scopeId, KapuaId accountId) throws KapuaException { - RoleQuery query = new RoleQueryImpl(accountId); + RoleQuery query = new RoleQuery(accountId); RoleListResult rolesToDelete = query(query); @@ -269,12 +267,13 @@ private void deleteRoleByAccountId(KapuaId scopeId, KapuaId accountId) throws Ka } public List userIdsByRoleId(KapuaId scopeId, KapuaId roleId) throws KapuaException { - AccessRoleQuery accessRoleQuery = accessRoleFactory.newQuery(scopeId); + KapuaQuery accessRoleQuery = new KapuaQuery(scopeId); accessRoleQuery.setPredicate(accessRoleQuery.attributePredicate(AccessRoleAttributes.ROLE_ID, roleId)); AccessRoleListResult accessRoleListResult = accessRoleService.query(accessRoleQuery); - AccessInfoQuery accessInfoQuery = accessInfoFactory.newQuery(scopeId); - accessInfoQuery.setPredicate(accessInfoQuery.attributePredicate(KapuaEntityAttributes.ENTITY_ID, accessRoleListResult.getItems().stream().map(AccessRole::getAccessInfoId).collect(Collectors.toList()))); + KapuaQuery accessInfoQuery = new KapuaQuery(scopeId); + accessInfoQuery.setPredicate( + accessInfoQuery.attributePredicate(KapuaEntityAttributes.ENTITY_ID, accessRoleListResult.getItems().stream().map(AccessRole::getAccessInfoId).collect(Collectors.toList()))); AccessInfoListResult accessInfoListResult = accessInfoService.query(accessInfoQuery); return accessInfoListResult.getItems().stream().map(AccessInfo::getUserId).collect(Collectors.toList()); diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/shiro/AuthorizationModule.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/shiro/AuthorizationModule.java index 97baf44fba9..ac5c0c56232 100644 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/shiro/AuthorizationModule.java +++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/shiro/AuthorizationModule.java @@ -27,7 +27,6 @@ import org.eclipse.kapua.commons.jpa.NamedCacheFactory; import org.eclipse.kapua.commons.metric.CommonsMetric; import org.eclipse.kapua.commons.model.domains.Domains; -import org.eclipse.kapua.commons.service.event.store.api.EventStoreFactory; import org.eclipse.kapua.commons.service.event.store.api.EventStoreRecordRepository; import org.eclipse.kapua.commons.service.event.store.internal.EventStoreServiceImpl; import org.eclipse.kapua.commons.service.internal.cache.KapuaCacheManager; @@ -74,8 +73,6 @@ import org.eclipse.kapua.service.authorization.group.shiro.GroupFactoryImpl; import org.eclipse.kapua.service.authorization.group.shiro.GroupImplJpaRepository; import org.eclipse.kapua.service.authorization.group.shiro.GroupServiceImpl; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; -import org.eclipse.kapua.service.authorization.permission.shiro.PermissionFactoryImpl; import org.eclipse.kapua.service.authorization.permission.shiro.PermissionValidator; import org.eclipse.kapua.service.authorization.role.RoleFactory; import org.eclipse.kapua.service.authorization.role.RolePermissionFactory; @@ -106,8 +103,6 @@ protected void configureModule() { bind(DomainFactory.class).to(DomainFactoryImpl.class).in(Singleton.class); - bind(PermissionFactory.class).to(PermissionFactoryImpl.class).in(Singleton.class); - bind(AccessInfoFactory.class).to(AccessInfoFactoryImpl.class).in(Singleton.class); bind(AccessPermissionFactory.class).to(AccessPermissionFactoryImpl.class).in(Singleton.class); bind(AccessRoleFactory.class).to(AccessRoleFactoryImpl.class).in(Singleton.class); @@ -147,9 +142,7 @@ ServiceModule authorizationServiceModule(AccessInfoService accessInfoService, DomainRegistryService domainRegistryService, GroupService groupService, AuthorizationService authorizationService, - PermissionFactory permissionFactory, KapuaJpaTxManagerFactory txManagerFactory, - EventStoreFactory eventStoreFactory, EventStoreRecordRepository eventStoreRecordRepository, ServiceEventBus serviceEventBus, KapuaAuthorizationSetting kapuaAuthorizationSetting, @@ -164,9 +157,7 @@ ServiceModule authorizationServiceModule(AccessInfoService accessInfoService, new ServiceEventHouseKeeperFactoryImpl( new EventStoreServiceImpl( authorizationService, - permissionFactory, txManagerFactory.create("kapua-authorization"), - eventStoreFactory, eventStoreRecordRepository ), txManagerFactory.create("kapua-authorization"), @@ -188,16 +179,13 @@ TxManager authorizationTxManager( @Singleton DomainRegistryService domainRegistryService( AuthorizationService authorizationService, - PermissionFactory permissionFactory, - DomainRepository domainRepository, DomainFactory domainFactory, + DomainRepository domainRepository, KapuaJpaTxManagerFactory jpaTxManagerFactory) { return new DomainRegistryServiceImpl( authorizationService, - permissionFactory, jpaTxManagerFactory.create("kapua-authorization"), - domainRepository, - domainFactory); + domainRepository); } @Provides @@ -208,7 +196,7 @@ DomainRepository domainRepository(KapuaJpaRepositoryConfiguration jpaRepoConfig) @Provides @Singleton - RolePermissionService rolePermissionService(PermissionFactory permissionFactory, + RolePermissionService rolePermissionService( AuthorizationService authorizationService, RoleRepository roleRepository, RolePermissionRepository rolePermissionRepository, @@ -216,7 +204,6 @@ RolePermissionService rolePermissionService(PermissionFactory permissionFactory, PermissionValidator permissionValidator) { return new RolePermissionServiceImpl( authorizationService, - permissionFactory, jpaTxManagerFactory.create("kapua-authorization"), roleRepository, rolePermissionRepository, @@ -226,7 +213,7 @@ RolePermissionService rolePermissionService(PermissionFactory permissionFactory, @Provides @Singleton - RoleService roleService(PermissionFactory permissionFactory, + RoleService roleService( AuthorizationService authorizationService, RolePermissionFactory rolePermissionFactory, AccessRoleFactory accessRoleFactory, @@ -240,7 +227,6 @@ RoleService roleService(PermissionFactory permissionFactory, PermissionValidator permissionValidator ) { return new RoleServiceImpl( - permissionFactory, authorizationService, rolePermissionFactory, accessRoleFactory, @@ -272,12 +258,12 @@ RolePermissionRepository rolePermissionRepository(KapuaJpaRepositoryConfiguratio @Provides @Singleton - GroupService groupService(PermissionFactory permissionFactory, + GroupService groupService( AuthorizationService authorizationService, Map, ServiceConfigurationManager> serviceConfigurationManagersByServiceClass, GroupRepository groupRepository, KapuaJpaTxManagerFactory jpaTxManagerFactory) { - return new GroupServiceImpl(permissionFactory, authorizationService, serviceConfigurationManagersByServiceClass.get(GroupService.class), + return new GroupServiceImpl(authorizationService, serviceConfigurationManagersByServiceClass.get(GroupService.class), jpaTxManagerFactory.create("kapua-authorization"), groupRepository); } @@ -292,26 +278,20 @@ GroupRepository groupRepository(KapuaJpaRepositoryConfiguration jpaRepoConfig) { @Singleton AccessInfoService accessInfoService( AuthorizationService authorizationService, - PermissionFactory permissionFactory, RoleRepository roleRepository, AccessRoleFactory accessRoleFactory, AccessRoleRepository accessRoleRepository, AccessInfoRepository accessInfoRepository, - AccessInfoFactory accessInfoFactory, AccessPermissionRepository accessPermissionRepository, - AccessPermissionFactory accessPermissionFactory, KapuaJpaTxManagerFactory jpaTxManagerFactory, PermissionValidator permissionValidator) { return new AccessInfoServiceImpl(authorizationService, - permissionFactory, jpaTxManagerFactory.create("kapua-authorization"), roleRepository, accessRoleFactory, accessRoleRepository, accessInfoRepository, - accessInfoFactory, accessPermissionRepository, - accessPermissionFactory, permissionValidator); } @@ -328,13 +308,11 @@ AccessInfoRepository accessInfoRepository(KapuaCacheManager kapuaCacheManager, C @Singleton AccessPermissionService accessPermissionService( AuthorizationService authorizationService, - PermissionFactory permissionFactory, AccessPermissionRepository accessPermissionRepository, AccessInfoRepository accessInfoRepository, KapuaJpaTxManagerFactory jpaTxManagerFactory, PermissionValidator permissionValidator) { return new AccessPermissionServiceImpl(authorizationService, - permissionFactory, jpaTxManagerFactory.create("kapua-authorization"), accessPermissionRepository, accessInfoRepository, @@ -357,15 +335,13 @@ AccessRoleService accessRoleService(RoleRepository roleRepository, AccessInfoRepository accessInfoRepository, AccessRoleRepository accessRoleRepository, AuthorizationService authorizationService, - PermissionFactory permissionFactory, KapuaJpaTxManagerFactory jpaTxManagerFactory) { return new AccessRoleServiceImpl( jpaTxManagerFactory.create("kapua-authorization"), roleRepository, accessInfoRepository, accessRoleRepository, - authorizationService, - permissionFactory + authorizationService ); } diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/shiro/GroupServiceConfigurationManagerModule.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/shiro/GroupServiceConfigurationManagerModule.java index 1c928b8fdf0..76185f95341 100644 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/shiro/GroupServiceConfigurationManagerModule.java +++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/shiro/GroupServiceConfigurationManagerModule.java @@ -29,7 +29,6 @@ import org.eclipse.kapua.commons.jpa.KapuaJpaTxManagerFactory; import org.eclipse.kapua.commons.model.domains.Domains; import org.eclipse.kapua.commons.util.xml.XmlUtil; -import org.eclipse.kapua.service.authorization.group.GroupFactory; import org.eclipse.kapua.service.authorization.group.GroupRepository; import org.eclipse.kapua.service.authorization.group.GroupService; @@ -54,7 +53,6 @@ protected void configureModule() { @Singleton public ServiceConfigurationManager groupServiceConfigurationManager( KapuaJpaTxManagerFactory jpaTxManagerFactory, - GroupFactory factory, RootUserTester rootUserTester, AccountRelativeFinder accountRelativeFinder, GroupRepository groupRepository, @@ -74,7 +72,6 @@ public ServiceConfigurationManager groupServiceConfigurationManager( rootUserTester, accountRelativeFinder, new UsedEntitiesCounterImpl( - factory, groupRepository ), new ResourceBasedServiceConfigurationMetadataProvider(xmlUtil))); } diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/shiro/KapuaAuthorizingRealm.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/shiro/KapuaAuthorizingRealm.java index fb0ceb47430..af90b941802 100644 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/shiro/KapuaAuthorizingRealm.java +++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/shiro/KapuaAuthorizingRealm.java @@ -27,10 +27,10 @@ import org.eclipse.kapua.locator.KapuaLocator; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.model.query.KapuaListResult; +import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.service.authorization.access.AccessInfo; import org.eclipse.kapua.service.authorization.access.AccessInfoAttributes; import org.eclipse.kapua.service.authorization.access.AccessInfoFactory; -import org.eclipse.kapua.service.authorization.access.AccessInfoQuery; import org.eclipse.kapua.service.authorization.access.AccessInfoService; import org.eclipse.kapua.service.authorization.access.AccessPermission; import org.eclipse.kapua.service.authorization.access.AccessPermissionListResult; @@ -38,7 +38,7 @@ import org.eclipse.kapua.service.authorization.access.AccessRole; import org.eclipse.kapua.service.authorization.access.AccessRoleListResult; import org.eclipse.kapua.service.authorization.access.AccessRoleService; -import org.eclipse.kapua.service.authorization.permission.shiro.PermissionImpl; +import org.eclipse.kapua.service.authorization.permission.Permission; import org.eclipse.kapua.service.authorization.role.Role; import org.eclipse.kapua.service.authorization.role.RolePermission; import org.eclipse.kapua.service.authorization.role.RolePermissionListResult; @@ -97,7 +97,7 @@ protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal throw new AuthenticationException(); } // Get user access infos - AccessInfoQuery accessInfoQuery = accessInfoFactory.newQuery(user.getScopeId()); + KapuaQuery accessInfoQuery = new KapuaQuery(user.getScopeId()); accessInfoQuery.setPredicate(accessInfoQuery.attributePredicate(AccessInfoAttributes.USER_ID, user.getId())); final KapuaListResult accessInfos; @@ -130,7 +130,7 @@ protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal } for (AccessPermission accessPermission : accessPermissions.getItems()) { - PermissionImpl p = accessPermission.getPermission(); + Permission p = accessPermission.getPermission(); logger.trace("User: {} has permission: {}", username, p); info.addObjectPermission(permissionMapper.mapPermission(p)); } @@ -171,7 +171,7 @@ protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal for (RolePermission rolePermission : rolePermissions.getItems()) { - PermissionImpl p = rolePermission.getPermission(); + Permission p = rolePermission.getPermission(); logger.trace("Role: {} has permission: {}", role, p); info.addObjectPermission(permissionMapper.mapPermission(p)); } diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/shiro/PermissionMapperImpl.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/shiro/PermissionMapperImpl.java index b8ef98954cd..21b871d748c 100644 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/shiro/PermissionMapperImpl.java +++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/shiro/PermissionMapperImpl.java @@ -12,6 +12,10 @@ *******************************************************************************/ package org.eclipse.kapua.service.authorization.shiro; +import java.util.Optional; + +import javax.inject.Inject; + import org.apache.shiro.authz.Permission; import org.apache.shiro.authz.UnauthorizedException; import org.apache.shiro.authz.permission.WildcardPermission; @@ -32,10 +36,8 @@ import org.eclipse.kapua.service.authorization.domain.DomainRegistryService; import org.eclipse.kapua.service.authorization.group.Group; -import javax.inject.Inject; -import java.util.Optional; - public class PermissionMapperImpl implements PermissionMapper { + private final DomainRegistryService domainService; private final AccountService accountService; @@ -50,7 +52,8 @@ public Permission mapPermission(org.eclipse.kapua.service.authorization.permissi return new KapuaPermission(permission.getDomain(), permission.getAction(), permission.getTargetScopeId(), permission.getGroupId(), permission.getForwardable()); } - public class KapuaPermission extends WildcardPermission implements org.eclipse.kapua.service.authorization.permission.Permission, Permission { + public class KapuaPermission extends WildcardPermission implements Permission { + private String domain; private Actions action; private KapuaId targetScopeId; @@ -131,22 +134,21 @@ public boolean equals(Object obj) { /** * This method needs to be overridden to support Access {@link Group} feature. *

        - * {@link KapuaEntityService}s that access a specific {@link KapuaEntity} (i.e. {@link KapuaEntityService#create(KapuaEntityCreator)}, {@link KapuaEntityService#delete(KapuaId, KapuaId)}) - * can make the control taking in consideration of the {@link Group#getId()} parameter as it is known.
        + * {@link KapuaEntityService}s that access a specific {@link KapuaEntity} (i.e. {@link KapuaEntityService#create(KapuaEntityCreator)}, {@link KapuaEntityService#delete(KapuaId, KapuaId)}) can + * make the control taking in consideration of the {@link Group#getId()} parameter as it is known.
        *

        - * Instead, methods that access multiple {@link KapuaEntity}s (i.e. {@link KapuaEntityService#query(KapuaQuery)}, {@link KapuaEntityService#count(KapuaQuery)}) - * cannot make a direct control of the {@link Group#getId()} parameter as it is not known and they can be a lot.
        - * The access control then, is performed by hiding the data that a {@link Subject} cannot see instead of throwing {@link UnauthorizedException}. + * Instead, methods that access multiple {@link KapuaEntity}s (i.e. {@link KapuaEntityService#query(KapuaQuery)}, {@link KapuaEntityService#count(KapuaQuery)}) cannot make a direct control of + * the {@link Group#getId()} parameter as it is not known and they can be a lot.
        The access control then, is performed by hiding the data that a {@link Subject} cannot see instead of + * throwing {@link UnauthorizedException}. *

        *

        * The access control for {@link KapuaEntityService#query(KapuaQuery)}, {@link KapuaEntityService#count(KapuaQuery)}) must specify that {@link Group#ANY} group assigned to the permission is * enough to pass the {@link AuthorizationService#checkPermission(org.eclipse.kapua.service.authorization.permission.Permission)}. *

        *

        - * In case of the {@link org.eclipse.kapua.service.authorization.permission.Permission#getForwardable()} equals to {@code true}, more lookup is required.
        - * If a parent account access the resources of one of its child accounts it won't have the direct permission to access it. - * A lookup of {@link Account#getParentAccountPath()} will be required to search if the current user scope id is - * one of the parent of the given {@link org.eclipse.kapua.service.authorization.permission.Permission#getTargetScopeId()} + * In case of the {@link org.eclipse.kapua.service.authorization.permission.Permission#getForwardable()} equals to {@code true}, more lookup is required.
        If a parent account access the + * resources of one of its child accounts it won't have the direct permission to access it. A lookup of {@link Account#getParentAccountPath()} will be required to search if the current user + * scope id is one of the parent of the given {@link org.eclipse.kapua.service.authorization.permission.Permission#getTargetScopeId()} *

        * * @since 1.0.0 @@ -154,7 +156,7 @@ public boolean equals(Object obj) { @Override public boolean implies(Permission shiroPermission) { - org.eclipse.kapua.service.authorization.permission.Permission targetPermission = (org.eclipse.kapua.service.authorization.permission.Permission) shiroPermission; + KapuaPermission targetPermission = (KapuaPermission) shiroPermission; // Check target Permission domain checkTargetPermissionIsGroupable(targetPermission); @@ -188,10 +190,11 @@ public boolean implies(Permission shiroPermission) { *

        * If it is, promotes this {@link org.eclipse.kapua.service.authorization.permission.Permission#getGroupId()} to {@code null} (a.k.a. ALL groups). * - * @param targetPermission The target {@link Permission} to check. + * @param targetPermission + * The target {@link Permission} to check. * @since 2.0.0 */ - private void checkTargetPermissionIsGroupable(org.eclipse.kapua.service.authorization.permission.Permission targetPermission) { + private void checkTargetPermissionIsGroupable(KapuaPermission targetPermission) { if (targetPermission.getDomain() != null) { try { org.eclipse.kapua.service.authorization.domain.Domain domainDefinition = KapuaSecurityUtils.doPrivileged(() -> domainService.findByName(targetPermission.getDomain())); @@ -208,21 +211,19 @@ private void checkTargetPermissionIsGroupable(org.eclipse.kapua.service.authoriz /** * Checks {@code this} Permission against the given {@link Permission} parameter. *

        - * It tries to forward {@code this} Permission to the {@link #getTargetScopeId()} of the given {@link Permission} parameter.
        - * This means that if the required permission has scope id 'B' and {@code this} {@link Permission} has scope id 'A', - * this methods search the {@link Account#getParentAccountPath()} of the scope id 'B' and checks the {@link Permission} forwarding {@code this} Permission - * to the same level of the given {@link Permission}. + * It tries to forward {@code this} Permission to the {@link #getTargetScopeId()} of the given {@link Permission} parameter.
        This means that if the required permission has scope id 'B' and + * {@code this} {@link Permission} has scope id 'A', this methods search the {@link Account#getParentAccountPath()} of the scope id 'B' and checks the {@link Permission} forwarding + * {@code this} Permission to the same level of the given {@link Permission}. *

        *

        *

        Example:

        - * User 'A' in account 'A' has scopeId 'A' and this permission (A) "*:*:A:*". - * Account 'A' has a child account 'B', then 'B' has this parent account path: '/A/B'; - * User 'A' tries to access a resource of account 'B' an the direct check {@link Permission#implies(Permission)} fails. - * So this method searches the parent account path of account 'B', found that 'A' is a parent of 'B' + * User 'A' in account 'A' has scopeId 'A' and this permission (A) "*:*:A:*". Account 'A' has a child account 'B', then 'B' has this parent account path: '/A/B'; User 'A' tries to access a + * resource of account 'B' an the direct check {@link Permission#implies(Permission)} fails. So this method searches the parent account path of account 'B', found that 'A' is a parent of 'B' * so then {@code this} {@link Permission} is checked again with 'B' as scopeId. *

        * - * @param shiroPermission The permission to check against. + * @param shiroPermission + * The permission to check against. * @return {@code true} if this permission is forward-able and is valid when forwarded, {@code false otherwise} * @since 1.0.0 */ @@ -250,8 +251,6 @@ private boolean forwardPermission(Permission shiroPermission) { return false; } - - @Override public void setDomain(String domain) { this.domain = domain; } diff --git a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/shiro/RoleServiceConfigurationManagerModule.java b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/shiro/RoleServiceConfigurationManagerModule.java index 271085d9978..df444819527 100644 --- a/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/shiro/RoleServiceConfigurationManagerModule.java +++ b/service/security/shiro/src/main/java/org/eclipse/kapua/service/authorization/shiro/RoleServiceConfigurationManagerModule.java @@ -29,7 +29,6 @@ import org.eclipse.kapua.commons.jpa.KapuaJpaTxManagerFactory; import org.eclipse.kapua.commons.model.domains.Domains; import org.eclipse.kapua.commons.util.xml.XmlUtil; -import org.eclipse.kapua.service.authorization.role.RoleFactory; import org.eclipse.kapua.service.authorization.role.RoleRepository; import org.eclipse.kapua.service.authorization.role.RoleService; @@ -54,7 +53,6 @@ protected void configureModule() { @Singleton public ServiceConfigurationManager roleServiceConfigurationManager( KapuaJpaTxManagerFactory jpaTxManagerFactory, - RoleFactory roleFactory, RootUserTester rootUserTester, AccountRelativeFinder accountRelativeFinder, RoleRepository roleRepository, @@ -74,7 +72,6 @@ public ServiceConfigurationManager roleServiceConfigurationManager( rootUserTester, accountRelativeFinder, new UsedEntitiesCounterImpl( - roleFactory, roleRepository ), new ResourceBasedServiceConfigurationMetadataProvider(xmlUtil))); diff --git a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/credential/mfa/shiro/MfaOptionCreatorImplTest.java b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/credential/mfa/shiro/MfaOptionCreatorTest.java similarity index 76% rename from service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/credential/mfa/shiro/MfaOptionCreatorImplTest.java rename to service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/credential/mfa/shiro/MfaOptionCreatorTest.java index 2f69e86301d..998f04018d8 100644 --- a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/credential/mfa/shiro/MfaOptionCreatorImplTest.java +++ b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/credential/mfa/shiro/MfaOptionCreatorTest.java @@ -14,35 +14,35 @@ import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.qa.markers.junit.JUnitTests; +import org.eclipse.kapua.service.authentication.credential.mfa.MfaOptionCreator; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; - @Category(JUnitTests.class) -public class MfaOptionCreatorImplTest { +public class MfaOptionCreatorTest { KapuaId[] scopeIds; KapuaId[] userIds; KapuaId[] newUserIds; - MfaOptionCreatorImpl mfaOptionCreatorImpl1; - MfaOptionCreatorImpl mfaOptionCreatorImpl2; + MfaOptionCreator mfaOptionCreatorImpl1; + MfaOptionCreator mfaOptionCreatorImpl2; @Before public void initialize() { - scopeIds = new KapuaId[]{null, KapuaId.ONE}; - userIds = new KapuaId[]{null, KapuaId.ONE}; - newUserIds = new KapuaId[]{null, KapuaId.ANY}; - mfaOptionCreatorImpl1 = new MfaOptionCreatorImpl(KapuaId.ONE, KapuaId.ONE); - mfaOptionCreatorImpl2 = new MfaOptionCreatorImpl(KapuaId.ONE); + scopeIds = new KapuaId[] { null, KapuaId.ONE }; + userIds = new KapuaId[] { null, KapuaId.ONE }; + newUserIds = new KapuaId[] { null, KapuaId.ANY }; + mfaOptionCreatorImpl1 = new MfaOptionCreator(KapuaId.ONE, KapuaId.ONE); + mfaOptionCreatorImpl2 = new MfaOptionCreator(KapuaId.ONE); } @Test public void mfaOptionCreatorImplScopeIdUserIdSecretKeyParametersTest() { for (KapuaId scopeId : scopeIds) { for (KapuaId userId : userIds) { - MfaOptionCreatorImpl mfaOptionCreatorImpl = new MfaOptionCreatorImpl(scopeId, userId); + MfaOptionCreator mfaOptionCreatorImpl = new MfaOptionCreator(scopeId, userId); Assert.assertEquals("Expected and actual values should be the same.", scopeId, mfaOptionCreatorImpl.getScopeId()); Assert.assertEquals("Expected and actual values should be the same.", userId, mfaOptionCreatorImpl.getUserId()); } @@ -52,7 +52,7 @@ public void mfaOptionCreatorImplScopeIdUserIdSecretKeyParametersTest() { @Test public void mfaOptionCreatorImplScopeIdParameterTest() { for (KapuaId scopeId : scopeIds) { - MfaOptionCreatorImpl mfaOptionCreatorImpl = new MfaOptionCreatorImpl(scopeId); + MfaOptionCreator mfaOptionCreatorImpl = new MfaOptionCreator(scopeId); Assert.assertEquals("Expected and actual values should be the same.", scopeId, mfaOptionCreatorImpl.getScopeId()); Assert.assertNull("Null expected.", mfaOptionCreatorImpl.getUserId()); } diff --git a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/credential/mfa/shiro/MfaOptionFactoryImplTest.java b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/credential/mfa/shiro/MfaOptionFactoryImplTest.java index 46af59ccee6..4de136da130 100644 --- a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/credential/mfa/shiro/MfaOptionFactoryImplTest.java +++ b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/credential/mfa/shiro/MfaOptionFactoryImplTest.java @@ -12,23 +12,20 @@ *******************************************************************************/ package org.eclipse.kapua.service.authentication.credential.mfa.shiro; +import java.util.Date; + import org.eclipse.kapua.KapuaEntityCloneException; import org.eclipse.kapua.commons.model.id.KapuaEid; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.qa.markers.junit.JUnitTests; import org.eclipse.kapua.service.authentication.credential.mfa.MfaOption; import org.eclipse.kapua.service.authentication.credential.mfa.MfaOptionCreator; -import org.eclipse.kapua.service.authentication.credential.mfa.MfaOptionListResult; -import org.eclipse.kapua.service.authentication.credential.mfa.MfaOptionQuery; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.mockito.Mockito; -import java.util.Date; - - @Category(JUnitTests.class) public class MfaOptionFactoryImplTest { @@ -42,29 +39,13 @@ public class MfaOptionFactoryImplTest { @Before public void initialize() { mfaOptionFactoryImpl = new MfaOptionFactoryImpl(); - scopeIds = new KapuaId[]{null, KapuaId.ONE}; - userIds = new KapuaEid[]{null, new KapuaEid()}; + scopeIds = new KapuaId[] { null, KapuaId.ONE }; + userIds = new KapuaEid[] { null, new KapuaEid() }; mfaOption = Mockito.mock(MfaOption.class); trustExpirationDate = new Date(); modifiedOn = new Date(); } - @Test - public void newCreatorScopeIdUserIdMfaSecretKeyParametersTest() { - for (KapuaId scopeId : scopeIds) { - for (KapuaEid userId : userIds) { - MfaOptionCreator mfaOptionCreatorImpl = mfaOptionFactoryImpl.newCreator(scopeId, userId); - Assert.assertEquals("Expected and actual values should be the same.", scopeId, mfaOptionCreatorImpl.getScopeId()); - Assert.assertEquals("Expected and actual values should be the same.", userId, mfaOptionCreatorImpl.getUserId()); - } - } - } - - @Test - public void newListResultTest() { - Assert.assertTrue("Instance of MfaOptionListResult expected.", mfaOptionFactoryImpl.newListResult() instanceof MfaOptionListResult); - } - @Test public void newEntityTest() { for (KapuaId scopeId : scopeIds) { @@ -73,18 +54,10 @@ public void newEntityTest() { } } - @Test - public void newQueryTest() { - for (KapuaId scopeId : scopeIds) { - MfaOptionQuery mfaOptionQuery = mfaOptionFactoryImpl.newQuery(scopeId); - Assert.assertEquals("Expected and actual values should be the same.", scopeId, mfaOptionQuery.getScopeId()); - } - } - @Test public void newCreatorScopeIdParameterTest() { for (KapuaId scopeId : scopeIds) { - MfaOptionCreator mfaOptionCreator = mfaOptionFactoryImpl.newCreator(scopeId); + MfaOptionCreator mfaOptionCreator = new MfaOptionCreator(scopeId); Assert.assertEquals("Expected and actual values should be the same.", scopeId, mfaOptionCreator.getScopeId()); } } diff --git a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/credential/mfa/shiro/MfaOptionQueryImplTest.java b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/credential/mfa/shiro/MfaOptionQueryImplTest.java deleted file mode 100644 index 51f23ca3f59..00000000000 --- a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/credential/mfa/shiro/MfaOptionQueryImplTest.java +++ /dev/null @@ -1,44 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authentication.credential.mfa.shiro; - -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.qa.markers.junit.JUnitTests; -import org.junit.Assert; -import org.junit.Test; -import org.junit.experimental.categories.Category; - - -@Category(JUnitTests.class) -public class MfaOptionQueryImplTest { - - @Test - public void mfaOptionQueryImplTest() { - MfaOptionQueryImpl mfaOptionQueryImpl = new MfaOptionQueryImpl(); - Assert.assertNull("Null expected.", mfaOptionQueryImpl.getScopeId()); - Assert.assertNull("mfaOptionQueryImpl.sortCriteria", mfaOptionQueryImpl.getSortCriteria()); - Assert.assertNotNull("mfaOptionQueryImpl.defaultSortCriteria", mfaOptionQueryImpl.getDefaultSortCriteria()); - } - - @Test - public void mfaOptionQueryImplScopeIdParameterTest() { - KapuaId[] scopeIds = {null, KapuaId.ONE}; - - for (KapuaId scopeId : scopeIds) { - MfaOptionQueryImpl mfaOptionQueryImpl = new MfaOptionQueryImpl(scopeId); - Assert.assertEquals("Expected and actual values should be the same.", scopeId, mfaOptionQueryImpl.getScopeId()); - Assert.assertNull("mfaOptionQueryImpl.sortCriteria", mfaOptionQueryImpl.getSortCriteria()); - Assert.assertNotNull("mfaOptionQueryImpl.defaultSortCriteria", mfaOptionQueryImpl.getDefaultSortCriteria()); - } - } -} \ No newline at end of file diff --git a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/credential/shiro/CredentialCreatorImplTest.java b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/credential/shiro/CredentialCreatorTest.java similarity index 91% rename from service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/credential/shiro/CredentialCreatorImplTest.java rename to service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/credential/shiro/CredentialCreatorTest.java index d47070f30d8..65f711c8e9b 100644 --- a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/credential/shiro/CredentialCreatorImplTest.java +++ b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/credential/shiro/CredentialCreatorTest.java @@ -12,26 +12,27 @@ *******************************************************************************/ package org.eclipse.kapua.service.authentication.credential.shiro; +import java.util.Date; + import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.qa.markers.junit.JUnitTests; +import org.eclipse.kapua.service.authentication.credential.CredentialCreator; import org.eclipse.kapua.service.authentication.credential.CredentialStatus; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; -import java.util.Date; - @Category(JUnitTests.class) -public class CredentialCreatorImplTest { +public class CredentialCreatorTest { - CredentialCreatorImpl credentialCreatorImpl1, credentialCreatorImpl2; + CredentialCreator credentialCreatorImpl1, credentialCreatorImpl2; @Before public void initialize() { - credentialCreatorImpl1 = new CredentialCreatorImpl(KapuaId.ONE, KapuaId.ONE, "API_KEY", "credential key", CredentialStatus.ENABLED, new Date()); - credentialCreatorImpl2 = new CredentialCreatorImpl(KapuaId.ONE); + credentialCreatorImpl1 = new CredentialCreator(KapuaId.ONE, KapuaId.ONE, "API_KEY", "credential key", CredentialStatus.ENABLED, new Date()); + credentialCreatorImpl2 = new CredentialCreator(KapuaId.ONE); } @Test @@ -49,7 +50,7 @@ public void credentialCreatorImplMultipleParametersTest() { for (String credentialKey : credentialKeys) { for (CredentialStatus credentialStatus : credentialStatuses) { for (Date date : dates) { - CredentialCreatorImpl credentialCreatorImpl = new CredentialCreatorImpl(scopeId, userId, credentialType, credentialKey, credentialStatus, date); + CredentialCreator credentialCreatorImpl = new CredentialCreator(scopeId, userId, credentialType, credentialKey, credentialStatus, date); Assert.assertEquals("Expected and actual values should be the same.", scopeId, credentialCreatorImpl.getScopeId()); Assert.assertEquals("Expected and actual values should be the same.", userId, credentialCreatorImpl.getUserId()); Assert.assertEquals("Expected and actual values should be the same.", credentialType, credentialCreatorImpl.getCredentialType()); @@ -68,7 +69,7 @@ public void credentialCreatorImplMultipleParametersTest() { public void credentialCreatorImplScopeIdParameterTest() { KapuaId[] scopeIds = {null, KapuaId.ONE}; for (KapuaId scopeId : scopeIds) { - CredentialCreatorImpl credentialCreatorImpl = new CredentialCreatorImpl(scopeId); + CredentialCreator credentialCreatorImpl = new CredentialCreator(scopeId); Assert.assertEquals("Expected and actual values should be the same.", scopeId, credentialCreatorImpl.getScopeId()); Assert.assertNull("Null expected.", credentialCreatorImpl.getUserId()); Assert.assertNull("Null expected.", credentialCreatorImpl.getCredentialType()); diff --git a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/credential/shiro/CredentialFactoryImplTest.java b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/credential/shiro/CredentialFactoryImplTest.java index 0261f3eb3b0..acee9d63cd1 100644 --- a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/credential/shiro/CredentialFactoryImplTest.java +++ b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/credential/shiro/CredentialFactoryImplTest.java @@ -12,24 +12,22 @@ *******************************************************************************/ package org.eclipse.kapua.service.authentication.credential.shiro; +import java.util.Date; + import org.eclipse.kapua.KapuaEntityCloneException; import org.eclipse.kapua.commons.model.id.KapuaEid; import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.qa.markers.junit.JUnitTests; -import org.eclipse.kapua.service.authentication.credential.CredentialStatus; import org.eclipse.kapua.service.authentication.credential.Credential; -import org.eclipse.kapua.service.authentication.credential.CredentialQuery; import org.eclipse.kapua.service.authentication.credential.CredentialCreator; -import org.eclipse.kapua.service.authentication.credential.CredentialListResult; +import org.eclipse.kapua.service.authentication.credential.CredentialStatus; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.mockito.Mockito; -import java.util.Date; - - @Category(JUnitTests.class) public class CredentialFactoryImplTest { @@ -46,12 +44,12 @@ public class CredentialFactoryImplTest { @Before public void initialize() { credentialFactoryImpl = new CredentialFactoryImpl(); - scopeIds = new KapuaId[]{null, KapuaId.ONE}; - userIds = new KapuaEid[]{null, new KapuaEid()}; - credentialKeys = new String[]{null, "", "!!credentialKey-1", "#1(credentialKey.,/Key)9--99", "!$$ 1-2 key//", "credential_K_ey(....)<00>"}; - credentialTypes = new String[] {null, "PASSWORD", "API_KEY", "JWT"}; - credentialStatuses = new CredentialStatus[]{null, CredentialStatus.ENABLED, CredentialStatus.DISABLED}; - dates = new Date[]{null, new Date()}; + scopeIds = new KapuaId[] { null, KapuaId.ONE }; + userIds = new KapuaEid[] { null, new KapuaEid() }; + credentialKeys = new String[] { null, "", "!!credentialKey-1", "#1(credentialKey.,/Key)9--99", "!$$ 1-2 key//", "credential_K_ey(....)<00>" }; + credentialTypes = new String[] { null, "PASSWORD", "API_KEY", "JWT" }; + credentialStatuses = new CredentialStatus[] { null, CredentialStatus.ENABLED, CredentialStatus.DISABLED }; + dates = new Date[] { null, new Date() }; credential = Mockito.mock(Credential.class); expirationDate = new Date(); modifiedOn = new Date(); @@ -65,7 +63,7 @@ public void newCreatorScopeIdUserIdMfaSecretKeyParametersTest() { for (String credentialKey : credentialKeys) { for (CredentialStatus credentialStatus : credentialStatuses) { for (Date date : dates) { - CredentialCreatorImpl credentialCreatorImpl = credentialFactoryImpl.newCreator(scopeId, userId, credentialType, credentialKey, credentialStatus, date); + CredentialCreator credentialCreatorImpl = new CredentialCreator(scopeId, userId, credentialType, credentialKey, credentialStatus, date); Assert.assertEquals("Expected and actual values should be the same.", scopeId, credentialCreatorImpl.getScopeId()); Assert.assertEquals("Expected and actual values should be the same.", userId, credentialCreatorImpl.getUserId()); Assert.assertEquals("Expected and actual values should be the same.", credentialType, credentialCreatorImpl.getCredentialType()); @@ -80,11 +78,6 @@ public void newCreatorScopeIdUserIdMfaSecretKeyParametersTest() { } } - @Test - public void newListResultTest() { - Assert.assertTrue("True expected.", credentialFactoryImpl.newListResult() instanceof CredentialListResult); - } - @Test public void newEntityTest() { for (KapuaId scopeId : scopeIds) { @@ -120,7 +113,7 @@ public void newMfaOptionTest() { @Test public void newQueryTest() { for (KapuaId scopeId : scopeIds) { - CredentialQuery credentialQuery = credentialFactoryImpl.newQuery(scopeId); + final KapuaQuery credentialQuery = new KapuaQuery(scopeId); Assert.assertEquals("Expected and actual values should be the same.", scopeId, credentialQuery.getScopeId()); } } @@ -128,7 +121,7 @@ public void newQueryTest() { @Test public void newCreatorScopeIdParameterTest() { for (KapuaId scopeId : scopeIds) { - CredentialCreator credentialCreator = credentialFactoryImpl.newCreator(scopeId); + CredentialCreator credentialCreator = new CredentialCreator(scopeId); Assert.assertEquals("Expected and actual values should be the same.", scopeId, credentialCreator.getScopeId()); } } diff --git a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/credential/shiro/CredentialQueryImplTest.java b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/credential/shiro/CredentialQueryImplTest.java deleted file mode 100644 index 7192854baa1..00000000000 --- a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/credential/shiro/CredentialQueryImplTest.java +++ /dev/null @@ -1,43 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authentication.credential.shiro; - -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.qa.markers.junit.JUnitTests; -import org.junit.Assert; -import org.junit.Test; -import org.junit.experimental.categories.Category; - - -@Category(JUnitTests.class) -public class CredentialQueryImplTest { - - @Test - public void credentialQueryImplWithoutParameterTest() { - CredentialQueryImpl credentialQueryImpl = new CredentialQueryImpl(); - Assert.assertNull("Null expected.", credentialQueryImpl.getScopeId()); - Assert.assertNull("credentialQueryImpl.sortCriteria", credentialQueryImpl.getSortCriteria()); - Assert.assertNotNull("credentialQueryImpl.defaultSortCriteria", credentialQueryImpl.getDefaultSortCriteria()); - } - - @Test - public void credentialQueryImplScopeIdTest() { - KapuaId[] scopeIds = {null, KapuaId.ONE}; - for (KapuaId scopeId : scopeIds) { - CredentialQueryImpl credentialQueryImpl = new CredentialQueryImpl(scopeId); - Assert.assertEquals("Expected and actual values should be the same.", scopeId, credentialQueryImpl.getScopeId()); - Assert.assertNull("credentialQueryImpl.sortCriteria", credentialQueryImpl.getSortCriteria()); - Assert.assertNotNull("credentialQueryImpl.defaultSortCriteria", credentialQueryImpl.getDefaultSortCriteria()); - } - } -} \ No newline at end of file diff --git a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/AccessTokenCredentialsImplTest.java b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/AccessTokenCredentialsImplTest.java index 04a54937b60..f89959c40aa 100644 --- a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/AccessTokenCredentialsImplTest.java +++ b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/AccessTokenCredentialsImplTest.java @@ -13,19 +13,16 @@ package org.eclipse.kapua.service.authentication.shiro; import org.eclipse.kapua.qa.markers.junit.JUnitTests; -import org.eclipse.kapua.service.authentication.AccessTokenCredentials; -import org.eclipse.kapua.service.authentication.shiro.realm.model.AccessTokenCredentialsAnotherImpl; import org.junit.Assert; import org.junit.Test; import org.junit.experimental.categories.Category; - @Category(JUnitTests.class) public class AccessTokenCredentialsImplTest { @Test(expected = NullPointerException.class) public void accessTokenCredentialsImplCloneConstructorNullTest() { - new AccessTokenCredentialsImpl((AccessTokenCredentials) null); + new AccessTokenCredentialsImpl((AccessTokenCredentialsImpl) null); } @Test @@ -40,7 +37,7 @@ public void accessTokenCredentialsImplCloneConstructorImplTest() { @Test public void accessTokenCredentialsImplCloneConstructorAnotherTest() { - AccessTokenCredentials first = new AccessTokenCredentialsAnotherImpl("anAccessToken"); + AccessTokenCredentialsImpl first = new AccessTokenCredentialsImpl("anAccessToken"); AccessTokenCredentialsImpl second = new AccessTokenCredentialsImpl(first); @@ -50,7 +47,7 @@ public void accessTokenCredentialsImplCloneConstructorAnotherTest() { @Test public void accessTokenCredentialsImplTokenIdParameterTest() { - String[] tokenIds = {null, "", "!!tokenID-1", "#1(TOKEN.,/token id)9--99", "!$$ 1-2 ID//", "id_tokeN(....)<00>"}; + String[] tokenIds = { null, "", "!!tokenID-1", "#1(TOKEN.,/token id)9--99", "!$$ 1-2 ID//", "id_tokeN(....)<00>" }; for (String tokenId : tokenIds) { AccessTokenCredentialsImpl accessTokenCredentialsImpl = new AccessTokenCredentialsImpl(tokenId); @@ -62,12 +59,14 @@ public void accessTokenCredentialsImplTokenIdParameterTest() { @Test public void setAndGetTokenIdPrincipalAndCredentialsTest() { - String[] newTokenIds = {null, "", "!!NEWtokenID-1", "#1(newTOKEN.,/token id)9--99", "!$$ 1-2new ID//", "id_tokeN NEW ID(....)<00>"}; - AccessTokenCredentialsImpl accessTokenCredentialsImpl = new AccessTokenCredentialsImpl("token id"); + String[] newTokenIds = { null, "", "!!NEWtokenID-1", "#1(newTOKEN.,/token id)9--99", "!$$ 1-2new ID//", "id_tokeN NEW ID(....)<00>" }; + AccessTokenCredentialsImpl accessTokenCredentials = new AccessTokenCredentialsImpl("token id"); for (String newTokenId : newTokenIds) { - accessTokenCredentialsImpl.setTokenId(newTokenId); - Assert.assertEquals("Expected and actual values should be the same.", newTokenId, accessTokenCredentialsImpl.getTokenId()); + accessTokenCredentials.setTokenId(newTokenId); + Assert.assertEquals("Expected and actual values should be the same.", newTokenId, accessTokenCredentials.getTokenId()); + AccessTokenCredentialsImpl accessTokenCredentialsImpl = new AccessTokenCredentialsImpl(accessTokenCredentials); + accessTokenCredentials.setTokenId(newTokenId); Assert.assertEquals("Expected and actual values should be the same.", newTokenId, accessTokenCredentialsImpl.getPrincipal()); Assert.assertEquals("Expected and actual values should be the same.", newTokenId, accessTokenCredentialsImpl.getCredentials()); } diff --git a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/ApiKeyCredentialsImplTest.java b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/ApiKeyCredentialsImplTest.java index 46f0293b37b..d2474e8f895 100644 --- a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/ApiKeyCredentialsImplTest.java +++ b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/ApiKeyCredentialsImplTest.java @@ -14,12 +14,10 @@ import org.eclipse.kapua.qa.markers.junit.JUnitTests; import org.eclipse.kapua.service.authentication.ApiKeyCredentials; -import org.eclipse.kapua.service.authentication.shiro.realm.model.ApiKeyCredentialsAnotherImpl; import org.junit.Assert; import org.junit.Test; import org.junit.experimental.categories.Category; - @Category(JUnitTests.class) public class ApiKeyCredentialsImplTest { @@ -30,17 +28,7 @@ public void apiKeyCredentialsImplCloneConstructorNullTest() { @Test public void apiKeyCredentialsImplCloneConstructorImplTest() { - ApiKeyCredentialsImpl first = new ApiKeyCredentialsImpl("anApiKey"); - - ApiKeyCredentialsImpl second = new ApiKeyCredentialsImpl(first); - - Assert.assertNotEquals("ApiKeyCredentialImpl", first, second); - Assert.assertEquals("ApiKeyCredential.apiKey", first.getApiKey(), second.getApiKey()); - } - - @Test - public void apiKeyCredentialsImplCloneConstructorAnotherTest() { - ApiKeyCredentials first = new ApiKeyCredentialsAnotherImpl("anApiKey"); + ApiKeyCredentials first = new ApiKeyCredentials("anApiKey"); ApiKeyCredentialsImpl second = new ApiKeyCredentialsImpl(first); @@ -50,7 +38,7 @@ public void apiKeyCredentialsImplCloneConstructorAnotherTest() { @Test public void apiKeyCredentialsImplTest() { - String[] apiKeys = {null, "", "!!api key-1", "#1(API KEY.,/api key)9--99", "!$$ 1-2 KEY//", "APIkey(....)<00>"}; + String[] apiKeys = { null, "", "!!api key-1", "#1(API KEY.,/api key)9--99", "!$$ 1-2 KEY//", "APIkey(....)<00>" }; for (String apiKey : apiKeys) { ApiKeyCredentialsImpl apiKeyCredentialsImpl = new ApiKeyCredentialsImpl(apiKey); @@ -62,11 +50,12 @@ public void apiKeyCredentialsImplTest() { @Test public void setAndGetApiKeyPrincipalAndCredentialsTest() { - String[] newApiKeys = {null, "", "!!api key-1NEW", "#1(new API KEY.,/api key)9--99", "!$$ 1-2 newKEY//", "NEwAPIkey(....)<00>"}; - ApiKeyCredentialsImpl apiKeyCredentialsImpl = new ApiKeyCredentialsImpl("apiKey"); + String[] newApiKeys = { null, "", "!!api key-1NEW", "#1(new API KEY.,/api key)9--99", "!$$ 1-2 newKEY//", "NEwAPIkey(....)<00>" }; + ApiKeyCredentials apiKeyCredentials = new ApiKeyCredentials("apiKey"); for (String newApiKey : newApiKeys) { - apiKeyCredentialsImpl.setApiKey(newApiKey); + apiKeyCredentials.setApiKey(newApiKey); + ApiKeyCredentialsImpl apiKeyCredentialsImpl = new ApiKeyCredentialsImpl(apiKeyCredentials); Assert.assertEquals("Expected and actual values should be the same.", newApiKey, apiKeyCredentialsImpl.getApiKey()); Assert.assertEquals("Expected and actual values should be the same.", newApiKey, apiKeyCredentialsImpl.getPrincipal()); Assert.assertEquals("Expected and actual values should be the same.", newApiKey, apiKeyCredentialsImpl.getCredentials()); diff --git a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/CredentialsFactoryImplTest.java b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/CredentialsFactoryTest.java similarity index 63% rename from service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/CredentialsFactoryImplTest.java rename to service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/CredentialsFactoryTest.java index 25c28463c56..9c8ee27c15e 100644 --- a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/CredentialsFactoryImplTest.java +++ b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/CredentialsFactoryTest.java @@ -13,40 +13,36 @@ package org.eclipse.kapua.service.authentication.shiro; import org.eclipse.kapua.qa.markers.junit.JUnitTests; -import org.eclipse.kapua.service.authentication.UsernamePasswordCredentials; -import org.eclipse.kapua.service.authentication.AccessTokenCredentials; import org.eclipse.kapua.service.authentication.ApiKeyCredentials; import org.eclipse.kapua.service.authentication.JwtCredentials; import org.eclipse.kapua.service.authentication.RefreshTokenCredentials; - +import org.eclipse.kapua.service.authentication.UsernamePasswordCredentials; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; - @Category(JUnitTests.class) -public class CredentialsFactoryImplTest { +public class CredentialsFactoryTest { - CredentialsFactoryImpl credentialsFactoryImpl; String[] usernames, passwords, apiKeys, idTokens, accessTokens, refreshTokens; @Before public void initialize() { - credentialsFactoryImpl = new CredentialsFactoryImpl(); - usernames = new String[]{null, "", "user_name123!!", "user#999username", "USERNAME_9", "user,,,,name", "... us_er%%67na*(me"}; - passwords = new String[]{null, "", "pass-word0000@!!,,,#", "!@#00PaSSwOrD.", " password ---44<>", "pA_ss0###woE**9()", " pass0wo-rd 12344*&^%"}; - apiKeys = new String[]{null, "", "api_key1122#$%", " aPi)(..,,KEY", "apiKEYYY ./??)_)*", "<> 1111 ", "keyyy&^$$##Z||'", "%%%KEY api-key11"}; - idTokens = new String[]{null, "", " ID tokenID 747.,.,,,82(*&%<> ", " token((11@-", "id)__.,TOKen65", "TOKENid543$#%&t oken", "to-ken_id++=,", "id,,,,id3$^&"}; - accessTokens = new String[]{null, "", " j_w=t110.,<> jwt", "(!!)432j&^w$#3t", "##<>/.JWT ", "__J!#W(-8T ", "jw&* 990t ", "jwt987)_=;''' .", "jwt JWT-123"}; - refreshTokens = new String[]{null, "", " refresh tokenREFRESH 747.,.,,,82(*&%<> ", " token((11@-", "REFresh)__.,TOKen65", "TOKENrefresh543$#%&t oken", "to-ken_++rE=fresh,", "refresh,,,,id3$^&"}; + usernames = new String[] { null, "", "user_name123!!", "user#999username", "USERNAME_9", "user,,,,name", "... us_er%%67na*(me" }; + passwords = new String[] { null, "", "pass-word0000@!!,,,#", "!@#00PaSSwOrD.", " password ---44<>", "pA_ss0###woE**9()", " pass0wo-rd 12344*&^%" }; + apiKeys = new String[] { null, "", "api_key1122#$%", " aPi)(..,,KEY", "apiKEYYY ./??)_)*", "<> 1111 ", "keyyy&^$$##Z||'", "%%%KEY api-key11" }; + idTokens = new String[] { null, "", " ID tokenID 747.,.,,,82(*&%<> ", " token((11@-", "id)__.,TOKen65", "TOKENid543$#%&t oken", "to-ken_id++=,", "id,,,,id3$^&" }; + accessTokens = new String[] { null, "", " j_w=t110.,<> jwt", "(!!)432j&^w$#3t", "##<>/.JWT ", "__J!#W(-8T ", "jw&* 990t ", "jwt987)_=;''' .", "jwt JWT-123" }; + refreshTokens = new String[] { null, "", " refresh tokenREFRESH 747.,.,,,82(*&%<> ", " token((11@-", "REFresh)__.,TOKen65", "TOKENrefresh543$#%&t oken", "to-ken_++rE=fresh,", + "refresh,,,,id3$^&" }; } @Test public void newUsernamePasswordCredentialsTest() { for (String username : usernames) { for (String password : passwords) { - UsernamePasswordCredentials usernamePasswordCredentials = credentialsFactoryImpl.newUsernamePasswordCredentials(username, password); + UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials(username, password); Assert.assertEquals("Expected and actual values should be the same.", username, usernamePasswordCredentials.getUsername()); Assert.assertEquals("Expected and actual values should be the same.", password, usernamePasswordCredentials.getPassword()); } @@ -56,7 +52,7 @@ public void newUsernamePasswordCredentialsTest() { @Test public void newApiKeyCredentialsTest() { for (String apiKey : apiKeys) { - ApiKeyCredentials apiKeyCredentials = credentialsFactoryImpl.newApiKeyCredentials(apiKey); + ApiKeyCredentials apiKeyCredentials = new ApiKeyCredentials(apiKey); Assert.assertEquals("Expected and actual values should be the same.", apiKey, apiKeyCredentials.getApiKey()); } } @@ -65,7 +61,7 @@ public void newApiKeyCredentialsTest() { public void newJwtCredentialsTest() { for (String accessToken : accessTokens) { for (String idToken : idTokens) { - JwtCredentials jwtCredentials = credentialsFactoryImpl.newJwtCredentials(accessToken, idToken); + JwtCredentials jwtCredentials = new JwtCredentials(accessToken, idToken); Assert.assertEquals("Expected and actual values should be the same.", accessToken, jwtCredentials.getAccessToken()); Assert.assertEquals("Expected and actual values should be the same.", idToken, jwtCredentials.getIdToken()); } @@ -73,9 +69,9 @@ public void newJwtCredentialsTest() { } @Test - public void newAccessTokenCredentialsTest() { + public void newAccessTokenCredentialsImplTest() { for (String idToken : idTokens) { - AccessTokenCredentials accessTokenCredentials = credentialsFactoryImpl.newAccessTokenCredentials(idToken); + AccessTokenCredentialsImpl accessTokenCredentials = new AccessTokenCredentialsImpl(idToken); Assert.assertEquals("Expected and actual values should be the same.", idToken, accessTokenCredentials.getTokenId()); } } @@ -84,7 +80,7 @@ public void newAccessTokenCredentialsTest() { public void newRefreshTokenCredentialsTest() { for (String idToken : idTokens) { for (String refreshToken : refreshTokens) { - RefreshTokenCredentials refreshTokenCredentials = credentialsFactoryImpl.newRefreshTokenCredentials(idToken, refreshToken); + RefreshTokenCredentials refreshTokenCredentials = new RefreshTokenCredentials(idToken, refreshToken); Assert.assertEquals("Expected and actual values should be the same.", idToken, refreshTokenCredentials.getTokenId()); Assert.assertEquals("Expected and actual values should be the same.", refreshToken, refreshTokenCredentials.getRefreshToken()); } diff --git a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/JwtCredentialsTest.java b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/JwtCredentialsTest.java index abb4dc254fe..d17688ae9fb 100644 --- a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/JwtCredentialsTest.java +++ b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/JwtCredentialsTest.java @@ -14,26 +14,24 @@ import org.eclipse.kapua.qa.markers.junit.JUnitTests; import org.eclipse.kapua.service.authentication.JwtCredentials; -import org.eclipse.kapua.service.authentication.shiro.realm.model.JwtCredentialsAnotherImpl; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; - @Category(JUnitTests.class) public class JwtCredentialsTest { - JwtCredentialsImpl jwtCredentialsImpl; + JwtCredentials jwtCredentials; String[] accessTokens, idsToken, newAccessTokens, newIdsToken; @Before public void initialize() { - jwtCredentialsImpl = new JwtCredentialsImpl("accessToken", "idToken"); - idsToken = new String[]{null, "", " ID tokenID 747.,.,,,82(*&%<> ", " token((11@-", "id)__.,TOKen65", "TOKENid543$#%&t oken", "to-ken_id++=,", "id,,,,id3$^&"}; - accessTokens = new String[]{null, "", " j_w=t110.,<> jwt", "(!!)432j&^w$#3t", "##<>/.JWT ", "__J!#W(-8T ", "jw&* 990t ", "jwt987)_=;''' .", "jwt JWT-123"}; - newAccessTokens = new String[]{null, "", "new_Jwt1122#$%", " JWT)(..,,new", "NEW_jwt ./??)_)*", "<> 1111 ", "jwttt&^$$##Z||'", "%%%KEY NEW-JWT11"}; - newIdsToken = new String[]{null, "", "NEW tokenID0000@!!,,,#", "!@#00tokenID new.", " new id TOK --EN-44<>", "pA_ss0###woE**9()", " tokenID new tokenID 12344*&^%"}; + jwtCredentials = new JwtCredentials("accessToken", "idToken"); + idsToken = new String[] { null, "", " ID tokenID 747.,.,,,82(*&%<> ", " token((11@-", "id)__.,TOKen65", "TOKENid543$#%&t oken", "to-ken_id++=,", "id,,,,id3$^&" }; + accessTokens = new String[] { null, "", " j_w=t110.,<> jwt", "(!!)432j&^w$#3t", "##<>/.JWT ", "__J!#W(-8T ", "jw&* 990t ", "jwt987)_=;''' .", "jwt JWT-123" }; + newAccessTokens = new String[] { null, "", "new_Jwt1122#$%", " JWT)(..,,new", "NEW_jwt ./??)_)*", "<> 1111 ", "jwttt&^$$##Z||'", "%%%KEY NEW-JWT11" }; + newIdsToken = new String[] { null, "", "NEW tokenID0000@!!,,,#", "!@#00tokenID new.", " new id TOK --EN-44<>", "pA_ss0###woE**9()", " tokenID new tokenID 12344*&^%" }; } @Test(expected = NullPointerException.class) @@ -43,7 +41,7 @@ public void jwtCredentialsImplCloneConstructorNullTest() { @Test public void jwtCredentialsImplCloneConstructorImplTest() { - JwtCredentialsImpl first = new JwtCredentialsImpl("aJwt", "anIdToken"); + JwtCredentials first = new JwtCredentials("aJwt", "anIdToken"); JwtCredentialsImpl second = new JwtCredentialsImpl(first); @@ -54,7 +52,7 @@ public void jwtCredentialsImplCloneConstructorImplTest() { @Test public void jwtCredentialsImplCloneConstructorAnotherTest() { - JwtCredentials first = new JwtCredentialsAnotherImpl("aJwt", "anIdToken"); + JwtCredentials first = new JwtCredentials("aJwt", "anIdToken"); JwtCredentialsImpl second = new JwtCredentialsImpl(first); @@ -67,7 +65,7 @@ public void jwtCredentialsImplCloneConstructorAnotherTest() { public void jwtCredentialsImplTest() { for (String accessToken : accessTokens) { for (String idToken : idsToken) { - JwtCredentialsImpl jwtCredentialsImpl = new JwtCredentialsImpl(accessToken, idToken); + JwtCredentialsImpl jwtCredentialsImpl = new JwtCredentialsImpl(new JwtCredentials(accessToken, idToken)); Assert.assertEquals("Expected and actual values should be the same.", accessToken, jwtCredentialsImpl.getAccessToken()); Assert.assertEquals("Expected and actual values should be the same.", idToken, jwtCredentialsImpl.getIdToken()); Assert.assertEquals("Expected and actual values should be the same.", accessToken, jwtCredentialsImpl.getPrincipal()); @@ -79,18 +77,19 @@ public void jwtCredentialsImplTest() { @Test public void setAndGetJwtPrincipalAndCredentialTest() { for (String newAccessToken : newAccessTokens) { - jwtCredentialsImpl.setAccessToken(newAccessToken); - Assert.assertEquals("Expected and actual values should be the same.", newAccessToken, jwtCredentialsImpl.getAccessToken()); - Assert.assertEquals("Expected and actual values should be the same.", newAccessToken, jwtCredentialsImpl.getPrincipal()); - Assert.assertEquals("Expected and actual values should be the same.", newAccessToken, jwtCredentialsImpl.getCredentials()); + jwtCredentials.setAccessToken(newAccessToken); + final JwtCredentialsImpl credentials = new JwtCredentialsImpl(jwtCredentials); + Assert.assertEquals("Expected and actual values should be the same.", newAccessToken, credentials.getAccessToken()); + Assert.assertEquals("Expected and actual values should be the same.", newAccessToken, credentials.getPrincipal()); + Assert.assertEquals("Expected and actual values should be the same.", newAccessToken, credentials.getCredentials()); } } @Test public void setAndGetIdTokenTest() { for (String newIdToken : newIdsToken) { - jwtCredentialsImpl.setIdToken(newIdToken); - Assert.assertEquals("Expected and actual values should be the same.", newIdToken, jwtCredentialsImpl.getIdToken()); + jwtCredentials.setIdToken(newIdToken); + Assert.assertEquals("Expected and actual values should be the same.", newIdToken, jwtCredentials.getIdToken()); } } } diff --git a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/RefreshTokenCredentialsImplTest.java b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/RefreshTokenCredentialsImplTest.java deleted file mode 100644 index 03f494db645..00000000000 --- a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/RefreshTokenCredentialsImplTest.java +++ /dev/null @@ -1,64 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authentication.shiro; - -import org.eclipse.kapua.qa.markers.junit.JUnitTests; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.experimental.categories.Category; - - -@Category(JUnitTests.class) -public class RefreshTokenCredentialsImplTest { - - String[] idsToken, refreshTokens, newIdsToken, newRefreshTokens; - RefreshTokenCredentialsImpl refreshTokenCredentialsImpl; - - @Before - public void initialize() { - idsToken = new String[]{null, "", " ID tokenID 747.,.,,,82(*&%<> ", " token((11@-", "id)__.,TOKen65", "TOKENid543$#%&t oken", "to-ken_id++=,", "id,,,,id3$^&"}; - refreshTokens = new String[]{null, "", " refresh tokenREFRESH 747.,.,,,82(*&%<> ", " token((11@-", "REFresh)__.,TOKen65", "TOKENrefresh543$#%&t oken", "to-ken_++rE=fresh,", "refresh,,,,id3$^&"}; - newIdsToken = new String[]{null, "", "NEW tokenID0000@!!,,,#", "!@#00tokenID new.", " new id TOK --EN-44<>", "pA_ss0###woE**9()", " tokenID new tokenID 12344*&^%"}; - newRefreshTokens = new String[]{null, "", "new_refresh1122TOKEN#$%", " JWT)(..,,new", "NEW_token .refresh/??)_)*", "<> 1111 ", "jwttt&^$$##Z||'", "%%%KEY NEW-TOKEN1r-e5f&resh"}; - } - - @Test - public void refreshTokenCredentialsImplTest() { - for (String idToken : idsToken) { - for (String refreshToken : refreshTokens) { - refreshTokenCredentialsImpl = new RefreshTokenCredentialsImpl(idToken, refreshToken); - Assert.assertEquals("Expected and actual values should be the same.", idToken, refreshTokenCredentialsImpl.getTokenId()); - Assert.assertEquals("Expected and actual values should be the same.", refreshToken, refreshTokenCredentialsImpl.getRefreshToken()); - } - } - } - - @Test - public void setAndGetTokenIdTest() { - refreshTokenCredentialsImpl = new RefreshTokenCredentialsImpl("token id", "refresh token"); - for (String newIdToken : newIdsToken) { - refreshTokenCredentialsImpl.setTokenId(newIdToken); - Assert.assertEquals("Expected and actual values should be the same.", newIdToken, refreshTokenCredentialsImpl.getTokenId()); - } - } - - @Test - public void setAndGetRefreshTokenTest() { - refreshTokenCredentialsImpl = new RefreshTokenCredentialsImpl("token id", "refresh token"); - for (String newRefreshToken : newRefreshTokens) { - refreshTokenCredentialsImpl.setRefreshToken(newRefreshToken); - Assert.assertEquals("Expected and actual values should be the same.", newRefreshToken, refreshTokenCredentialsImpl.getRefreshToken()); - } - } -} \ No newline at end of file diff --git a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/RefreshTokenCredentialsTest.java b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/RefreshTokenCredentialsTest.java new file mode 100644 index 00000000000..7198413e091 --- /dev/null +++ b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/RefreshTokenCredentialsTest.java @@ -0,0 +1,65 @@ +/******************************************************************************* + * Copyright (c) 2021, 2022 Eurotech and/or its affiliates and others + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Eurotech - initial API and implementation + *******************************************************************************/ +package org.eclipse.kapua.service.authentication.shiro; + +import org.eclipse.kapua.qa.markers.junit.JUnitTests; +import org.eclipse.kapua.service.authentication.RefreshTokenCredentials; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.experimental.categories.Category; + +@Category(JUnitTests.class) +public class RefreshTokenCredentialsTest { + + String[] idsToken, refreshTokens, newIdsToken, newRefreshTokens; + RefreshTokenCredentials refreshTokenCredentials; + + @Before + public void initialize() { + idsToken = new String[] { null, "", " ID tokenID 747.,.,,,82(*&%<> ", " token((11@-", "id)__.,TOKen65", "TOKENid543$#%&t oken", "to-ken_id++=,", "id,,,,id3$^&" }; + refreshTokens = new String[] { null, "", " refresh tokenREFRESH 747.,.,,,82(*&%<> ", " token((11@-", "REFresh)__.,TOKen65", "TOKENrefresh543$#%&t oken", "to-ken_++rE=fresh,", + "refresh,,,,id3$^&" }; + newIdsToken = new String[] { null, "", "NEW tokenID0000@!!,,,#", "!@#00tokenID new.", " new id TOK --EN-44<>", "pA_ss0###woE**9()", " tokenID new tokenID 12344*&^%" }; + newRefreshTokens = new String[] { null, "", "new_refresh1122TOKEN#$%", " JWT)(..,,new", "NEW_token .refresh/??)_)*", "<> 1111 ", "jwttt&^$$##Z||'", "%%%KEY NEW-TOKEN1r-e5f&resh" }; + } + + @Test + public void refreshTokenCredentialsTest() { + for (String idToken : idsToken) { + for (String refreshToken : refreshTokens) { + refreshTokenCredentials = new RefreshTokenCredentials(idToken, refreshToken); + Assert.assertEquals("Expected and actual values should be the same.", idToken, refreshTokenCredentials.getTokenId()); + Assert.assertEquals("Expected and actual values should be the same.", refreshToken, refreshTokenCredentials.getRefreshToken()); + } + } + } + + @Test + public void setAndGetTokenIdTest() { + refreshTokenCredentials = new RefreshTokenCredentials("token id", "refresh token"); + for (String newIdToken : newIdsToken) { + refreshTokenCredentials.setTokenId(newIdToken); + Assert.assertEquals("Expected and actual values should be the same.", newIdToken, refreshTokenCredentials.getTokenId()); + } + } + + @Test + public void setAndGetRefreshTokenTest() { + refreshTokenCredentials = new RefreshTokenCredentials("token id", "refresh token"); + for (String newRefreshToken : newRefreshTokens) { + refreshTokenCredentials.setRefreshToken(newRefreshToken); + Assert.assertEquals("Expected and actual values should be the same.", newRefreshToken, refreshTokenCredentials.getRefreshToken()); + } + } +} \ No newline at end of file diff --git a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/UsernamePasswordCredentialsImplTest.java b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/UsernamePasswordCredentialsImplTest.java deleted file mode 100644 index 3726bdf472d..00000000000 --- a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/UsernamePasswordCredentialsImplTest.java +++ /dev/null @@ -1,164 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authentication.shiro; - -import org.eclipse.kapua.qa.markers.junit.JUnitTests; -import org.eclipse.kapua.service.authentication.UsernamePasswordCredentials; -import org.eclipse.kapua.service.authentication.shiro.realm.model.UsernamePasswordCredentialsAnotherImpl; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.experimental.categories.Category; - - -@Category(JUnitTests.class) -public class UsernamePasswordCredentialsImplTest { - - String[] usernames, passwords, newUsernames, newPasswords, trustKeys, authenticationCodes; - UsernamePasswordCredentialsImpl usernamePasswordCredentialsImpl; - - @Before - public void initialize() { - usernames = new String[]{null, "", "user_name123!!", "user#999username", "USERNAME_9", "user,,,,name", "... us_er%%67na*(me"}; - passwords = new String[]{null, "", "pass-word0000@!!,,,#", "!@#00PaSSwOrD.", " password ---44<>", "pA_ss0###woE**9()", " pass0wo-rd 12344*&^%"}; - newUsernames = new String[]{null, "", "NEW---user_name123!!", "user#999username,.,@#NEW", "1111USERNAME_9", " new--^%4user,,,,name", "... us_er%%67na*(me NEW "}; - newPasswords = new String[]{null, "", "pass-word0000@!!,new password,,#", "!@#00PaSSwOrD._@#new", "new password ---44<>", " new#@$pA_ss0###woE**9()", " pass0wo-rd 12344*NEW&^%"}; - trustKeys = new String[]{null, "", "!!trust key-1", "#1(TRUST KEY.,/trust key)9--99", "!$$ 1-2 KEY//", "trust 99key(....)<00>"}; - authenticationCodes = new String[]{null, "", " authentication@#$%Code=t110.,<> code", "(!!)432j&^authenti)(&%cation-Code$#3t", "##<>/.CODE ", "__J!#W(-8T ", "authenticatioN&* 99code0t ", "jwt987)_=;''' .", "jwt CODE-123"}; - usernamePasswordCredentialsImpl = new UsernamePasswordCredentialsImpl("username", "password"); - } - - @Test(expected = NullPointerException.class) - public void usernamePasswordCredentialsImplCloneConstructorNullTest() { - new UsernamePasswordCredentialsImpl(null); - } - - @Test - public void usernamePasswordCredentialsImplCloneConstructorImplTest() { - UsernamePasswordCredentialsImpl first = new UsernamePasswordCredentialsImpl("aUsername", "aPassword"); - first.setTrustKey("aTrustKey"); - first.setAuthenticationCode("aAuthCode"); - - UsernamePasswordCredentialsImpl second = new UsernamePasswordCredentialsImpl(first); - - Assert.assertNotEquals("UsernamePasswordCredentialImpl", first, second); - Assert.assertEquals("UsernamePasswordCredential.username", first.getUsername(), second.getUsername()); - Assert.assertEquals("UsernamePasswordCredential.password", first.getPassword(), second.getPassword()); - Assert.assertEquals("UsernamePasswordCredential.trustKey", first.getTrustKey(), second.getTrustKey()); - Assert.assertEquals("UsernamePasswordCredential.authenticationCode", first.getAuthenticationCode(), second.getAuthenticationCode()); - } - - @Test - public void usernamePasswordCredentialsImplCloneConstructorAnotherTest() { - UsernamePasswordCredentials first = new UsernamePasswordCredentialsAnotherImpl("aUsername", "aPassword"); - first.setTrustKey("aTrustKey"); - first.setAuthenticationCode("aAuthCode"); - - UsernamePasswordCredentialsImpl second = new UsernamePasswordCredentialsImpl(first); - - Assert.assertNotEquals("UsernamePasswordCredentialImpl", first, second); - Assert.assertEquals("UsernamePasswordCredential.username", first.getUsername(), second.getUsername()); - Assert.assertEquals("UsernamePasswordCredential.password", first.getPassword(), second.getPassword()); - Assert.assertEquals("UsernamePasswordCredential.trustKey", first.getTrustKey(), second.getTrustKey()); - Assert.assertEquals("UsernamePasswordCredential.authenticationCode", first.getAuthenticationCode(), second.getAuthenticationCode()); - } - - @Test - public void usernamePasswordCredentialsImplParseNullTest() { - UsernamePasswordCredentialsImpl first = null; - - UsernamePasswordCredentialsImpl second = UsernamePasswordCredentialsImpl.parse(null); - - Assert.assertNull("Parsed UsernamePasswordCredentialsImpl", second); - Assert.assertEquals("UsernamePasswordCredentialImpl", first, second); - } - - @Test - public void usernamePasswordCredentialsImplParseImplTest() { - UsernamePasswordCredentialsImpl first = new UsernamePasswordCredentialsImpl("aUsername", "aPassword"); - first.setTrustKey("aTrustKey"); - first.setAuthenticationCode("aAuthCode"); - - UsernamePasswordCredentialsImpl second = UsernamePasswordCredentialsImpl.parse(first); - - Assert.assertEquals("UsernamePasswordCredentialImpl", first, second); - Assert.assertEquals("UsernamePasswordCredential.username", first.getUsername(), second.getUsername()); - Assert.assertEquals("UsernamePasswordCredential.password", first.getPassword(), second.getPassword()); - Assert.assertEquals("UsernamePasswordCredential.trustKey", first.getTrustKey(), second.getTrustKey()); - Assert.assertEquals("UsernamePasswordCredential.authenticationCode", first.getAuthenticationCode(), second.getAuthenticationCode()); - } - - @Test - public void usernamePasswordCredentiaslImplParseAnotherTest() { - UsernamePasswordCredentials first = new UsernamePasswordCredentialsAnotherImpl("aUsername", "aPassword"); - first.setTrustKey("aTrustKey"); - first.setAuthenticationCode("aAuthCode"); - - UsernamePasswordCredentialsImpl second = UsernamePasswordCredentialsImpl.parse(first); - - Assert.assertNotEquals("UsernamePasswordCredentialImpl", first, second); - Assert.assertEquals("UsernamePasswordCredential.username", first.getUsername(), second.getUsername()); - Assert.assertEquals("UsernamePasswordCredential.password", first.getPassword(), second.getPassword()); - Assert.assertEquals("UsernamePasswordCredential.trustKey", first.getTrustKey(), second.getTrustKey()); - Assert.assertEquals("UsernamePasswordCredential.authenticationCode", first.getAuthenticationCode(), second.getAuthenticationCode()); - } - - @Test - public void usernamePasswordCredentialsImplTest() { - for (String username : usernames) { - for (String password : passwords) { - UsernamePasswordCredentialsImpl usernamePasswordCredentialsImpl = new UsernamePasswordCredentialsImpl(username, password); - Assert.assertEquals("Expected and actual values should be the same.", username, usernamePasswordCredentialsImpl.getUsername()); - Assert.assertEquals("Expected and actual values should be the same.", username, usernamePasswordCredentialsImpl.getPrincipal()); - Assert.assertEquals("Expected and actual values should be the same.", password, usernamePasswordCredentialsImpl.getPassword()); - Assert.assertEquals("Expected and actual values should be the same.", password, usernamePasswordCredentialsImpl.getCredentials()); - Assert.assertNull("Null expected.", usernamePasswordCredentialsImpl.getAuthenticationCode()); - Assert.assertNull("Null expected.", usernamePasswordCredentialsImpl.getTrustKey()); - } - } - } - - @Test - public void setAndGetUsernameAndPrincipalTest() { - for (String newUsername : newUsernames) { - usernamePasswordCredentialsImpl.setUsername(newUsername); - Assert.assertEquals("Expected and actual values should be the same.", newUsername, usernamePasswordCredentialsImpl.getUsername()); - Assert.assertEquals("Expected and actual values should be the same.", newUsername, usernamePasswordCredentialsImpl.getPrincipal()); - } - } - - @Test - public void setAndGetPasswordAndCredentialsTest() { - for (String newPassword : newPasswords) { - usernamePasswordCredentialsImpl.setPassword(newPassword); - Assert.assertEquals("Expected and actual values should be the same.", newPassword, usernamePasswordCredentialsImpl.getPassword()); - Assert.assertEquals("Expected and actual values should be the same.", newPassword, usernamePasswordCredentialsImpl.getCredentials()); - } - } - - @Test - public void setAndGetAuthenticationCodeTest() { - for (String authenticationCode : authenticationCodes) { - usernamePasswordCredentialsImpl.setAuthenticationCode(authenticationCode); - Assert.assertEquals("Expected and actual values should be the same.", authenticationCode, usernamePasswordCredentialsImpl.getAuthenticationCode()); - } - } - - @Test - public void setAndGetTrustKeyTest() { - for (String trustKey : trustKeys) { - usernamePasswordCredentialsImpl.setTrustKey(trustKey); - Assert.assertEquals("Expected and actual values should be the same.", trustKey, usernamePasswordCredentialsImpl.getTrustKey()); - } - } -} \ No newline at end of file diff --git a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/realm/AccessTokenCredentialsConverterTest.java b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/realm/AccessTokenCredentialsConverterTest.java deleted file mode 100644 index fa8f896a30f..00000000000 --- a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/realm/AccessTokenCredentialsConverterTest.java +++ /dev/null @@ -1,87 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2023, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authentication.shiro.realm; - -import org.eclipse.kapua.qa.markers.junit.JUnitTests; -import org.eclipse.kapua.service.authentication.AccessTokenCredentials; -import org.eclipse.kapua.service.authentication.exception.KapuaAuthenticationException; -import org.eclipse.kapua.service.authentication.shiro.AccessTokenCredentialsImpl; -import org.eclipse.kapua.service.authentication.shiro.realm.model.AccessTokenCredentialsAnotherImpl; -import org.eclipse.kapua.service.authentication.shiro.realm.model.NotProcessableCredentials; -import org.eclipse.kapua.service.authentication.shiro.realm.model.NotProcessableCredentialsImpl; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.experimental.categories.Category; - -@Category(JUnitTests.class) -public class AccessTokenCredentialsConverterTest { - - AccessTokenCredentialsConverter instance; - - @Before - public void setUp() { - instance = new AccessTokenCredentialsConverter(); - } - - @Test - public void accessTokenCredentialsImplCanProcessNullTest() { - Assert.assertFalse(instance.canProcess(null)); - } - - @Test - public void accessTokenCredentialsImplCanProcessImplTest() throws KapuaAuthenticationException { - AccessTokenCredentials accessTokenCredentialsImpl = new AccessTokenCredentialsImpl("anAccessToken"); - AccessTokenCredentials accessTokenCredentialsAnother = new AccessTokenCredentialsAnotherImpl("anAccessToken"); - NotProcessableCredentials notProcessableCredentials = new NotProcessableCredentialsImpl(); - - Assert.assertTrue(instance.canProcess(accessTokenCredentialsImpl)); - Assert.assertTrue(instance.canProcess(accessTokenCredentialsAnother)); - Assert.assertFalse(instance.canProcess(notProcessableCredentials)); - } - - @Test - public void accessTokenCredentialsImplMapToShiroImplTest() throws KapuaAuthenticationException { - AccessTokenCredentialsImpl first = new AccessTokenCredentialsImpl("anAccessToken"); - - AccessTokenCredentialsImpl second = (AccessTokenCredentialsImpl) instance.convertToShiro(first); - - Assert.assertEquals(first, second); - Assert.assertEquals(first.getTokenId(), second.getTokenId()); - } - - @Test - public void accessTokenCredentialsImplMapToShiroAnotherTest() throws KapuaAuthenticationException { - AccessTokenCredentials first = new AccessTokenCredentialsAnotherImpl("anAccessToken"); - - AccessTokenCredentialsImpl second = (AccessTokenCredentialsImpl) instance.convertToShiro(first); - - Assert.assertNotNull(second); - Assert.assertNotEquals(first, second); - Assert.assertEquals(first.getTokenId(), second.getTokenId()); - } - - @Test(expected = NullPointerException.class) - public void accessTokenCredentialsImplMapToShiroNullTest() throws KapuaAuthenticationException { - instance.convertToShiro(null); - } - - @Test(expected = KapuaAuthenticationException.class) - public void accessTokenCredentialsImplMapToShiroEmptyTest() throws KapuaAuthenticationException { - AccessTokenCredentialsImpl first = new AccessTokenCredentialsImpl((String) null); - - Assert.assertNotNull(first); - - instance.convertToShiro(first); - } -} \ No newline at end of file diff --git a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/realm/ApiKeyCredentialsConverterTest.java b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/realm/ApiKeyCredentialsConverterTest.java index 34f6b79ba55..84eaa63a4ef 100644 --- a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/realm/ApiKeyCredentialsConverterTest.java +++ b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/realm/ApiKeyCredentialsConverterTest.java @@ -16,7 +16,6 @@ import org.eclipse.kapua.service.authentication.ApiKeyCredentials; import org.eclipse.kapua.service.authentication.exception.KapuaAuthenticationException; import org.eclipse.kapua.service.authentication.shiro.ApiKeyCredentialsImpl; -import org.eclipse.kapua.service.authentication.shiro.realm.model.ApiKeyCredentialsAnotherImpl; import org.eclipse.kapua.service.authentication.shiro.realm.model.NotProcessableCredentials; import org.eclipse.kapua.service.authentication.shiro.realm.model.NotProcessableCredentialsImpl; import org.junit.Assert; @@ -41,32 +40,20 @@ public void apoKeyCredentialsImplCanProcessNullTest() { @Test public void apoKeyCredentialsImplCanProcessImplTest() throws KapuaAuthenticationException { - ApiKeyCredentials apoKeyCredentialsImpl = new ApiKeyCredentialsImpl("anApiKey"); - ApiKeyCredentials apoKeyCredentialsAnother = new ApiKeyCredentialsAnotherImpl("anApiKey"); + ApiKeyCredentials apoKeyCredentials = new ApiKeyCredentials("anApiKey"); NotProcessableCredentials notProcessableCredentials = new NotProcessableCredentialsImpl(); - Assert.assertTrue(instance.canProcess(apoKeyCredentialsImpl)); - Assert.assertTrue(instance.canProcess(apoKeyCredentialsAnother)); + Assert.assertTrue(instance.canProcess(apoKeyCredentials)); Assert.assertFalse(instance.canProcess(notProcessableCredentials)); } @Test public void apiKeyCredentialsImplMapToShiroImplTest() throws KapuaAuthenticationException { - ApiKeyCredentials first = new ApiKeyCredentialsImpl("anApiKey"); + ApiKeyCredentials first = new ApiKeyCredentials("anApiKey"); ApiKeyCredentialsImpl second = (ApiKeyCredentialsImpl) instance.convertToShiro(first); - Assert.assertEquals(first, second); - Assert.assertEquals(first.getApiKey(), second.getApiKey()); - } - - @Test - public void apiKeyCredentialsImplMapToShiroAnotherTest() throws KapuaAuthenticationException { - ApiKeyCredentials first = new ApiKeyCredentialsAnotherImpl("anApiKey"); - - ApiKeyCredentialsImpl second = (ApiKeyCredentialsImpl) instance.convertToShiro(first); - - Assert.assertNotNull(second); + Assert.assertNotEquals(first, second); Assert.assertNotEquals(first, second); Assert.assertEquals(first.getApiKey(), second.getApiKey()); } @@ -78,7 +65,7 @@ public void apiKeyCredentialsImplMapToShiroNullTest() throws KapuaAuthentication @Test(expected = KapuaAuthenticationException.class) public void apiKeyCredentialsImplMapToShiroEmptyTest() throws KapuaAuthenticationException { - ApiKeyCredentialsImpl first = new ApiKeyCredentialsImpl((String) null); + ApiKeyCredentials first = new ApiKeyCredentials((String) null); Assert.assertNotNull(first); diff --git a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/realm/JwtCredentialsConverterTest.java b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/realm/JwtCredentialsConverterTest.java index 78a970280d3..028c684f587 100644 --- a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/realm/JwtCredentialsConverterTest.java +++ b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/realm/JwtCredentialsConverterTest.java @@ -16,7 +16,6 @@ import org.eclipse.kapua.service.authentication.JwtCredentials; import org.eclipse.kapua.service.authentication.exception.KapuaAuthenticationException; import org.eclipse.kapua.service.authentication.shiro.JwtCredentialsImpl; -import org.eclipse.kapua.service.authentication.shiro.realm.model.JwtCredentialsAnotherImpl; import org.eclipse.kapua.service.authentication.shiro.realm.model.NotProcessableCredentials; import org.eclipse.kapua.service.authentication.shiro.realm.model.NotProcessableCredentialsImpl; import org.junit.Assert; @@ -41,34 +40,21 @@ public void jwtCredentialsImplCanProcessNullTest() { @Test public void jwtCredentialsImplCanProcessImplTest() throws KapuaAuthenticationException { - JwtCredentials jwtCredentialsImpl = new JwtCredentialsImpl("aJwt", "anIdToken"); - JwtCredentials jwtCredentialsAnother = new JwtCredentialsAnotherImpl("aJwt", "anIdToken"); + JwtCredentials jwtCredentialsImpl = new JwtCredentials("aJwt", "anIdToken"); NotProcessableCredentials notProcessableCredentials = new NotProcessableCredentialsImpl(); Assert.assertTrue(instance.canProcess(jwtCredentialsImpl)); - Assert.assertTrue(instance.canProcess(jwtCredentialsAnother)); Assert.assertFalse(instance.canProcess(notProcessableCredentials)); } @Test public void jwtCredentialsImplMapToShiroImplTest() throws KapuaAuthenticationException { - JwtCredentialsImpl first = new JwtCredentialsImpl("aJwt", "anIdToken"); - - JwtCredentialsImpl second = (JwtCredentialsImpl) instance.convertToShiro(first); - - Assert.assertNotNull(second); - Assert.assertEquals(first, second); - Assert.assertEquals(first.getAccessToken(), second.getAccessToken()); - Assert.assertEquals(first.getIdToken(), second.getIdToken()); - } - - @Test - public void jwtCredentialsImplMapToShiroAnotherTest() throws KapuaAuthenticationException { - JwtCredentials first = new JwtCredentialsAnotherImpl("aJwt", "anIdToken"); + JwtCredentials first = new JwtCredentials("aJwt", "anIdToken"); JwtCredentialsImpl second = (JwtCredentialsImpl) instance.convertToShiro(first); Assert.assertNotNull(second); + Assert.assertNotEquals(first, second); Assert.assertEquals(first.getAccessToken(), second.getAccessToken()); Assert.assertEquals(first.getIdToken(), second.getIdToken()); } @@ -80,7 +66,7 @@ public void jwtCredentialsImplMapToShiroNullTest() throws KapuaAuthenticationExc @Test(expected = KapuaAuthenticationException.class) public void jwtCredentialsImplMapToShiroEmptyTest() throws KapuaAuthenticationException { - JwtCredentialsImpl first = new JwtCredentialsImpl(null, null); + JwtCredentials first = new JwtCredentials(null, null); Assert.assertNotNull(first); diff --git a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/realm/UserPassCredentialsConverterTest.java b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/realm/UserPassCredentialsConverterTest.java index 06334966f3a..12d76103397 100644 --- a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/realm/UserPassCredentialsConverterTest.java +++ b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/realm/UserPassCredentialsConverterTest.java @@ -18,7 +18,6 @@ import org.eclipse.kapua.service.authentication.shiro.UsernamePasswordCredentialsImpl; import org.eclipse.kapua.service.authentication.shiro.realm.model.NotProcessableCredentials; import org.eclipse.kapua.service.authentication.shiro.realm.model.NotProcessableCredentialsImpl; -import org.eclipse.kapua.service.authentication.shiro.realm.model.UsernamePasswordCredentialsAnotherImpl; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -41,18 +40,16 @@ public void usernamePasswordCredentialsImplCanProcessNullTest() { @Test public void usernamePasswordCredentialsImplCanProcessImplTest() throws KapuaAuthenticationException { - UsernamePasswordCredentials usernamePasswordCredentialsImpl = new UsernamePasswordCredentialsImpl("aUsernamePassword", "anIdToken"); - UsernamePasswordCredentials usernamePasswordCredentialsAnother = new UsernamePasswordCredentialsAnotherImpl("aUsernamePassword", "anIdToken"); + UsernamePasswordCredentials usernamePasswordCredentialsImpl = new UsernamePasswordCredentials("aUsernamePassword", "anIdToken"); NotProcessableCredentials notProcessableCredentials = new NotProcessableCredentialsImpl(); Assert.assertTrue(instance.canProcess(usernamePasswordCredentialsImpl)); - Assert.assertTrue(instance.canProcess(usernamePasswordCredentialsAnother)); Assert.assertFalse(instance.canProcess(notProcessableCredentials)); } @Test public void usernamePasswordCredentialsImplMapToShiroImplTest() throws KapuaAuthenticationException { - UsernamePasswordCredentialsImpl first = new UsernamePasswordCredentialsImpl("aUsername", "aPassword"); + UsernamePasswordCredentials first = new UsernamePasswordCredentials("aUsername", "aPassword"); first.setAuthenticationCode("123456"); first.setTrustKey("aTrustKey"); first.setTrustMe(true); @@ -60,17 +57,15 @@ public void usernamePasswordCredentialsImplMapToShiroImplTest() throws KapuaAuth UsernamePasswordCredentialsImpl second = (UsernamePasswordCredentialsImpl) instance.convertToShiro(first); Assert.assertNotNull(second); - Assert.assertEquals(first, second); + Assert.assertNotEquals(first, second); Assert.assertEquals(first.getUsername(), second.getUsername()); Assert.assertEquals(first.getPassword(), second.getPassword()); - Assert.assertEquals(first.getAuthenticationCode(), second.getAuthenticationCode()); - Assert.assertEquals(first.getTrustKey(), second.getTrustKey()); - Assert.assertEquals(first.getTrustMe(), second.getTrustMe()); + Assert.assertEquals(first.getAuthenticationCode(), first.getAuthenticationCode()); } @Test public void usernamePasswordCredentialsImplMapToShiroAnotherTest() throws KapuaAuthenticationException { - UsernamePasswordCredentials first = new UsernamePasswordCredentialsAnotherImpl("aAccessToken", "anIdToken"); + UsernamePasswordCredentials first = new UsernamePasswordCredentials("aAccessToken", "anIdToken"); first.setAuthenticationCode("123456"); first.setTrustKey("aTrustKey"); first.setTrustMe(true); @@ -81,9 +76,6 @@ public void usernamePasswordCredentialsImplMapToShiroAnotherTest() throws KapuaA Assert.assertNotEquals(first, second); Assert.assertEquals(first.getUsername(), second.getUsername()); Assert.assertEquals(first.getPassword(), second.getPassword()); - Assert.assertEquals(first.getAuthenticationCode(), second.getAuthenticationCode()); - Assert.assertEquals(first.getTrustKey(), second.getTrustKey()); - Assert.assertEquals(first.getTrustMe(), second.getTrustMe()); } @Test(expected = NullPointerException.class) @@ -93,7 +85,7 @@ public void usernamePasswordCredentialsImplMapToShiroNullTest() throws KapuaAuth @Test(expected = KapuaAuthenticationException.class) public void usernamePasswordCredentialsImplMapToShiroEmptyTest() throws KapuaAuthenticationException { - UsernamePasswordCredentialsImpl first = new UsernamePasswordCredentialsImpl(null, null); + UsernamePasswordCredentials first = new UsernamePasswordCredentials(null, null); Assert.assertNotNull(first); diff --git a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/realm/model/AccessTokenCredentialsAnotherImpl.java b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/realm/model/AccessTokenCredentialsAnotherImpl.java deleted file mode 100644 index f6e86d102c6..00000000000 --- a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/realm/model/AccessTokenCredentialsAnotherImpl.java +++ /dev/null @@ -1,33 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2023, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authentication.shiro.realm.model; - -import org.eclipse.kapua.service.authentication.AccessTokenCredentials; - -public class AccessTokenCredentialsAnotherImpl implements AccessTokenCredentials { - private String tokenId; - - public AccessTokenCredentialsAnotherImpl(String tokenId) { - setTokenId(tokenId); - } - - @Override - public String getTokenId() { - return tokenId; - } - - @Override - public void setTokenId(String tokenId) { - this.tokenId = tokenId; - } -} diff --git a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/realm/model/ApiKeyCredentialsAnotherImpl.java b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/realm/model/ApiKeyCredentialsAnotherImpl.java deleted file mode 100644 index b8a1eb587c5..00000000000 --- a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/realm/model/ApiKeyCredentialsAnotherImpl.java +++ /dev/null @@ -1,33 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2023, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authentication.shiro.realm.model; - -import org.eclipse.kapua.service.authentication.ApiKeyCredentials; - -public class ApiKeyCredentialsAnotherImpl implements ApiKeyCredentials { - private String apiKey; - - public ApiKeyCredentialsAnotherImpl(String apiKey) { - setApiKey(apiKey); - } - - @Override - public String getApiKey() { - return apiKey; - } - - @Override - public void setApiKey(String apiKey) { - this.apiKey = apiKey; - } -} diff --git a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/realm/model/JwtCredentialsAnotherImpl.java b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/realm/model/JwtCredentialsAnotherImpl.java deleted file mode 100644 index 6590e133940..00000000000 --- a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/realm/model/JwtCredentialsAnotherImpl.java +++ /dev/null @@ -1,45 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2023, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authentication.shiro.realm.model; - -import org.eclipse.kapua.service.authentication.JwtCredentials; - -public class JwtCredentialsAnotherImpl implements JwtCredentials { - private String accessToken; - private String idToken; - - public JwtCredentialsAnotherImpl(String accessToken, String idToken) { - setAccessToken(accessToken); - setIdToken(idToken); - } - - @Override - public String getAccessToken() { - return accessToken; - } - - @Override - public void setAccessToken(String accessToken) { - this.accessToken = accessToken; - } - - @Override - public String getIdToken() { - return idToken; - } - - @Override - public void setIdToken(String idToken) { - this.idToken = idToken; - } -} diff --git a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/realm/model/UsernamePasswordCredentialsAnotherImpl.java b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/realm/model/UsernamePasswordCredentialsAnotherImpl.java deleted file mode 100644 index edccceb3e4f..00000000000 --- a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/shiro/realm/model/UsernamePasswordCredentialsAnotherImpl.java +++ /dev/null @@ -1,79 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2023, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authentication.shiro.realm.model; - -import org.eclipse.kapua.service.authentication.UsernamePasswordCredentials; - -public class UsernamePasswordCredentialsAnotherImpl implements UsernamePasswordCredentials { - - private String username; - private String password; - private String authenticationCode; - private String trustKey; - private boolean trustMe; - - public UsernamePasswordCredentialsAnotherImpl(String username, String password) { - setUsername(username); - setPassword(password); - } - - @Override - public String getUsername() { - return username; - } - - @Override - public void setUsername(String username) { - this.username = username; - } - - @Override - public String getPassword() { - return password; - } - - @Override - public void setPassword(String password) { - this.password = password; - } - - @Override - public String getAuthenticationCode() { - return authenticationCode; - } - - @Override - public void setAuthenticationCode(String authenticationCode) { - this.authenticationCode = authenticationCode; - } - - @Override - public String getTrustKey() { - return trustKey; - } - - @Override - public void setTrustKey(String trustKey) { - this.trustKey = trustKey; - } - - @Override - public boolean getTrustMe() { - return trustMe; - } - - @Override - public void setTrustMe(boolean trustMe) { - this.trustMe = trustMe; - } -} diff --git a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/token/shiro/AccessTokenCreatorImplTest.java b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/token/shiro/AccessTokenCreatorImplTest.java index 0d73bf4acce..89bf430b696 100644 --- a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/token/shiro/AccessTokenCreatorImplTest.java +++ b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/token/shiro/AccessTokenCreatorImplTest.java @@ -12,87 +12,81 @@ *******************************************************************************/ package org.eclipse.kapua.service.authentication.token.shiro; +import java.util.Date; + import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.qa.markers.junit.JUnitTests; +import org.eclipse.kapua.service.authentication.token.AccessTokenCreator; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; -import java.util.Date; - - @Category(JUnitTests.class) public class AccessTokenCreatorImplTest { - AccessTokenCreatorImpl accessTokenCreatorImpl; + AccessTokenCreator accessTokenCreator; @Before public void initialize() { - accessTokenCreatorImpl = new AccessTokenCreatorImpl(KapuaId.ONE); + accessTokenCreator = new AccessTokenCreator(KapuaId.ONE); } @Test public void accessTokenCreatorImplTest() { - Assert.assertEquals("Expected and actual values should be the same.", KapuaId.ONE, accessTokenCreatorImpl.getScopeId()); - } - - @Test - public void accessTokenCreatorImplNullTest() { - AccessTokenCreatorImpl accessTokenCreatorImpl = new AccessTokenCreatorImpl(null); - Assert.assertNull("Null expected.", accessTokenCreatorImpl.getScopeId()); + Assert.assertEquals("Expected and actual values should be the same.", KapuaId.ONE, accessTokenCreator.getScopeId()); } @Test public void setAndGetTokenIdTest() { - String[] tokenIds = {null, "", "!!tokenID-1", "#1(TOKEN.,/token id)9--99", "!$$ 1-2 ID//", "id_tokeN(....)<00>"}; + String[] tokenIds = { null, "", "!!tokenID-1", "#1(TOKEN.,/token id)9--99", "!$$ 1-2 ID//", "id_tokeN(....)<00>" }; - Assert.assertNull("Null expected.", accessTokenCreatorImpl.getTokenId()); + Assert.assertNull("Null expected.", accessTokenCreator.getTokenId()); for (String tokenId : tokenIds) { - accessTokenCreatorImpl.setTokenId(tokenId); - Assert.assertEquals("Expected and actual values should be the same.", tokenId, accessTokenCreatorImpl.getTokenId()); + accessTokenCreator.setTokenId(tokenId); + Assert.assertEquals("Expected and actual values should be the same.", tokenId, accessTokenCreator.getTokenId()); } } @Test public void setAndGetUserIdTest() { - KapuaId[] userIds = {null, KapuaId.ONE}; + KapuaId[] userIds = { null, KapuaId.ONE }; - Assert.assertNull("Null expected.", accessTokenCreatorImpl.getUserId()); + Assert.assertNull("Null expected.", accessTokenCreator.getUserId()); for (KapuaId userId : userIds) { - accessTokenCreatorImpl.setUserId(userId); - Assert.assertEquals("Expected and actual values should be the same.", userId, accessTokenCreatorImpl.getUserId()); + accessTokenCreator.setUserId(userId); + Assert.assertEquals("Expected and actual values should be the same.", userId, accessTokenCreator.getUserId()); } } @Test public void setAndGetExpiresOnTest() { - Date[] expiresOnDates = {null, new Date(), new Date(1L), new Date(9999999999999L)}; - Assert.assertNull("Null expected.", accessTokenCreatorImpl.getExpiresOn()); + Date[] expiresOnDates = { null, new Date(), new Date(1L), new Date(9999999999999L) }; + Assert.assertNull("Null expected.", accessTokenCreator.getExpiresOn()); for (Date expiresOnDate : expiresOnDates) { - accessTokenCreatorImpl.setExpiresOn(expiresOnDate); - Assert.assertEquals("Expected and actual values should be the same.", expiresOnDate, accessTokenCreatorImpl.getExpiresOn()); + accessTokenCreator.setExpiresOn(expiresOnDate); + Assert.assertEquals("Expected and actual values should be the same.", expiresOnDate, accessTokenCreator.getExpiresOn()); } } @Test public void setAndGetRefreshTokenTest() { - String[] refreshTokens = {null, "", "!!refreshToken-1", "#1(TOKEN.,/refresh token id)9--99", "!$$ 1-2 REFREsh//", "refresh_tokeN(....)<00>"}; + String[] refreshTokens = { null, "", "!!refreshToken-1", "#1(TOKEN.,/refresh token id)9--99", "!$$ 1-2 REFREsh//", "refresh_tokeN(....)<00>" }; - Assert.assertNull("Null expected.", accessTokenCreatorImpl.getRefreshToken()); + Assert.assertNull("Null expected.", accessTokenCreator.getRefreshToken()); for (String refreshToken : refreshTokens) { - accessTokenCreatorImpl.setRefreshToken(refreshToken); - Assert.assertEquals("Expected and actual values should be the same.", refreshToken, accessTokenCreatorImpl.getRefreshToken()); + accessTokenCreator.setRefreshToken(refreshToken); + Assert.assertEquals("Expected and actual values should be the same.", refreshToken, accessTokenCreator.getRefreshToken()); } } @Test public void setAndGetRefreshExpiresOnTest() { - Date[] refreshExpiresOnDates = {null, new Date(), new Date(1L), new Date(9999999999999L)}; - Assert.assertNull("Null expected.", accessTokenCreatorImpl.getRefreshExpiresOn()); + Date[] refreshExpiresOnDates = { null, new Date(), new Date(1L), new Date(9999999999999L) }; + Assert.assertNull("Null expected.", accessTokenCreator.getRefreshExpiresOn()); for (Date refreshExpiresOnDate : refreshExpiresOnDates) { - accessTokenCreatorImpl.setRefreshExpiresOn(refreshExpiresOnDate); - Assert.assertEquals("Expected and actual values should be the same.", refreshExpiresOnDate, accessTokenCreatorImpl.getRefreshExpiresOn()); + accessTokenCreator.setRefreshExpiresOn(refreshExpiresOnDate); + Assert.assertEquals("Expected and actual values should be the same.", refreshExpiresOnDate, accessTokenCreator.getRefreshExpiresOn()); } } } \ No newline at end of file diff --git a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/token/shiro/AccessTokenFactoryImplTest.java b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/token/shiro/AccessTokenFactoryImplTest.java index d1659e85aca..2c0e1fe4e2d 100644 --- a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/token/shiro/AccessTokenFactoryImplTest.java +++ b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/token/shiro/AccessTokenFactoryImplTest.java @@ -12,24 +12,19 @@ *******************************************************************************/ package org.eclipse.kapua.service.authentication.token.shiro; +import java.util.Date; + import org.eclipse.kapua.KapuaEntityCloneException; import org.eclipse.kapua.commons.model.id.KapuaEid; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.qa.markers.junit.JUnitTests; import org.eclipse.kapua.service.authentication.token.AccessToken; -import org.eclipse.kapua.service.authentication.token.AccessTokenQuery; -import org.eclipse.kapua.service.authentication.token.LoginInfo; -import org.eclipse.kapua.service.authentication.token.AccessTokenListResult; -import org.eclipse.kapua.service.authentication.token.AccessTokenCreator; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.mockito.Mockito; -import java.util.Date; - - @Category(JUnitTests.class) public class AccessTokenFactoryImplTest { @@ -44,43 +39,17 @@ public class AccessTokenFactoryImplTest { @Before public void initialize() { accessTokenFactoryImpl = new AccessTokenFactoryImpl(); - scopeIds = new KapuaId[]{null, KapuaId.ONE}; - userIds = new KapuaEid[]{null, new KapuaEid()}; - tokenIds = new String[]{null, "", "!!token id-1", "#1(token.,/tokenID)9--99", "!$$ 1-2 id//", "to_ken_id(....)<00>"}; - refreshTokens = new String[]{null, "", "!!token refresh token-1", "#1(REfreSF.,/token_refresh)9--99", "!$$ 1-2 id//", "to_ken_refRESH token(....)<00>"}; - expiresOnDates = new Date[]{null, new Date()}; - refreshExpiresOnDates = new Date[]{null, new Date()}; + scopeIds = new KapuaId[] { null, KapuaId.ONE }; + userIds = new KapuaEid[] { null, new KapuaEid() }; + tokenIds = new String[] { null, "", "!!token id-1", "#1(token.,/tokenID)9--99", "!$$ 1-2 id//", "to_ken_id(....)<00>" }; + refreshTokens = new String[] { null, "", "!!token refresh token-1", "#1(REfreSF.,/token_refresh)9--99", "!$$ 1-2 id//", "to_ken_refRESH token(....)<00>" }; + expiresOnDates = new Date[] { null, new Date() }; + refreshExpiresOnDates = new Date[] { null, new Date() }; accessToken = Mockito.mock(AccessToken.class); modifiedOn = new Date(); createdOn = new Date(); invalidatedOn = new Date(); - tokenIdentifiers = new String[]{"a2fe104f-5d03-4a09-a28d-817ebbc85901", "8e075aeb-be2a-49a7-8dec-346760375d19", "e71b2f52-e02e-4e24-9147-96674e3bf599"}; - } - - @Test - public void newCreatorMultipleParametersTest() { - for (KapuaId scopeId : scopeIds) { - for (KapuaEid userId : userIds) { - for (String tokenId : tokenIds) { - for (Date expiresOnDate : expiresOnDates) { - for (String refreshToken : refreshTokens) { - for (Date refreshExpiresOnDate : refreshExpiresOnDates) { - for (String tokenIdenfier : tokenIdentifiers) { - AccessTokenCreatorImpl accessTokenCreatorImpl = accessTokenFactoryImpl.newCreator(scopeId, userId, tokenId, expiresOnDate, refreshToken, refreshExpiresOnDate, tokenIdenfier); - Assert.assertEquals("Expected and actual values should be the same.", scopeId, accessTokenCreatorImpl.getScopeId()); - Assert.assertEquals("Expected and actual values should be the same.", userId, accessTokenCreatorImpl.getUserId()); - Assert.assertEquals("Expected and actual values should be the same.", tokenId, accessTokenCreatorImpl.getTokenId()); - Assert.assertEquals("Expected and actual values should be the same.", expiresOnDate, accessTokenCreatorImpl.getExpiresOn()); - Assert.assertEquals("Expected and actual values should be the same.", refreshToken, accessTokenCreatorImpl.getRefreshToken()); - Assert.assertEquals("Expected and actual values should be the same.", refreshExpiresOnDate, accessTokenCreatorImpl.getRefreshExpiresOn()); - Assert.assertEquals("Expected and actual values should be the same.", tokenIdenfier, accessTokenCreatorImpl.getTokenIdentifier()); - } - } - } - } - } - } - } + tokenIdentifiers = new String[] { "a2fe104f-5d03-4a09-a28d-817ebbc85901", "8e075aeb-be2a-49a7-8dec-346760375d19", "e71b2f52-e02e-4e24-9147-96674e3bf599" }; } @Test @@ -91,27 +60,6 @@ public void newEntityTest() { } } - @Test - public void newCreatorScopeIdParameterTest() { - for (KapuaId scopeId : scopeIds) { - AccessTokenCreator accessTokenCreator = accessTokenFactoryImpl.newCreator(scopeId); - Assert.assertEquals("Expected and actual values should be the same.", scopeId, accessTokenCreator.getScopeId()); - } - } - - @Test - public void newQueryTest() { - for (KapuaId scopeId : scopeIds) { - AccessTokenQuery accessTokenQuery = accessTokenFactoryImpl.newQuery(scopeId); - Assert.assertEquals("Expected and actual values should be the same.", scopeId, accessTokenQuery.getScopeId()); - } - } - - @Test - public void newListResultTest() { - Assert.assertTrue("True expected.", accessTokenFactoryImpl.newListResult() instanceof AccessTokenListResult); - } - @Test public void cloneTest() { Mockito.when(accessToken.getId()).thenReturn(KapuaId.ONE); @@ -148,9 +96,4 @@ public void cloneTest() { public void cloneNullTest() { accessTokenFactoryImpl.clone(null); } - - @Test - public void newLoginInfoTest() { - Assert.assertTrue("True expected.", accessTokenFactoryImpl.newLoginInfo() instanceof LoginInfo); - } } \ No newline at end of file diff --git a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/token/shiro/AccessTokenQueryImplTest.java b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/token/shiro/AccessTokenQueryImplTest.java deleted file mode 100644 index 1bb5a584d51..00000000000 --- a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authentication/token/shiro/AccessTokenQueryImplTest.java +++ /dev/null @@ -1,47 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authentication.token.shiro; - -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.qa.markers.junit.JUnitTests; -import org.junit.Assert; -import org.junit.Test; -import org.junit.experimental.categories.Category; - -import java.lang.reflect.Constructor; -import java.lang.reflect.Modifier; - - -@Category(JUnitTests.class) -public class AccessTokenQueryImplTest { - - @Test - public void accessTokenQueryImplTest() throws Exception { - Constructor accessTokenQueryImpl = AccessTokenQueryImpl.class.getDeclaredConstructor(); - accessTokenQueryImpl.setAccessible(true); - accessTokenQueryImpl.newInstance(); - Assert.assertTrue("True expected.", Modifier.isPrivate(accessTokenQueryImpl.getModifiers())); - } - - @Test - public void accessTokenQueryImplTestScopeIdParameterTest() { - AccessTokenQueryImpl accessTokenQueryImpl = new AccessTokenQueryImpl(KapuaId.ONE); - Assert.assertEquals("Expected and actual values should be the same.", KapuaId.ONE, accessTokenQueryImpl.getScopeId()); - } - - @Test - public void accessTokenQueryImplTestNullScopeIdParameterTest() { - AccessTokenQueryImpl accessTokenQueryImpl = new AccessTokenQueryImpl(null); - Assert.assertNull("Null expected.", accessTokenQueryImpl.getScopeId()); - } -} \ No newline at end of file diff --git a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/access/shiro/AccessInfoFactoryImplTest.java b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/access/shiro/AccessInfoFactoryImplTest.java index 2ce26e553a5..6190dfb73d4 100644 --- a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/access/shiro/AccessInfoFactoryImplTest.java +++ b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/access/shiro/AccessInfoFactoryImplTest.java @@ -12,30 +12,26 @@ *******************************************************************************/ package org.eclipse.kapua.service.authorization.access.shiro; +import java.util.Date; + import org.eclipse.kapua.KapuaEntityCloneException; import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.qa.markers.junit.JUnitTests; import org.eclipse.kapua.service.authorization.access.AccessInfo; -import org.eclipse.kapua.service.authorization.access.AccessInfoCreator; -import org.eclipse.kapua.service.authorization.access.AccessInfoListResult; -import org.eclipse.kapua.service.authorization.access.AccessInfoQuery; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.mockito.Mockito; -import java.util.Date; - - @Category(JUnitTests.class) public class AccessInfoFactoryImplTest { AccessInfoFactoryImpl accessInfoFactoryImpl; KapuaId scopeId; AccessInfo accessInfo; - Date createdOn,modifiedOn; - + Date createdOn, modifiedOn; @Before public void initialize() { @@ -69,41 +65,20 @@ public void newEntityNullTest() { Assert.assertNull("Null expected.", accessInfo.getScopeId()); } - @Test - public void newCreatorTest() { - AccessInfoCreator accessInfoCreator = accessInfoFactoryImpl.newCreator(scopeId); - - Assert.assertEquals("Expected and actual values should be the same.", scopeId, accessInfoCreator.getScopeId()); - } - - @Test - public void newCreatorNullTest() { - AccessInfoCreator accessInfoCreator = accessInfoFactoryImpl.newCreator(null); - - Assert.assertNull("Null expected.", accessInfoCreator.getScopeId()); - } - @Test public void newQueryTest() { - AccessInfoQuery accessInfoQuery = accessInfoFactoryImpl.newQuery(scopeId); + KapuaQuery accessInfoQuery = new KapuaQuery(scopeId); Assert.assertEquals("Expected and actual values should be the same.", scopeId, accessInfoQuery.getScopeId()); } @Test public void newQueryNullTest() { - AccessInfoQuery accessInfoQuery = accessInfoFactoryImpl.newQuery(null); + KapuaQuery accessInfoQuery = new KapuaQuery((KapuaId) null); Assert.assertNull("Null expected.", accessInfoQuery.getScopeId()); } - @Test - public void newListResultTest() { - AccessInfoListResult accessInfoListResult = accessInfoFactoryImpl.newListResult(); - - Assert.assertTrue("True expected.", accessInfoListResult.isEmpty()); - } - @Test public void cloneTest() { AccessInfo resultAccessInfo = accessInfoFactoryImpl.clone(accessInfo); diff --git a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/access/shiro/AccessInfoQueryImplTest.java b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/access/shiro/AccessInfoQueryImplTest.java deleted file mode 100644 index 30be73ea269..00000000000 --- a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/access/shiro/AccessInfoQueryImplTest.java +++ /dev/null @@ -1,45 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authorization.access.shiro; - -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.qa.markers.junit.JUnitTests; -import org.junit.Assert; -import org.junit.Test; -import org.junit.experimental.categories.Category; - - -@Category(JUnitTests.class) -public class AccessInfoQueryImplTest { - - @Test - public void accessInfoQueryImplWithoutParameterTest() { - AccessInfoQueryImpl accessInfoQueryImpl = new AccessInfoQueryImpl(); - - Assert.assertNull("Null expected.", accessInfoQueryImpl.getScopeId()); - } - - @Test - public void accessInfoQueryImplScopeIdParameterTest() { - AccessInfoQueryImpl accessInfoQueryImpl = new AccessInfoQueryImpl(KapuaId.ONE); - - Assert.assertEquals("Expected and actual values should be the same.", KapuaId.ONE, accessInfoQueryImpl.getScopeId()); - } - - @Test - public void accessInfoQueryImplNullScopeIdParameterTest() { - AccessInfoQueryImpl accessInfoQueryImpl = new AccessInfoQueryImpl(null); - - Assert.assertNull("Null expected.", accessInfoQueryImpl.getScopeId()); - } -} \ No newline at end of file diff --git a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/access/shiro/AccessPermissionCreatorImplTest.java b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/access/shiro/AccessPermissionCreatorTest.java similarity index 81% rename from service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/access/shiro/AccessPermissionCreatorImplTest.java rename to service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/access/shiro/AccessPermissionCreatorTest.java index 725ffc74ff2..f82926f7b65 100644 --- a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/access/shiro/AccessPermissionCreatorImplTest.java +++ b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/access/shiro/AccessPermissionCreatorTest.java @@ -14,31 +14,31 @@ import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.qa.markers.junit.JUnitTests; +import org.eclipse.kapua.service.authorization.access.AccessPermissionCreator; import org.eclipse.kapua.service.authorization.permission.Permission; import org.junit.Assert; import org.junit.Test; import org.junit.experimental.categories.Category; import org.mockito.Mockito; - @Category(JUnitTests.class) -public class AccessPermissionCreatorImplTest { +public class AccessPermissionCreatorTest { @Test public void accessPermissionCreatorImplTest() { - AccessPermissionCreatorImpl accessPermissionCreatorImpl = new AccessPermissionCreatorImpl(KapuaId.ONE); + AccessPermissionCreator accessPermissionCreatorImpl = new AccessPermissionCreator(KapuaId.ONE); Assert.assertEquals("Expected and actual values should be the same.", KapuaId.ONE, accessPermissionCreatorImpl.getScopeId()); } @Test public void accessPermissionCreatorImplNullTest() { - AccessPermissionCreatorImpl accessPermissionCreatorImpl = new AccessPermissionCreatorImpl(null); + AccessPermissionCreator accessPermissionCreatorImpl = new AccessPermissionCreator(null); Assert.assertNull("Null expected.", accessPermissionCreatorImpl.getScopeId()); } @Test public void setAndGetAccessInfoIdTest() { - AccessPermissionCreatorImpl accessPermissionCreatorImpl = new AccessPermissionCreatorImpl(KapuaId.ONE); + AccessPermissionCreator accessPermissionCreatorImpl = new AccessPermissionCreator(KapuaId.ONE); Assert.assertNull("Null expected.", accessPermissionCreatorImpl.getAccessInfoId()); accessPermissionCreatorImpl.setAccessInfoId(KapuaId.ONE); @@ -49,7 +49,7 @@ public void setAndGetAccessInfoIdTest() { @Test public void setAndGetPermissionTest() { - AccessPermissionCreatorImpl accessPermissionCreatorImpl = new AccessPermissionCreatorImpl(KapuaId.ONE); + AccessPermissionCreator accessPermissionCreatorImpl = new AccessPermissionCreator(KapuaId.ONE); Permission permission = Mockito.mock(Permission.class); Assert.assertNull("Null expected.", accessPermissionCreatorImpl.getPermission()); diff --git a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/access/shiro/AccessPermissionFactoryImplTest.java b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/access/shiro/AccessPermissionFactoryImplTest.java index a7654bd3539..4682d028eb9 100644 --- a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/access/shiro/AccessPermissionFactoryImplTest.java +++ b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/access/shiro/AccessPermissionFactoryImplTest.java @@ -15,16 +15,12 @@ import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.qa.markers.junit.JUnitTests; import org.eclipse.kapua.service.authorization.access.AccessPermission; -import org.eclipse.kapua.service.authorization.access.AccessPermissionCreator; -import org.eclipse.kapua.service.authorization.access.AccessPermissionListResult; -import org.eclipse.kapua.service.authorization.access.AccessPermissionQuery; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.mockito.Mockito; - @Category(JUnitTests.class) public class AccessPermissionFactoryImplTest { @@ -34,7 +30,7 @@ public class AccessPermissionFactoryImplTest { @Before public void initialize() { accessPermissionFactoryImpl = new AccessPermissionFactoryImpl(); - scopeIds = new KapuaId[]{null, KapuaId.ONE}; + scopeIds = new KapuaId[] { null, KapuaId.ONE }; } @Test @@ -44,25 +40,6 @@ public void newEntityTest() { } } - @Test - public void newCreatorTest() { - for (KapuaId scopeId : scopeIds) { - Assert.assertTrue("True expected.", accessPermissionFactoryImpl.newCreator(scopeId) instanceof AccessPermissionCreator); - } - } - - @Test - public void newQueryTest() { - for (KapuaId scopeId : scopeIds) { - Assert.assertTrue("True expected.", accessPermissionFactoryImpl.newQuery(scopeId) instanceof AccessPermissionQuery); - } - } - - @Test - public void newListResultTest() { - Assert.assertTrue("True expected.", accessPermissionFactoryImpl.newListResult() instanceof AccessPermissionListResult); - } - @Test public void cloneTest() { AccessPermission accessPermission = Mockito.mock(AccessPermission.class); diff --git a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/access/shiro/AccessPermissionQueryImplTest.java b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/access/shiro/AccessPermissionQueryImplTest.java deleted file mode 100644 index ee1fb61f155..00000000000 --- a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/access/shiro/AccessPermissionQueryImplTest.java +++ /dev/null @@ -1,48 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authorization.access.shiro; - -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.qa.markers.junit.JUnitTests; -import org.junit.Assert; -import org.junit.Test; -import org.junit.experimental.categories.Category; - - -@Category(JUnitTests.class) -public class AccessPermissionQueryImplTest { - - @Test - public void accessPermissionQueryImplWithoutParametersTest() { - AccessPermissionQueryImpl accessPermissionQueryImpl = new AccessPermissionQueryImpl(); - Assert.assertNull("Null expected.", accessPermissionQueryImpl.getScopeId()); - Assert.assertNull("accessPermissionQueryImpl.sortCriteria", accessPermissionQueryImpl.getSortCriteria()); - Assert.assertNotNull("accessPermissionQueryImpl.defaultSortCriteria", accessPermissionQueryImpl.getDefaultSortCriteria()); - } - - @Test - public void accessPermissionQueryImplScopeIdParameterTest() { - AccessPermissionQueryImpl accessPermissionQueryImpl = new AccessPermissionQueryImpl(KapuaId.ONE); - Assert.assertEquals("Expected and actual values should be the same.", KapuaId.ONE, accessPermissionQueryImpl.getScopeId()); - Assert.assertNull("accessPermissionQueryImpl.sortCriteria", accessPermissionQueryImpl.getSortCriteria()); - Assert.assertNotNull("accessPermissionQueryImpl.defaultSortCriteria", accessPermissionQueryImpl.getDefaultSortCriteria()); - } - - @Test - public void accessPermissionQueryImplNullScopeIdParameterTest() { - AccessPermissionQueryImpl accessPermissionQueryImpl = new AccessPermissionQueryImpl(null); - Assert.assertNull("Null expected.", accessPermissionQueryImpl.getScopeId()); - Assert.assertNull("accessPermissionQueryImpl.sortCriteria", accessPermissionQueryImpl.getSortCriteria()); - Assert.assertNotNull("accessPermissionQueryImpl.defaultSortCriteria", accessPermissionQueryImpl.getDefaultSortCriteria()); - } -} \ No newline at end of file diff --git a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/access/shiro/AccessRoleCreatorImplTest.java b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/access/shiro/AccessRoleCreatorTest.java similarity index 88% rename from service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/access/shiro/AccessRoleCreatorImplTest.java rename to service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/access/shiro/AccessRoleCreatorTest.java index 99538c02f5c..bd33c02a18a 100644 --- a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/access/shiro/AccessRoleCreatorImplTest.java +++ b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/access/shiro/AccessRoleCreatorTest.java @@ -14,6 +14,7 @@ import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.qa.markers.junit.JUnitTests; +import org.eclipse.kapua.service.authorization.access.AccessRoleCreator; import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -21,13 +22,13 @@ @Category(JUnitTests.class) -public class AccessRoleCreatorImplTest { +public class AccessRoleCreatorTest { - AccessRoleCreatorImpl accessRoleCreatorImpl; + AccessRoleCreator accessRoleCreatorImpl; @Before public void initialize() { - accessRoleCreatorImpl = new AccessRoleCreatorImpl(KapuaId.ONE); + accessRoleCreatorImpl = new AccessRoleCreator(KapuaId.ONE); } @Test @@ -39,7 +40,7 @@ public void accessRoleCreatorImplTest() { @Test public void accessRoleCreatorImplNullTest() { - AccessRoleCreatorImpl accessRoleCreatorImplNullId = new AccessRoleCreatorImpl(null); + AccessRoleCreator accessRoleCreatorImplNullId = new AccessRoleCreator(null); Assert.assertNull("Null expected.", accessRoleCreatorImplNullId.getScopeId()); Assert.assertNull("Null expected.", accessRoleCreatorImplNullId.getAccessInfoId()); Assert.assertNull("Null expected.", accessRoleCreatorImplNullId.getRoleId()); diff --git a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/access/shiro/AccessRoleFactoryImplTest.java b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/access/shiro/AccessRoleFactoryImplTest.java index 2e6eea3848f..46dbf1f62a7 100644 --- a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/access/shiro/AccessRoleFactoryImplTest.java +++ b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/access/shiro/AccessRoleFactoryImplTest.java @@ -12,22 +12,19 @@ *******************************************************************************/ package org.eclipse.kapua.service.authorization.access.shiro; +import java.util.Date; + import org.eclipse.kapua.KapuaEntityCloneException; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.qa.markers.junit.JUnitTests; import org.eclipse.kapua.service.authorization.access.AccessRole; import org.eclipse.kapua.service.authorization.access.AccessRoleCreator; -import org.eclipse.kapua.service.authorization.access.AccessRoleListResult; -import org.eclipse.kapua.service.authorization.access.AccessRoleQuery; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.mockito.Mockito; -import java.util.Date; - - @Category(JUnitTests.class) public class AccessRoleFactoryImplTest { @@ -63,34 +60,16 @@ public void newEntityNullTest() { @Test public void newCreatorTest() { - AccessRoleCreator accessRoleCreator = accessRoleFactoryImpl.newCreator(KapuaId.ONE); + AccessRoleCreator accessRoleCreator = new AccessRoleCreator(KapuaId.ONE); Assert.assertEquals("Expected and actual values should be the same.", KapuaId.ONE, accessRoleCreator.getScopeId()); } @Test public void newCreatorNullTest() { - AccessRoleCreator accessRoleCreator = accessRoleFactoryImpl.newCreator(null); + AccessRoleCreator accessRoleCreator = new AccessRoleCreator(null); Assert.assertNull("Null expected.", accessRoleCreator.getScopeId()); } - @Test - public void newQueryTest() { - AccessRoleQuery accessRoleQuery = accessRoleFactoryImpl.newQuery(KapuaId.ONE); - Assert.assertEquals("Expected and actual values should be the same.", KapuaId.ONE, accessRoleQuery.getScopeId()); - } - - @Test - public void newQueryNullTest() { - AccessRoleQuery accessRoleQuery = accessRoleFactoryImpl.newQuery(null); - Assert.assertNull("Null expected.", accessRoleQuery.getScopeId()); - } - - @Test - public void newListResultTest() { - AccessRoleListResult accessRoleListResult = accessRoleFactoryImpl.newListResult(); - Assert.assertTrue("True expected.", accessRoleListResult.isEmpty()); - } - @Test public void cloneTest() { accessRoleFactoryImpl.clone(accessRole); diff --git a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/access/shiro/AccessRoleQueryImplTest.java b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/access/shiro/AccessRoleQueryImplTest.java deleted file mode 100644 index 4f6601d333e..00000000000 --- a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/access/shiro/AccessRoleQueryImplTest.java +++ /dev/null @@ -1,40 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authorization.access.shiro; - -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.qa.markers.junit.JUnitTests; -import org.junit.Assert; -import org.junit.Test; -import org.junit.experimental.categories.Category; - - -@Category(JUnitTests.class) -public class AccessRoleQueryImplTest { - - @Test - public void accessRoleQueryImplWithoutParametersTest() { - AccessRoleQueryImpl accessRoleQueryImpl = new AccessRoleQueryImpl(); - Assert.assertNull("Null expected.", accessRoleQueryImpl.getScopeId()); - Assert.assertNull("accessRoleQueryImpl.sortCriteria", accessRoleQueryImpl.getSortCriteria()); - Assert.assertNotNull("accessRoleQueryImpl.defaultSortCriteria", accessRoleQueryImpl.getDefaultSortCriteria()); - } - - @Test - public void accessRoleQueryImplScopeIdParameterTest() { - AccessRoleQueryImpl accessRoleQueryImpl = new AccessRoleQueryImpl(KapuaId.ONE); - Assert.assertEquals("Expected and actual values should be the same.", KapuaId.ONE, accessRoleQueryImpl.getScopeId()); - Assert.assertNull("accessRoleQueryImpl.sortCriteria", accessRoleQueryImpl.getSortCriteria()); - Assert.assertNotNull("accessRoleQueryImpl.defaultSortCriteria", accessRoleQueryImpl.getDefaultSortCriteria()); - } -} \ No newline at end of file diff --git a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/domain/shiro/DomainCreatorImplTest.java b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/domain/shiro/DomainCreatorTest.java similarity index 74% rename from service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/domain/shiro/DomainCreatorImplTest.java rename to service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/domain/shiro/DomainCreatorTest.java index 742a29aaf85..66274b69092 100644 --- a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/domain/shiro/DomainCreatorImplTest.java +++ b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/domain/shiro/DomainCreatorTest.java @@ -12,25 +12,27 @@ *******************************************************************************/ package org.eclipse.kapua.service.authorization.domain.shiro; +import java.util.HashSet; +import java.util.Set; + import org.eclipse.kapua.model.domain.Actions; +import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.qa.markers.junit.JUnitTests; +import org.eclipse.kapua.service.authorization.domain.DomainCreator; import org.junit.Assert; import org.junit.Test; import org.junit.experimental.categories.Category; -import java.util.HashSet; -import java.util.Set; - - @Category(JUnitTests.class) -public class DomainCreatorImplTest { +public class DomainCreatorTest { @Test public void domainCreatorImplTest() { - String[] names = {"", " na123)(&*^&NAME <>", "Na-,,..,,Me name ---", "-&^454536 na___,,12 NAME name ", "! 2#@ na meNEMA 2323", "12&^%4 ,,,. '|<>*(", " ,,123name;;'", "12#name--765 ,.aaa!!#$%^<> "}; + String[] names = { "", " na123)(&*^&NAME <>", "Na-,,..,,Me name ---", "-&^454536 na___,,12 NAME name ", "! 2#@ na meNEMA 2323", "12&^%4 ,,,. '|<>*(", " ,,123name;;'", + "12#name--765 ,.aaa!!#$%^<> " }; for (String name : names) { - DomainCreatorImpl domainCreatorImpl = new DomainCreatorImpl(name); + DomainCreator domainCreatorImpl = new DomainCreator(name); Assert.assertNull("Null expected.", domainCreatorImpl.getScopeId()); Assert.assertEquals("Expected and actual values should be the same.", name, domainCreatorImpl.getName()); Assert.assertNull("Null expected.", domainCreatorImpl.getActions()); @@ -40,7 +42,7 @@ public void domainCreatorImplTest() { @Test public void domainCreatorImplNullTest() { - DomainCreatorImpl domainCreatorImpl = new DomainCreatorImpl(null); + DomainCreator domainCreatorImpl = new DomainCreator((KapuaId) null); Assert.assertNull("Null expected.", domainCreatorImpl.getScopeId()); Assert.assertNull("Null expected.", domainCreatorImpl.getName()); Assert.assertNull("Null expected.", domainCreatorImpl.getActions()); @@ -49,9 +51,10 @@ public void domainCreatorImplNullTest() { @Test public void setAndGetNameTest() { - String[] newNames = {"", " na123)(&*^&NAME NEWname <>", "newNa-,,..,,Me name NEW NEW---", "-&^454536 na___,,12 NAME New name ", "! 2#@ na meNewNAME 23NeW23", "12&^%4 ,,,. '|*(", " ,,123name;;'", "12#name-new-name765 ,.aaa!!#$%^<> "}; + String[] newNames = { "", " na123)(&*^&NAME NEWname <>", "newNa-,,..,,Me name NEW NEW---", "-&^454536 na___,,12 NAME New name ", "! 2#@ na meNewNAME 23NeW23", + "12&^%4 ,,,. '|*(", " ,,123name;;'", "12#name-new-name765 ,.aaa!!#$%^<> " }; - DomainCreatorImpl domainCreatorImpl = new DomainCreatorImpl("name"); + DomainCreator domainCreatorImpl = new DomainCreator("name"); for (String newName : newNames) { domainCreatorImpl.setName(newName); Assert.assertEquals("Expected and actual values should be the same.", newName, domainCreatorImpl.getName()); @@ -63,7 +66,7 @@ public void setAndGetNameTest() { @Test public void setAndGetActionsTest() { Set actions = new HashSet<>(); - DomainCreatorImpl domainCreatorImpl = new DomainCreatorImpl("name"); + DomainCreator domainCreatorImpl = new DomainCreator("name"); domainCreatorImpl.setActions(actions); Assert.assertTrue("True expected", domainCreatorImpl.getActions().isEmpty()); @@ -82,8 +85,8 @@ public void setAndGetActionsTest() { @Test public void setAndGetGroupableTest() { - boolean[] groupables = {true, false}; - DomainCreatorImpl domainCreatorImpl = new DomainCreatorImpl("name"); + boolean[] groupables = { true, false }; + DomainCreator domainCreatorImpl = new DomainCreator("name"); for (boolean groupable : groupables) { domainCreatorImpl.setGroupable(groupable); diff --git a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/domain/shiro/DomainFactoryImplTest.java b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/domain/shiro/DomainFactoryImplTest.java index 6399442db7a..12b6afce9ab 100644 --- a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/domain/shiro/DomainFactoryImplTest.java +++ b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/domain/shiro/DomainFactoryImplTest.java @@ -12,25 +12,20 @@ *******************************************************************************/ package org.eclipse.kapua.service.authorization.domain.shiro; -import org.apache.commons.lang.NotImplementedException; +import java.util.Date; +import java.util.HashSet; +import java.util.Set; + import org.eclipse.kapua.model.domain.Actions; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.qa.markers.junit.JUnitTests; import org.eclipse.kapua.service.authorization.domain.Domain; -import org.eclipse.kapua.service.authorization.domain.DomainCreator; -import org.eclipse.kapua.service.authorization.domain.DomainListResult; -import org.eclipse.kapua.service.authorization.domain.DomainQuery; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.mockito.Mockito; -import java.util.Date; -import java.util.HashSet; -import java.util.Set; - - @Category(JUnitTests.class) public class DomainFactoryImplTest { @@ -41,46 +36,6 @@ public void initialize() { domainFactoryImpl = new DomainFactoryImpl(); } - @Test - public void newCreatorNameParameterTest() { - String[] names = {"", " na123)(&*^&NAME <>", "Na-,,..,,Me name ---", "-&^454536 na___,,12 NAME name ", "! 2#@ na meNEMA 2323", "12&^%4 ,,,. '|<>*(", " ,,123name;;'", "12#name--765 ,.aaa!!#$%^<> "}; - - for (String name : names) { - DomainCreator domainCreator = domainFactoryImpl.newCreator(name); - Assert.assertEquals("Expected and actual values should be the same.", name, domainCreator.getName()); - Assert.assertNull("Null expected.", domainCreator.getScopeId()); - } - } - - @Test - public void newCreatorNullNameParameterTest() { - DomainCreator domainCreator = domainFactoryImpl.newCreator((String) null); - Assert.assertNull("Null expected.", domainCreator.getName()); - Assert.assertNull("Null expected.", domainCreator.getScopeId()); - } - - @Test - public void newListResultTest() { - DomainListResult domainListResult = domainFactoryImpl.newListResult(); - Assert.assertTrue("True expected.", domainListResult.isEmpty()); - } - - @Test - public void newQueryTest() { - DomainQuery domainQuery = domainFactoryImpl.newQuery(KapuaId.ONE); - Assert.assertEquals("Expected and actual values should be the same.", KapuaId.ONE, domainQuery.getScopeId()); - Assert.assertNull("domainQuery.sortCriteria", domainQuery.getSortCriteria()); - Assert.assertNotNull("domainQuery.defaultSortCriteria", domainQuery.getDefaultSortCriteria()); - } - - @Test - public void newQueryNullTest() { - DomainQuery domainQuery = domainFactoryImpl.newQuery(null); - Assert.assertNull("Null expected.", domainQuery.getScopeId()); - Assert.assertNull("domainQuery.sortCriteria", domainQuery.getSortCriteria()); - Assert.assertNotNull("domainQuery.defaultSortCriteria", domainQuery.getDefaultSortCriteria()); - } - @Test public void newEntityTest() { Domain domain = domainFactoryImpl.newEntity(KapuaId.ONE); @@ -93,16 +48,6 @@ public void newEntityNullTest() { Assert.assertNull("Null expected.", domain.getScopeId()); } - @Test(expected = NotImplementedException.class) - public void newCreatorScopeIdParameterTest() { - domainFactoryImpl.newCreator(KapuaId.ONE); - } - - @Test(expected = NotImplementedException.class) - public void newCreatorNullScopeIdParameterTest() { - domainFactoryImpl.newCreator((KapuaId) null); - } - @Test public void cloneTest() { Domain domain = Mockito.mock(Domain.class); diff --git a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/domain/shiro/DomainQueryImplTest.java b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/domain/shiro/DomainQueryImplTest.java deleted file mode 100644 index e3be25cd1e3..00000000000 --- a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/domain/shiro/DomainQueryImplTest.java +++ /dev/null @@ -1,42 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authorization.domain.shiro; - -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.qa.markers.junit.JUnitTests; -import org.junit.Assert; -import org.junit.Test; -import org.junit.experimental.categories.Category; - - -@Category(JUnitTests.class) -public class DomainQueryImplTest { - - @Test - public void domainQueryImplWithoutParametersTest() { - DomainQueryImpl domainQueryImpl = new DomainQueryImpl(); - Assert.assertNull("Null expected.", domainQueryImpl.getScopeId()); - } - - @Test - public void domainQueryImplScopeIdParameterTest() { - DomainQueryImpl domainQueryImpl = new DomainQueryImpl(KapuaId.ONE); - Assert.assertEquals("Expected and actual values should be the same.", KapuaId.ONE, domainQueryImpl.getScopeId()); - } - - @Test - public void domainQueryImplNullScopeIdParameterTest() { - DomainQueryImpl domainQueryImpl = new DomainQueryImpl(null); - Assert.assertNull("Null expected.", domainQueryImpl.getScopeId()); - } -} \ No newline at end of file diff --git a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/group/shiro/GroupCreatorImplTest.java b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/group/shiro/GroupCreatorTest.java similarity index 77% rename from service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/group/shiro/GroupCreatorImplTest.java rename to service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/group/shiro/GroupCreatorTest.java index 56d52b01540..993f8f7e541 100644 --- a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/group/shiro/GroupCreatorImplTest.java +++ b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/group/shiro/GroupCreatorTest.java @@ -14,28 +14,29 @@ import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.qa.markers.junit.JUnitTests; +import org.eclipse.kapua.service.authorization.group.GroupCreator; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; - @Category(JUnitTests.class) -public class GroupCreatorImplTest { +public class GroupCreatorTest { String[] names; KapuaId scopeId; @Before public void initialize() { - names = new String[]{"", " na123)(&*^&NAME <>", "Na-,,..,,Me name ---", "-&^454536 na___,,12 NAME name ", "! 2#@ na meNEMA 2323", "12&^%4 ,,,. '|<>*(", " ,,123name;;'", "12#name--765 ,.aaa!!#$%^<> "}; + names = new String[] { "", " na123)(&*^&NAME <>", "Na-,,..,,Me name ---", "-&^454536 na___,,12 NAME name ", "! 2#@ na meNEMA 2323", "12&^%4 ,,,. '|<>*(", " ,,123name;;'", + "12#name--765 ,.aaa!!#$%^<> " }; scopeId = KapuaId.ONE; } @Test public void groupCreatorImplScopeIdNameParametersTest() { for (String name : names) { - GroupCreatorImpl groupCreatorImpl = new GroupCreatorImpl(scopeId, name); + GroupCreator groupCreatorImpl = new GroupCreator(scopeId, name); Assert.assertEquals("Expected and actual values should be the same.", scopeId, groupCreatorImpl.getScopeId()); Assert.assertEquals("Expected and actual values should be the same.", name, groupCreatorImpl.getName()); } @@ -44,7 +45,7 @@ public void groupCreatorImplScopeIdNameParametersTest() { @Test public void groupCreatorImplNullScopeIdNameParametersTest() { for (String name : names) { - GroupCreatorImpl groupCreatorImpl = new GroupCreatorImpl(null, name); + GroupCreator groupCreatorImpl = new GroupCreator(null, name); Assert.assertNull("Null expected.", groupCreatorImpl.getScopeId()); Assert.assertEquals("Expected and actual values should be the same.", name, groupCreatorImpl.getName()); } @@ -52,28 +53,28 @@ public void groupCreatorImplNullScopeIdNameParametersTest() { @Test public void groupCreatorImplScopeIdNullNameParametersTest() { - GroupCreatorImpl groupCreatorImpl = new GroupCreatorImpl(scopeId, null); + GroupCreator groupCreatorImpl = new GroupCreator(scopeId, null); Assert.assertEquals("Expected and actual values should be the same.", scopeId, groupCreatorImpl.getScopeId()); Assert.assertNull("Null expected.", groupCreatorImpl.getName()); } @Test public void groupCreatorImplNullScopeIdNullNameParametersTest() { - GroupCreatorImpl groupCreatorImpl = new GroupCreatorImpl(null, null); + GroupCreator groupCreatorImpl = new GroupCreator(null, null); Assert.assertNull("Null expected.", groupCreatorImpl.getScopeId()); Assert.assertNull("Null expected.", groupCreatorImpl.getName()); } @Test public void groupCreatorImplScopeIdParameterTest() { - GroupCreatorImpl groupCreatorImpl = new GroupCreatorImpl(scopeId); + GroupCreator groupCreatorImpl = new GroupCreator(scopeId); Assert.assertEquals("Expected and actual values should be the same.", scopeId, groupCreatorImpl.getScopeId()); Assert.assertNull("Null expected.", groupCreatorImpl.getName()); } @Test public void groupCreatorImplNullScopeIdParameterTest() { - GroupCreatorImpl groupCreatorImpl = new GroupCreatorImpl(null); + GroupCreator groupCreatorImpl = new GroupCreator(null); Assert.assertNull("Null expected.", groupCreatorImpl.getScopeId()); Assert.assertNull("Null expected.", groupCreatorImpl.getName()); } diff --git a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/group/shiro/GroupFactoryImplTest.java b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/group/shiro/GroupFactoryImplTest.java index 75badcb4e9c..aae6877d863 100644 --- a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/group/shiro/GroupFactoryImplTest.java +++ b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/group/shiro/GroupFactoryImplTest.java @@ -12,22 +12,19 @@ *******************************************************************************/ package org.eclipse.kapua.service.authorization.group.shiro; +import java.util.Date; + import org.eclipse.kapua.KapuaEntityCloneException; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.qa.markers.junit.JUnitTests; import org.eclipse.kapua.service.authorization.group.Group; import org.eclipse.kapua.service.authorization.group.GroupCreator; -import org.eclipse.kapua.service.authorization.group.GroupListResult; -import org.eclipse.kapua.service.authorization.group.GroupQuery; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.mockito.Mockito; -import java.util.Date; - - @Category(JUnitTests.class) public class GroupFactoryImplTest { @@ -41,7 +38,8 @@ public class GroupFactoryImplTest { public void initialize() { groupFactoryImpl = new GroupFactoryImpl(); scopeId = KapuaId.ONE; - names = new String[]{"", " na123)(&*^&NAME <>", "Na-,,..,,Me name ---", "-&^454536 na___,,12 NAME name ", "! 2#@ na meNEMA 2323", "12&^%4 ,,,. '|<>*(", " ,,123name;;'", "12#name--765 ,.aaa!!#$%^<> "}; + names = new String[] { "", " na123)(&*^&NAME <>", "Na-,,..,,Me name ---", "-&^454536 na___,,12 NAME name ", "! 2#@ na meNEMA 2323", "12&^%4 ,,,. '|<>*(", " ,,123name;;'", + "12#name--765 ,.aaa!!#$%^<> " }; group = Mockito.mock(Group.class); createdOn = new Date(); modifiedOn = new Date(); @@ -60,7 +58,7 @@ public void initialize() { @Test public void newCreatorScopeIdNameParametersTest() { for (String name : names) { - GroupCreator groupCreator = groupFactoryImpl.newCreator(scopeId, name); + GroupCreator groupCreator = new GroupCreator(scopeId, name); Assert.assertEquals("Expected and actual values should be the same.", name, groupCreator.getName()); Assert.assertEquals("Expected and actual values should be the same.", scopeId, groupCreator.getScopeId()); } @@ -69,7 +67,7 @@ public void newCreatorScopeIdNameParametersTest() { @Test public void newCreatorNullScopeIdNameParametersTest() { for (String name : names) { - GroupCreator groupCreator = groupFactoryImpl.newCreator(null, name); + GroupCreator groupCreator = new GroupCreator(null, name); Assert.assertEquals("Expected and actual values should be the same.", name, groupCreator.getName()); Assert.assertNull("Null expected.", groupCreator.getScopeId()); } @@ -77,7 +75,7 @@ public void newCreatorNullScopeIdNameParametersTest() { @Test public void newCreatorScopeIdNullNameParametersTest() { - GroupCreator groupCreator = groupFactoryImpl.newCreator(scopeId, null); + GroupCreator groupCreator = new GroupCreator(scopeId, null); Assert.assertNull("Null expected.", groupCreator.getName()); Assert.assertEquals("Expected and actual values should be the same.", scopeId, groupCreator.getScopeId()); } @@ -94,33 +92,15 @@ public void newEntityNullTest() { Assert.assertNull("Null expected.", group.getScopeId()); } - @Test - public void newListResultTest() { - GroupListResult groupListResult = groupFactoryImpl.newListResult(); - Assert.assertTrue("True expected.", groupListResult.isEmpty()); - } - - @Test - public void newQueryTest() { - GroupQuery groupQuery = groupFactoryImpl.newQuery(scopeId); - Assert.assertEquals("Expected and actual values should be the same.", scopeId, groupQuery.getScopeId()); - } - - @Test - public void newQueryNullTest() { - GroupQuery groupQuery = groupFactoryImpl.newQuery(null); - Assert.assertNull("Null expected.", groupQuery.getScopeId()); - } - @Test public void newCreatorTest() { - GroupCreator groupCreator = groupFactoryImpl.newCreator(scopeId); + GroupCreator groupCreator = new GroupCreator(scopeId); Assert.assertEquals("Expected and actual values should be the same.", scopeId, groupCreator.getScopeId()); } @Test public void newCreatorNullTest() { - GroupCreator groupCreator = groupFactoryImpl.newCreator(null); + GroupCreator groupCreator = new GroupCreator(null); Assert.assertNull("Null expected.", groupCreator.getScopeId()); } diff --git a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/group/shiro/GroupQueryImplTest.java b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/group/shiro/GroupQueryImplTest.java deleted file mode 100644 index 0d60b149cbe..00000000000 --- a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/group/shiro/GroupQueryImplTest.java +++ /dev/null @@ -1,40 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authorization.group.shiro; - -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.qa.markers.junit.JUnitTests; -import org.junit.Assert; -import org.junit.Test; -import org.junit.experimental.categories.Category; - - -@Category(JUnitTests.class) -public class GroupQueryImplTest { - - @Test - public void groupQueryImplTest() { - GroupQueryImpl groupQueryImpl = new GroupQueryImpl(KapuaId.ONE); - Assert.assertEquals("Expected and actual values should be the same.", KapuaId.ONE, groupQueryImpl.getScopeId()); - Assert.assertNull("groupQueryImpl.sortCriteria", groupQueryImpl.getSortCriteria()); - Assert.assertNotNull("groupQueryImpl.defaultSortCriteria", groupQueryImpl.getDefaultSortCriteria()); - } - - @Test - public void groupQueryImplNullTest() { - GroupQueryImpl groupQueryImpl = new GroupQueryImpl(null); - Assert.assertNull("Null expected.", groupQueryImpl.getScopeId()); - Assert.assertNull("groupQueryImpl.sortCriteria", groupQueryImpl.getSortCriteria()); - Assert.assertNotNull("groupQueryImpl.defaultSortCriteria", groupQueryImpl.getDefaultSortCriteria()); - } -} \ No newline at end of file diff --git a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/role/shiro/RoleCreatorImplTest.java b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/role/shiro/RoleCreatorTest.java similarity index 91% rename from service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/role/shiro/RoleCreatorImplTest.java rename to service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/role/shiro/RoleCreatorTest.java index d6c96fb0afd..beaed5e7233 100644 --- a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/role/shiro/RoleCreatorImplTest.java +++ b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/role/shiro/RoleCreatorTest.java @@ -12,29 +12,30 @@ *******************************************************************************/ package org.eclipse.kapua.service.authorization.role.shiro; +import java.util.HashSet; +import java.util.Set; + import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.qa.markers.junit.JUnitTests; import org.eclipse.kapua.service.authorization.permission.Permission; +import org.eclipse.kapua.service.authorization.role.RoleCreator; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.mockito.Mockito; -import java.util.HashSet; -import java.util.Set; - @Category(JUnitTests.class) -public class RoleCreatorImplTest { +public class RoleCreatorTest { - RoleCreatorImpl roleCreatorImpl; + RoleCreator roleCreatorImpl; Set permissions; Permission permission1, permission2; @Before public void initialize() { - roleCreatorImpl = new RoleCreatorImpl(KapuaId.ONE); + roleCreatorImpl = new RoleCreator(KapuaId.ONE); permissions = new HashSet<>(); permission1 = Mockito.mock(Permission.class); permission2 = Mockito.mock(Permission.class); @@ -44,7 +45,7 @@ public void initialize() { public void roleCreatorImplTest() { KapuaId[] scopeIds = {KapuaId.ONE, null}; for (KapuaId scopeId : scopeIds) { - RoleCreatorImpl roleCreatorImpl = new RoleCreatorImpl(scopeId); + RoleCreator roleCreatorImpl = new RoleCreator(scopeId); Assert.assertEquals("Expected and actual values should be the same.", scopeId, roleCreatorImpl.getScopeId()); Assert.assertTrue("True expected.", roleCreatorImpl.getPermissions().isEmpty()); } diff --git a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/role/shiro/RoleFactoryImplTest.java b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/role/shiro/RoleFactoryImplTest.java index 98b984f8866..4a46dc9d462 100644 --- a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/role/shiro/RoleFactoryImplTest.java +++ b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/role/shiro/RoleFactoryImplTest.java @@ -12,12 +12,11 @@ *******************************************************************************/ package org.eclipse.kapua.service.authorization.role.shiro; +import java.util.Date; + import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.qa.markers.junit.JUnitTests; import org.eclipse.kapua.service.authorization.role.Role; -import org.eclipse.kapua.service.authorization.role.RoleCreator; -import org.eclipse.kapua.service.authorization.role.RoleQuery; -import org.eclipse.kapua.service.authorization.role.RoleListResult; import org.eclipse.kapua.service.authorization.role.RolePermission; import org.junit.Assert; import org.junit.Before; @@ -25,9 +24,6 @@ import org.junit.experimental.categories.Category; import org.mockito.Mockito; -import java.util.Date; - - @Category(JUnitTests.class) public class RoleFactoryImplTest { @@ -67,36 +63,6 @@ public void newEntityNullTest() { Assert.assertNull("Null expected.", roleFactoryImpl.newEntity(null).getScopeId()); } - @Test - public void newCreatorTest() { - Assert.assertTrue("True expected.", roleFactoryImpl.newCreator(scopeId) instanceof RoleCreator); - Assert.assertEquals("Expected and actual values should be the same.", scopeId, roleFactoryImpl.newCreator(scopeId).getScopeId()); - } - - @Test - public void newCreatorNullTest() { - Assert.assertTrue("True expected.", roleFactoryImpl.newCreator(null) instanceof RoleCreator); - Assert.assertNull("Null expected.", roleFactoryImpl.newCreator(null).getScopeId()); - } - - @Test - public void newQueryTest() { - Assert.assertTrue("True expected.", roleFactoryImpl.newQuery(scopeId) instanceof RoleQuery); - Assert.assertEquals("Expected and actual values should be the same.", scopeId, roleFactoryImpl.newQuery(scopeId).getScopeId()); - } - - @Test - public void newQueryNullTest() { - Assert.assertTrue("True expected.", roleFactoryImpl.newQuery(null) instanceof RoleQuery); - Assert.assertNull("Null expected.", roleFactoryImpl.newQuery(null).getScopeId()); - } - - @Test - public void newListResultTest() { - Assert.assertTrue("True expected.", roleFactoryImpl.newListResult() instanceof RoleListResult); - Assert.assertTrue("True expected.", roleFactoryImpl.newListResult().isEmpty()); - } - @Test public void newRolePermissionTest() { Assert.assertTrue("True expected.", roleFactoryImpl.newRolePermission() instanceof RolePermission); diff --git a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/role/shiro/RolePermissionCreatorImplTest.java b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/role/shiro/RolePermissionCreatorTest.java similarity index 61% rename from service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/role/shiro/RolePermissionCreatorImplTest.java rename to service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/role/shiro/RolePermissionCreatorTest.java index c005528bd66..0f9433c3433 100644 --- a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/role/shiro/RolePermissionCreatorImplTest.java +++ b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/role/shiro/RolePermissionCreatorTest.java @@ -15,45 +15,45 @@ import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.qa.markers.junit.JUnitTests; import org.eclipse.kapua.service.authorization.permission.Permission; +import org.eclipse.kapua.service.authorization.role.RolePermissionCreator; import org.junit.Assert; import org.junit.Test; import org.junit.experimental.categories.Category; import org.mockito.Mockito; - @Category(JUnitTests.class) -public class RolePermissionCreatorImplTest { +public class RolePermissionCreatorTest { @Test - public void rolePermissionCreatorImplTest() { - KapuaId[] scopeIds = {null, KapuaId.ANY}; + public void rolePermissionCreatorTest() { + KapuaId[] scopeIds = { null, KapuaId.ANY }; for (KapuaId scopeId : scopeIds) { - RolePermissionCreatorImpl rolePermissionCreatorImpl = new RolePermissionCreatorImpl(scopeId); - Assert.assertEquals("Expected and actual values should be the same.", scopeId, rolePermissionCreatorImpl.getScopeId()); - Assert.assertNull("Null expected.", rolePermissionCreatorImpl.getRoleId()); - Assert.assertNull("Null expected.", rolePermissionCreatorImpl.getPermission()); + RolePermissionCreator rolePermissionCreator = new RolePermissionCreator(scopeId); + Assert.assertEquals("Expected and actual values should be the same.", scopeId, rolePermissionCreator.getScopeId()); + Assert.assertNull("Null expected.", rolePermissionCreator.getRoleId()); + Assert.assertNull("Null expected.", rolePermissionCreator.getPermission()); } } @Test public void setAndGetRoleIdTest() { - KapuaId[] roleIds = {null, KapuaId.ONE}; - RolePermissionCreatorImpl rolePermissionCreatorImpl = new RolePermissionCreatorImpl(KapuaId.ONE); + KapuaId[] roleIds = { null, KapuaId.ONE }; + RolePermissionCreator rolePermissionCreator = new RolePermissionCreator(KapuaId.ONE); for (KapuaId roleId : roleIds) { - rolePermissionCreatorImpl.setRoleId(roleId); - Assert.assertEquals("Expected and actual values should be the same.", roleId, rolePermissionCreatorImpl.getRoleId()); + rolePermissionCreator.setRoleId(roleId); + Assert.assertEquals("Expected and actual values should be the same.", roleId, rolePermissionCreator.getRoleId()); } } @Test public void setAndGetPermissionTest() { - Permission[] permissions = {null, Mockito.mock(Permission.class)}; - RolePermissionCreatorImpl rolePermissionCreatorImpl = new RolePermissionCreatorImpl(KapuaId.ONE); + Permission[] permissions = { null, Mockito.mock(Permission.class) }; + RolePermissionCreator rolePermissionCreator = new RolePermissionCreator(KapuaId.ONE); for (Permission permission : permissions) { - rolePermissionCreatorImpl.setPermission(permission); - Assert.assertEquals("Expected and actual values should be the same.", permission, rolePermissionCreatorImpl.getPermission()); + rolePermissionCreator.setPermission(permission); + Assert.assertEquals("Expected and actual values should be the same.", permission, rolePermissionCreator.getPermission()); } } } \ No newline at end of file diff --git a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/role/shiro/RolePermissionQueryImplTest.java b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/role/shiro/RolePermissionQueryImplTest.java deleted file mode 100644 index 42cd8f69d16..00000000000 --- a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/role/shiro/RolePermissionQueryImplTest.java +++ /dev/null @@ -1,44 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authorization.role.shiro; - -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.qa.markers.junit.JUnitTests; -import org.junit.Assert; -import org.junit.Test; -import org.junit.experimental.categories.Category; - - -@Category(JUnitTests.class) -public class RolePermissionQueryImplTest { - - @Test - public void rolePermissionQueryImplWithoutParametersTest() { - RolePermissionQueryImpl rolePermissionQueryImpl = new RolePermissionQueryImpl(); - Assert.assertNull("Null expected.", rolePermissionQueryImpl.getScopeId()); - Assert.assertNull("rolePermissionQueryImpl.sortCriteria", rolePermissionQueryImpl.getSortCriteria()); - Assert.assertNotNull("rolePermissionQueryImpl.defaultSortCriteria", rolePermissionQueryImpl.getDefaultSortCriteria()); - } - - @Test - public void rolePermissionQueryImpScopeIdTest() { - KapuaId[] scopeIds = {null, KapuaId.ANY}; - - for (KapuaId scopeId : scopeIds) { - RolePermissionQueryImpl rolePermissionQueryImpl = new RolePermissionQueryImpl(scopeId); - Assert.assertEquals("Expected and actual values should be the same.", scopeId, rolePermissionQueryImpl.getScopeId()); - Assert.assertNull("rolePermissionQueryImpl.sortCriteria", rolePermissionQueryImpl.getSortCriteria()); - Assert.assertNotNull("rolePermissionQueryImpl.defaultSortCriteria", rolePermissionQueryImpl.getDefaultSortCriteria()); - } - } -} \ No newline at end of file diff --git a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/role/shiro/RoleQueryImplTest.java b/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/role/shiro/RoleQueryImplTest.java deleted file mode 100644 index 929af6c9a56..00000000000 --- a/service/security/shiro/src/test/java/org/eclipse/kapua/service/authorization/role/shiro/RoleQueryImplTest.java +++ /dev/null @@ -1,44 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2021, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.authorization.role.shiro; - -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.qa.markers.junit.JUnitTests; -import org.junit.Assert; -import org.junit.Test; -import org.junit.experimental.categories.Category; - - -@Category(JUnitTests.class) -public class RoleQueryImplTest { - - @Test - public void rolePermissionQueryImplWithoutParametersTest() { - RoleQueryImpl roleQueryImpl = new RoleQueryImpl(); - Assert.assertNull("Null expected.", roleQueryImpl.getScopeId()); - Assert.assertNull("roleQueryImpl.sortCriteria", roleQueryImpl.getSortCriteria()); - Assert.assertNotNull("roleQueryImpl.defaultSortCriteria", roleQueryImpl.getDefaultSortCriteria()); - } - - @Test - public void rolePermissionQueryImpScopeIdTest() { - KapuaId[] scopeIds = {null, KapuaId.ANY}; - - for (KapuaId scopeId : scopeIds) { - RoleQueryImpl roleQueryImpl = new RoleQueryImpl(scopeId); - Assert.assertEquals("Expected and actual values should be the same.", scopeId, roleQueryImpl.getScopeId()); - Assert.assertNull("roleQueryImpl.sortCriteria", roleQueryImpl.getSortCriteria()); - Assert.assertNotNull("roleQueryImpl.defaultSortCriteria", roleQueryImpl.getDefaultSortCriteria()); - } - } -} \ No newline at end of file diff --git a/service/security/test-steps/pom.xml b/service/security/test-steps/pom.xml index 05ce7b0cdeb..d01c41ee436 100644 --- a/service/security/test-steps/pom.xml +++ b/service/security/test-steps/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-security - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-security-test-steps diff --git a/service/security/test-steps/src/main/java/org/eclipse/kapua/service/authentication/steps/AuthenticationServiceSteps.java b/service/security/test-steps/src/main/java/org/eclipse/kapua/service/authentication/steps/AuthenticationServiceSteps.java index 0a28f067097..9c9678d48c6 100644 --- a/service/security/test-steps/src/main/java/org/eclipse/kapua/service/authentication/steps/AuthenticationServiceSteps.java +++ b/service/security/test-steps/src/main/java/org/eclipse/kapua/service/authentication/steps/AuthenticationServiceSteps.java @@ -12,12 +12,12 @@ *******************************************************************************/ package org.eclipse.kapua.service.authentication.steps; -import com.google.inject.Singleton; -import io.cucumber.java.After; -import io.cucumber.java.Before; -import io.cucumber.java.Scenario; -import io.cucumber.java.en.Given; -import io.cucumber.java.en.When; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.inject.Inject; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.commons.security.KapuaSecurityUtils; import org.eclipse.kapua.locator.KapuaLocator; @@ -29,26 +29,23 @@ import org.eclipse.kapua.service.account.Account; import org.eclipse.kapua.service.authentication.credential.Credential; import org.eclipse.kapua.service.authentication.credential.CredentialCreator; -import org.eclipse.kapua.service.authentication.credential.CredentialFactory; import org.eclipse.kapua.service.authentication.credential.CredentialService; import org.eclipse.kapua.service.authentication.credential.CredentialStatus; import org.eclipse.kapua.service.authentication.user.PasswordChangeRequest; import org.eclipse.kapua.service.authentication.user.PasswordResetRequest; -import org.eclipse.kapua.service.authentication.user.UserCredentialsFactory; import org.eclipse.kapua.service.authentication.user.UserCredentialsService; -import org.eclipse.kapua.service.authorization.access.AccessInfoFactory; -import org.eclipse.kapua.service.authorization.access.AccessInfoService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; import org.eclipse.kapua.service.user.User; import org.eclipse.kapua.service.user.UserCreator; -import org.eclipse.kapua.service.user.UserFactory; import org.eclipse.kapua.service.user.UserService; import org.junit.Assert; -import javax.inject.Inject; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import com.google.inject.Singleton; + +import io.cucumber.java.After; +import io.cucumber.java.Before; +import io.cucumber.java.Scenario; +import io.cucumber.java.en.Given; +import io.cucumber.java.en.When; // Implementation of Gherkin steps used to test miscellaneous Shiro // authorization functionality. @@ -61,17 +58,9 @@ public class AuthenticationServiceSteps extends TestBase { private static final String LAST_ACCOUNT = "LastAccount"; private CredentialService credentialService; - private CredentialFactory credentialFactory; private UserService userService; - private UserFactory userFactory; private UserCredentialsService userCredentialsService; - private UserCredentialsFactory userCredentialsFactory; - - private AccessInfoService accessInfoService; - private AccessInfoFactory accessInfoFactory; - - private PermissionFactory permissionFactory; @Inject public AuthenticationServiceSteps(StepData stepData) { @@ -87,19 +76,13 @@ public void beforeScenarioNone(Scenario scenario) throws KapuaException { public void setServices() { locator = KapuaLocator.getInstance(); credentialService = locator.getService(CredentialService.class); - credentialFactory = locator.getFactory(CredentialFactory.class); userService = locator.getService(UserService.class); - userFactory = locator.getFactory(UserFactory.class); userCredentialsService = locator.getService(UserCredentialsService.class); - userCredentialsFactory = locator.getFactory(UserCredentialsFactory.class); - accessInfoService = locator.getService(AccessInfoService.class); - accessInfoFactory = locator.getFactory(AccessInfoFactory.class); - permissionFactory = locator.getFactory(PermissionFactory.class); } @When("I create default test-user") public void createDefaultUser() throws KapuaException { - UserCreator userCreator = userFactory.newCreator(KapuaId.ONE, "test-user"); + UserCreator userCreator = new UserCreator(KapuaId.ONE, "test-user"); User user = userService.create(userCreator); stepData.put("User", user); } @@ -192,7 +175,7 @@ public void createPasswordCredential(String password) throws Exception { primeException(); User user = (User) stepData.get("User"); - CredentialCreator credentialCreator = credentialFactory.newCreator(user.getScopeId(), user.getId(), "PASSWORD", password, CredentialStatus.ENABLED, null); + CredentialCreator credentialCreator = new CredentialCreator(user.getScopeId(), user.getId(), "PASSWORD", password, CredentialStatus.ENABLED, null); try { Credential credential = credentialService.create(credentialCreator); stepData.put(BasicSteps.LAST_CREDENTIAL_ID, credential.getId()); @@ -201,12 +184,11 @@ public void createPasswordCredential(String password) throws Exception { } } - @When("I change the user credential password with old password {string} and new password {string}") public void changeUserPasswordCredential(String oldPassword, String newPassword) throws Exception { primeException(); - PasswordChangeRequest passwordChangeRequest = userCredentialsFactory.newPasswordChangeRequest(); + PasswordChangeRequest passwordChangeRequest = new PasswordChangeRequest(); passwordChangeRequest.setCurrentPassword(oldPassword); passwordChangeRequest.setNewPassword(newPassword); @@ -217,12 +199,11 @@ public void changeUserPasswordCredential(String oldPassword, String newPassword) } } - @When("I reset the last created credential password, with the new password {string}") public void resetUserPasswordCredentialPassword(String newPassword) throws Exception { primeException(); - PasswordResetRequest passwordResetRequest = userCredentialsFactory.newPasswordResetRequest(); + PasswordResetRequest passwordResetRequest = new PasswordResetRequest(); passwordResetRequest.setNewPassword(newPassword); KapuaId credentialId = (KapuaId) stepData.get(BasicSteps.LAST_CREDENTIAL_ID); diff --git a/service/security/test-steps/src/main/java/org/eclipse/kapua/service/authorization/steps/AuthorizationServiceSteps.java b/service/security/test-steps/src/main/java/org/eclipse/kapua/service/authorization/steps/AuthorizationServiceSteps.java index f015b1ed1b6..530d327d5fc 100644 --- a/service/security/test-steps/src/main/java/org/eclipse/kapua/service/authorization/steps/AuthorizationServiceSteps.java +++ b/service/security/test-steps/src/main/java/org/eclipse/kapua/service/authorization/steps/AuthorizationServiceSteps.java @@ -12,20 +12,22 @@ *******************************************************************************/ package org.eclipse.kapua.service.authorization.steps; -import com.google.inject.Singleton; -import io.cucumber.java.After; -import io.cucumber.java.Before; -import io.cucumber.java.Scenario; -import io.cucumber.java.en.And; -import io.cucumber.java.en.Given; -import io.cucumber.java.en.Then; -import io.cucumber.java.en.When; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.inject.Inject; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.commons.security.KapuaSecurityUtils; import org.eclipse.kapua.locator.KapuaLocator; import org.eclipse.kapua.model.KapuaNamedEntityAttributes; import org.eclipse.kapua.model.domain.Actions; import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.model.query.predicate.AttributePredicate; import org.eclipse.kapua.qa.common.StepData; import org.eclipse.kapua.qa.common.TestBase; @@ -42,7 +44,6 @@ import org.eclipse.kapua.service.authorization.access.AccessInfoCreator; import org.eclipse.kapua.service.authorization.access.AccessInfoFactory; import org.eclipse.kapua.service.authorization.access.AccessInfoListResult; -import org.eclipse.kapua.service.authorization.access.AccessInfoQuery; import org.eclipse.kapua.service.authorization.access.AccessInfoService; import org.eclipse.kapua.service.authorization.access.AccessPermission; import org.eclipse.kapua.service.authorization.access.AccessPermissionCreator; @@ -54,22 +55,16 @@ import org.eclipse.kapua.service.authorization.access.AccessRoleCreator; import org.eclipse.kapua.service.authorization.access.AccessRoleFactory; import org.eclipse.kapua.service.authorization.access.AccessRoleListResult; -import org.eclipse.kapua.service.authorization.access.AccessRoleQuery; import org.eclipse.kapua.service.authorization.access.AccessRoleService; import org.eclipse.kapua.service.authorization.domain.Domain; import org.eclipse.kapua.service.authorization.domain.DomainCreator; -import org.eclipse.kapua.service.authorization.domain.DomainFactory; import org.eclipse.kapua.service.authorization.domain.DomainListResult; -import org.eclipse.kapua.service.authorization.domain.DomainQuery; import org.eclipse.kapua.service.authorization.domain.DomainRegistryService; import org.eclipse.kapua.service.authorization.group.Group; import org.eclipse.kapua.service.authorization.group.GroupCreator; -import org.eclipse.kapua.service.authorization.group.GroupFactory; import org.eclipse.kapua.service.authorization.group.GroupListResult; -import org.eclipse.kapua.service.authorization.group.GroupQuery; import org.eclipse.kapua.service.authorization.group.GroupService; import org.eclipse.kapua.service.authorization.permission.Permission; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; import org.eclipse.kapua.service.authorization.role.Role; import org.eclipse.kapua.service.authorization.role.RoleCreator; import org.eclipse.kapua.service.authorization.role.RoleFactory; @@ -79,7 +74,6 @@ import org.eclipse.kapua.service.authorization.role.RolePermissionCreator; import org.eclipse.kapua.service.authorization.role.RolePermissionFactory; import org.eclipse.kapua.service.authorization.role.RolePermissionListResult; -import org.eclipse.kapua.service.authorization.role.RolePermissionQuery; import org.eclipse.kapua.service.authorization.role.RolePermissionService; import org.eclipse.kapua.service.authorization.role.RoleQuery; import org.eclipse.kapua.service.authorization.role.RoleService; @@ -88,13 +82,15 @@ import org.eclipse.kapua.service.user.UserService; import org.junit.Assert; -import javax.inject.Inject; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; +import com.google.inject.Singleton; + +import io.cucumber.java.After; +import io.cucumber.java.Before; +import io.cucumber.java.Scenario; +import io.cucumber.java.en.And; +import io.cucumber.java.en.Given; +import io.cucumber.java.en.Then; +import io.cucumber.java.en.When; // Implementation of Gherkin steps used to test miscellaneous Shiro // authorization functionality. @@ -137,7 +133,6 @@ public class AuthorizationServiceSteps extends TestBase { private static final TestDomain TEST_DOMAIN = new TestDomain(); // Various Authorization service references - private PermissionFactory permissionFactory; private AccessInfoService accessInfoService; private AccessInfoFactory accessInfoFactory; private AccessPermissionService accessPermissionService; @@ -145,9 +140,7 @@ public class AuthorizationServiceSteps extends TestBase { private AccessRoleService accessRoleService; private AccessRoleFactory accessRoleFactory; private DomainRegistryService domainRegistryService; - private DomainFactory domainFactory; private GroupService groupService; - private GroupFactory groupFactory; private RoleService roleService; private RoleFactory roleFactory; private RolePermissionService rolePermissionService; @@ -169,14 +162,11 @@ public void setServices() { accessRoleService = locator.getService(AccessRoleService.class); accessRoleFactory = locator.getFactory(AccessRoleFactory.class); domainRegistryService = locator.getService(DomainRegistryService.class); - domainFactory = locator.getFactory(DomainFactory.class); groupService = locator.getService(GroupService.class); - groupFactory = locator.getFactory(GroupFactory.class); roleService = locator.getService(RoleService.class); roleFactory = locator.getFactory(RoleFactory.class); rolePermissionService = locator.getService(RolePermissionService.class); rolePermissionFactory = locator.getFactory(RolePermissionFactory.class); - permissionFactory = locator.getFactory(PermissionFactory.class); userService = locator.getService(UserService.class); } @@ -245,10 +235,10 @@ public void createAListOfRoles(List roles) throws Exception { permissions = new HashSet<>(); if ((tmpRole.getActions() != null) && (tmpRole.getActions().size() > 0)) { for (Actions tmpAct : tmpRole.getActions()) { - permissions.add(permissionFactory.newPermission(domain.getDomain().getName(), tmpAct, tmpRole.getScopeId())); + permissions.add(new Permission(domain.getDomain().getName(), tmpAct, tmpRole.getScopeId())); } } - roleCreator = roleFactory.newCreator(tmpRole.getScopeId()); + roleCreator = new RoleCreator(tmpRole.getScopeId()); roleCreator.setName(tmpRole.getName()); roleCreator.setPermissions(permissions); try { @@ -275,9 +265,9 @@ public void createAListOfRolePermissions(List perms) throws E Assert.assertNotNull(tmpCPerm.getScopeId()); Assert.assertNotNull(tmpCPerm.getAction()); domain.setScopeId(tmpCPerm.getScopeId()); - RolePermissionCreator rolePermissionCreator = rolePermissionFactory.newCreator(tmpCPerm.getScopeId()); + RolePermissionCreator rolePermissionCreator = new RolePermissionCreator(tmpCPerm.getScopeId()); rolePermissionCreator.setRoleId(role.getId()); - rolePermissionCreator.setPermission(permissionFactory.newPermission(domain.getDomain().getName(), tmpCPerm.getAction(), tmpCPerm.getTargetScopeId())); + rolePermissionCreator.setPermission(new Permission(domain.getDomain().getName(), tmpCPerm.getAction(), tmpCPerm.getTargetScopeId())); try { stepData.remove(ROLE_PERMISSIONS); rolePermission = rolePermissionService.create(rolePermissionCreator); @@ -382,18 +372,18 @@ public void deleteLastCreatedRolePermission() throws Exception { @When("I count the roles in scope {int}") public void countRolesInScope(int scope) throws Exception { - updateCount(() -> (int) roleService.count(roleFactory.newQuery(getKapuaId(scope)))); + updateCount(() -> (int) roleService.count(new KapuaQuery(getKapuaId(scope)))); } @When("I count the role permissions in scope {int}") public void countRolePermissionsInScope(Integer scope) throws Exception { - updateCount(() -> (int) rolePermissionService.count(rolePermissionFactory.newQuery(getKapuaId(scope)))); + updateCount(() -> (int) rolePermissionService.count(new KapuaQuery(getKapuaId(scope)))); } @When("I query for the role {string} in scope {int}") public void queryForRoleInScope(String name, Integer scope) throws Exception { KapuaId tmpId = getKapuaId(scope); - RoleQuery tmpQuery = roleFactory.newQuery(tmpId); + KapuaQuery tmpQuery = new KapuaQuery(tmpId); tmpQuery.setPredicate(tmpQuery.attributePredicate(KapuaNamedEntityAttributes.NAME, name, AttributePredicate.Operator.EQUAL)); stepData.remove(ROLE_LIST); stepData.remove(ROLE_FOUND); @@ -522,18 +512,14 @@ public void checkRoleForUpdates() { @Then("The role factory returns sane results") public void performRoleFactorySanityChecks() { Assert.assertNotNull(roleFactory.newEntity(SYS_SCOPE_ID)); - Assert.assertNotNull(roleFactory.newCreator(SYS_SCOPE_ID)); - Assert.assertNotNull(roleFactory.newQuery(SYS_SCOPE_ID)); - Assert.assertNotNull(roleFactory.newListResult()); + Assert.assertNotNull(new RoleCreator(SYS_SCOPE_ID)); Assert.assertNotNull(roleFactory.newRolePermission()); } @Then("The role permission factory returns sane results") public void performRolePermissionFactorySanityChecks() { Assert.assertNotNull(rolePermissionFactory.newEntity(SYS_SCOPE_ID)); - Assert.assertNotNull(rolePermissionFactory.newCreator(SYS_SCOPE_ID)); - Assert.assertNotNull(rolePermissionFactory.newQuery(SYS_SCOPE_ID)); - Assert.assertNotNull(rolePermissionFactory.newListResult()); + Assert.assertNotNull(new RolePermissionCreator(SYS_SCOPE_ID)); } @Then("The role comparator does its job") @@ -561,8 +547,8 @@ public void checkRolePermissionEqualityMethod() { RolePermission perm1 = rolePermissionFactory.newEntity(SYS_SCOPE_ID); RolePermission perm2 = rolePermissionFactory.newEntity(SYS_SCOPE_ID); Integer miscObj = 1; - Permission tmpPermission1 = permissionFactory.newPermission(TEST_DOMAIN.getName(), Actions.read, SYS_SCOPE_ID); - Permission tmpPermission2 = permissionFactory.newPermission(TEST_DOMAIN.getName(), Actions.write, SYS_SCOPE_ID); + Permission tmpPermission1 = new Permission(TEST_DOMAIN.getName(), Actions.read, SYS_SCOPE_ID); + Permission tmpPermission2 = new Permission(TEST_DOMAIN.getName(), Actions.write, SYS_SCOPE_ID); KapuaId tmpRoleId1 = getKapuaId(); KapuaId tmpRoleId2 = getKapuaId(); Assert.assertNotNull(perm1); @@ -587,7 +573,7 @@ public void checkRolePermissionEqualityMethod() { @Then("The role permission object constructors are sane") public void checkRolePermissionConstructors() { - Permission tmpPermission = permissionFactory.newPermission(TEST_DOMAIN.getName(), Actions.read, SYS_SCOPE_ID); + Permission tmpPermission = new Permission(TEST_DOMAIN.getName(), Actions.read, SYS_SCOPE_ID); KapuaId tmpRoleId = getKapuaId(); RolePermission perm1 = rolePermissionFactory.newEntity(SYS_SCOPE_ID); Assert.assertNotNull(perm1); @@ -607,7 +593,7 @@ public void createAListOfDomains(List domains) throws Exception { primeException(); for (CucDomain tmpDom : domains) { tmpDom.doParse(); - domainCreator = domainFactory.newCreator(tmpDom.getName()); + domainCreator = new DomainCreator(tmpDom.getName()); if (tmpDom.getActionSet() != null) { domainCreator.setActions(tmpDom.getActionSet()); } @@ -627,7 +613,7 @@ public void createAListOfDomains(List domains) throws Exception { @Given("I select the domain {string}") public void selectExistingDomain(String name) throws Exception { - DomainQuery query = domainFactory.newQuery(KapuaId.ANY); + final KapuaQuery query = new KapuaQuery(KapuaId.ANY); query.setPredicate(query.attributePredicate(KapuaNamedEntityAttributes.NAME, name, AttributePredicate.Operator.EQUAL)); try { primeException(); @@ -674,12 +660,12 @@ public void deleteRandomDomainId() throws Exception { @When("I count the domain entries in the database") public void countDomainEntries() throws Exception { - updateCount(() -> (int) domainRegistryService.count(domainFactory.newQuery(null))); + updateCount(() -> (int) domainRegistryService.count(new KapuaQuery((KapuaId) null))); } @When("I query for domains with the name {string}") public void queryForNamedDomain(String name) throws Exception { - DomainQuery query = domainFactory.newQuery(null); + final KapuaQuery query = new KapuaQuery((KapuaId) null); query.setPredicate(query.attributePredicate(KapuaNamedEntityAttributes.NAME, name, AttributePredicate.Operator.EQUAL)); stepData.remove("DomainList"); try { @@ -721,7 +707,7 @@ public void checkDomainIsNull() { @Then("I can compare domain objects") public void checkDomainComparison() throws KapuaException { KapuaSecurityUtils.doPrivileged(() -> { - DomainCreator tmpCreator = domainFactory.newCreator("name_1"); + DomainCreator tmpCreator = new DomainCreator("name_1"); tmpCreator.setServiceName("test"); HashSet tmpAct = new HashSet<>(); tmpAct.add(Actions.read); @@ -821,7 +807,7 @@ public void setGroupConfigurationValue(List cucConfigs) throws Except @When("I count the group entries in the database") public void countGroupEntries() throws Exception { - updateCount(() -> (int) groupService.count(groupFactory.newQuery(SYS_SCOPE_ID))); + updateCount(() -> (int) groupService.count(new KapuaQuery(SYS_SCOPE_ID))); } @Given("I create the group(s)") @@ -834,7 +820,7 @@ public void createAListOfGroups(List groups) throws Exception { primeException(); for (CucGroup tmpGrp : groups) { tmpGrp.doParse(); - groupCreator = groupFactory.newCreator(tmpGrp.getScopeId(), tmpGrp.getName()); + groupCreator = new GroupCreator(tmpGrp.getScopeId(), tmpGrp.getName()); try { group = groupService.create(groupCreator); stepData.put(GROUP_CREATOR, groupCreator); @@ -877,7 +863,7 @@ public void updateGroupWithFalseId() throws Exception { public void deleteGroupWithName(String groupName) throws Exception { primeException(); try { - GroupQuery tmpQuery = groupFactory.newQuery(getCurrentScopeId()); + final KapuaQuery tmpQuery = new KapuaQuery(getCurrentScopeId()); tmpQuery.setPredicate(tmpQuery.attributePredicate(KapuaNamedEntityAttributes.NAME, groupName, AttributePredicate.Operator.EQUAL)); Group group = groupService.query(tmpQuery).getFirstItem(); groupService.delete(group.getScopeId(), group.getId()); @@ -923,13 +909,13 @@ public void findGroupByRememberedId(String groupName) throws Exception { @When("I count all the groups in scope {int}") public void countGroupsInScope(int scope) throws Exception { - updateCount(() -> (int) groupService.count(groupFactory.newQuery(getKapuaId(scope)))); + updateCount(() -> (int) groupService.count(new KapuaQuery(getKapuaId(scope)))); } @When("I query for the group {string} in scope {int}") public void queryForGroup(String name, int scope) throws Exception { KapuaId tmpId = getKapuaId(scope); - GroupQuery tmpQuery = groupFactory.newQuery(tmpId); + final KapuaQuery tmpQuery = new KapuaQuery(tmpId); tmpQuery.setPredicate(tmpQuery.attributePredicate(KapuaNamedEntityAttributes.NAME, name, AttributePredicate.Operator.EQUAL)); stepData.remove("GroupList"); stepData.remove(GROUP); @@ -1026,21 +1012,21 @@ public void createPermissionsForDomain(String permList) { Domain curDomain = (Domain) stepData.get(DOMAIN); for (String perm : tmpList) { switch (perm.trim()) { - case "read": - permissions.add(permissionFactory.newPermission(curDomain.getDomain().getName(), Actions.read, currId)); - break; - case "write": - permissions.add(permissionFactory.newPermission(curDomain.getDomain().getName(), Actions.write, currId)); - break; - case "delete": - permissions.add(permissionFactory.newPermission(curDomain.getDomain().getName(), Actions.delete, currId)); - break; - case "connect": - permissions.add(permissionFactory.newPermission(curDomain.getDomain().getName(), Actions.connect, currId)); - break; - case "execute": - permissions.add(permissionFactory.newPermission(curDomain.getDomain().getName(), Actions.execute, currId)); - break; + case "read": + permissions.add(new Permission(curDomain.getDomain().getName(), Actions.read, currId)); + break; + case "write": + permissions.add(new Permission(curDomain.getDomain().getName(), Actions.write, currId)); + break; + case "delete": + permissions.add(new Permission(curDomain.getDomain().getName(), Actions.delete, currId)); + break; + case "connect": + permissions.add(new Permission(curDomain.getDomain().getName(), Actions.connect, currId)); + break; + case "execute": + permissions.add(new Permission(curDomain.getDomain().getName(), Actions.execute, currId)); + break; } } // Make sure that there is at least one valid item @@ -1052,7 +1038,7 @@ public void createPermissionsForDomain(String permList) { public void provideRoleForDomain(String name) throws Exception { KapuaId currId = (KapuaId) stepData.get(LAST_ACCOUNT_ID); Set permissions = (Set) stepData.get(PERMISSIONS); - RoleCreator roleCreator = roleFactory.newCreator(currId); + RoleCreator roleCreator = new RoleCreator(currId); roleCreator.setName(name); roleCreator.setPermissions(permissions); try { @@ -1082,7 +1068,7 @@ public void createAccessRole() throws Exception { KapuaId currScope = (KapuaId) stepData.get(LAST_ACCOUNT_ID); AccessInfo accessInfo = (AccessInfo) stepData.get(ACCESS_INFO); Role role = (Role) stepData.get("Role"); - AccessRoleCreator tmpCreator = accessRoleFactory.newCreator(currScope); + AccessRoleCreator tmpCreator = new AccessRoleCreator(currScope); tmpCreator.setAccessInfoId(accessInfo.getId()); tmpCreator.setRoleId(role.getId()); try { @@ -1099,7 +1085,7 @@ public void createAccessRole() throws Exception { public void createCleanAccessInfoEntity() throws Exception { KapuaId currScope = (KapuaId) stepData.get(LAST_ACCOUNT_ID); User tmpUser = (User) stepData.get("User"); - AccessInfoCreator accessInfoCreator = accessInfoFactory.newCreator(currScope); + AccessInfoCreator accessInfoCreator = new AccessInfoCreator(currScope); accessInfoCreator.setUserId(tmpUser.getId()); stepData.remove(PERMISSIONS); stepData.remove(ROLE_IDS); @@ -1118,7 +1104,7 @@ public void createCleanAccessInfoEntity() throws Exception { public void createAccessInfoEntity() throws Exception { KapuaId currScope = (KapuaId) stepData.get(LAST_ACCOUNT_ID); User tmpUser = (User) stepData.get("User"); - AccessInfoCreator accessInfoCreator = accessInfoFactory.newCreator(currScope); + AccessInfoCreator accessInfoCreator = new AccessInfoCreator(currScope); accessInfoCreator.setUserId(tmpUser.getId()); Set permissions = (Set) stepData.get(PERMISSIONS); Set roleIds = (Set) stepData.get(ROLE_IDS); @@ -1213,7 +1199,7 @@ public void findLastCreatedAccessRole() throws Exception { @When("I count the access roles in scope {int}") public void countAccesRolesInScope(Integer scope) throws Exception { - updateCount(() -> (int) accessRoleService.count(accessRoleFactory.newQuery(getKapuaId(scope)))); + updateCount(() -> (int) accessRoleService.count(new KapuaQuery(getKapuaId(scope)))); } @When("I delete the last created access role entry") @@ -1242,14 +1228,14 @@ public void deleteLastCreatedAccessInfoEntity() throws Exception { @When("I count the access info entities for scope {int}") public void countAccessInfoEntitiesInScope(Integer scope) throws Exception { - updateCount(() -> (int) accessInfoService.count(accessInfoFactory.newQuery(getKapuaId(scope)))); + updateCount(() -> (int) accessInfoService.count(new KapuaQuery(getKapuaId(scope)))); } @When("I query for the access info entities for the last user") public void queryForLastUserAccessInfoEntities() throws Exception { KapuaId currScope = (KapuaId) stepData.get(LAST_ACCOUNT_ID); User user = (User) stepData.get("User"); - AccessInfoQuery tmpQuery = accessInfoFactory.newQuery(currScope); + final KapuaQuery tmpQuery = new KapuaQuery(currScope); tmpQuery.setPredicate(tmpQuery.attributePredicate(AccessInfoAttributes.USER_ID, user.getId(), AttributePredicate.Operator.EQUAL)); try { primeException(); @@ -1267,7 +1253,7 @@ public void createPermissionEntries() throws Exception { KapuaId currScope = (KapuaId) stepData.get(LAST_ACCOUNT_ID); AccessInfo accessInfo = (AccessInfo) stepData.get(ACCESS_INFO); Set permissions = (Set) stepData.get(PERMISSIONS); - AccessPermissionCreator accessPermissionCreator = accessPermissionFactory.newCreator(currScope); + AccessPermissionCreator accessPermissionCreator = new AccessPermissionCreator(currScope); accessPermissionCreator.setAccessInfoId(accessInfo.getId()); try { primeException(); @@ -1314,18 +1300,16 @@ public void deleteLastCreatedPermission() throws Exception { @When("I count the permissions in scope {int}") public void countPermissionsForScope(Integer scope) throws Exception { - updateCount(() -> (int) accessPermissionService.count(accessPermissionFactory.newQuery(getKapuaId(scope)))); + updateCount(() -> (int) accessPermissionService.count(new KapuaQuery(getKapuaId(scope)))); } @When("I check the sanity of the access info factory") public void accessInfoServiceSanityCheck() throws Exception { try { primeException(); - Assert.assertNotNull(accessInfoFactory.newCreator(getKapuaId())); + Assert.assertNotNull(new AccessInfoCreator(getKapuaId())); Assert.assertNotNull(accessInfoFactory.newEntity(null)); - Assert.assertNotNull(accessInfoFactory.newQuery(getKapuaId())); - Assert.assertNotNull(accessInfoFactory.newListResult()); - AccessInfoCreator tmpCreator = accessInfoFactory.newCreator(getKapuaId()); + AccessInfoCreator tmpCreator = new AccessInfoCreator(getKapuaId()); Assert.assertNotNull(tmpCreator); AccessInfo tmpAccInfo = accessInfoFactory.newEntity(getKapuaId()); Assert.assertNotNull(tmpAccInfo); @@ -1338,20 +1322,18 @@ public void accessInfoServiceSanityCheck() throws Exception { @When("I check the sanity of the access permission factory") public void accessPermissionFactorySanityCheck() { - Assert.assertNotNull(accessPermissionFactory.newCreator(getKapuaId())); + Assert.assertNotNull(new AccessPermissionCreator(getKapuaId())); Assert.assertNotNull(accessPermissionFactory.newEntity(null)); Assert.assertNotNull(accessPermissionFactory.newEntity(getKapuaId())); - Assert.assertNotNull(accessPermissionFactory.newQuery(getKapuaId())); - Assert.assertNotNull(accessPermissionFactory.newListResult()); KapuaId tmpId = getKapuaId(); - AccessPermissionCreator tmpCreator = accessPermissionFactory.newCreator(tmpId); + AccessPermissionCreator tmpCreator = new AccessPermissionCreator(tmpId); Assert.assertNotNull(tmpCreator); Assert.assertNotNull(tmpCreator.getScopeId()); Assert.assertEquals(tmpId, tmpCreator.getScopeId()); AccessPermission tmpAccPerm = accessPermissionFactory.newEntity(getKapuaId()); Assert.assertNotNull(tmpAccPerm); tmpAccPerm.setAccessInfoId(getKapuaId()); - Permission tmpPerm = permissionFactory.newPermission(new TestDomain().getName(), Actions.read, getKapuaId(), getKapuaId()); + Permission tmpPerm = new Permission(new TestDomain().getName(), Actions.read, getKapuaId(), getKapuaId()); tmpAccPerm.setPermission(tmpPerm); Assert.assertEquals(tmpPerm, tmpAccPerm.getPermission()); tmpAccPerm.setAccessInfoId(null); @@ -1366,12 +1348,10 @@ public void accessPermissionFactorySanityCheck() { public void accessRoleFactorySanityCheck() throws Exception { try { primeException(); - Assert.assertNotNull(accessRoleFactory.newCreator(getKapuaId())); + Assert.assertNotNull(new AccessRoleCreator(getKapuaId())); Assert.assertNotNull(accessRoleFactory.newEntity(getKapuaId())); - Assert.assertNotNull(accessRoleFactory.newQuery(getKapuaId())); - Assert.assertNotNull(accessRoleFactory.newListResult()); KapuaId tmpId = getKapuaId(); - AccessRoleCreator tmpCreator = accessRoleFactory.newCreator(tmpId); + AccessRoleCreator tmpCreator = new AccessRoleCreator(tmpId); Assert.assertNotNull(tmpCreator); Assert.assertNotNull(tmpCreator.getScopeId()); Assert.assertEquals(tmpId, tmpCreator.getScopeId()); @@ -1510,8 +1490,8 @@ public void checkAccessRoleComparison() throws Exception { public void checkAccessPermissionComparison() { AccessPermission accPerm1 = accessPermissionFactory.newEntity(getKapuaId()); AccessPermission accPerm2 = accessPermissionFactory.newEntity(getKapuaId()); - Permission tmpPerm1 = permissionFactory.newPermission(new TestDomain().getName(), Actions.read, SYS_SCOPE_ID, getKapuaId()); - Permission tmpPerm2 = permissionFactory.newPermission(new TestDomain().getName(), Actions.write, SYS_SCOPE_ID, getKapuaId()); + Permission tmpPerm1 = new Permission(new TestDomain().getName(), Actions.read, SYS_SCOPE_ID, getKapuaId()); + Permission tmpPerm2 = new Permission(new TestDomain().getName(), Actions.write, SYS_SCOPE_ID, getKapuaId()); Assert.assertTrue(accPerm1.equals(accPerm1)); Assert.assertFalse(accPerm1.equals(null)); Assert.assertFalse(accPerm1.equals(Integer.valueOf(15))); @@ -1547,24 +1527,24 @@ public void checkAccessPermissionComparison() { public void permissionFactorySanityChecks() throws KapuaException { Permission tmpPerm = null; TestDomain tmpDomain = new TestDomain(); - tmpPerm = permissionFactory.newPermission(tmpDomain.getName(), Actions.read, SYS_SCOPE_ID); + tmpPerm = new Permission(tmpDomain.getName(), Actions.read, SYS_SCOPE_ID); Assert.assertNotNull(tmpPerm); Assert.assertNotNull(tmpPerm.getDomain()); Assert.assertEquals(tmpDomain.getName(), tmpPerm.getDomain()); Assert.assertEquals(Actions.read, tmpPerm.getAction()); - tmpPerm = permissionFactory.newPermission(tmpDomain.getName(), Actions.write, SYS_SCOPE_ID, getKapuaId(9)); + tmpPerm = new Permission(tmpDomain.getName(), Actions.write, SYS_SCOPE_ID, getKapuaId(9)); Assert.assertNotNull(tmpPerm); Assert.assertNotNull(tmpPerm.getDomain()); Assert.assertEquals(tmpDomain.getName(), tmpPerm.getDomain()); Assert.assertEquals(Actions.write, tmpPerm.getAction()); Assert.assertEquals(getKapuaId(9), tmpPerm.getGroupId()); Assert.assertFalse(tmpPerm.getForwardable()); - tmpPerm = permissionFactory.newPermission((String) null, Actions.execute, SYS_SCOPE_ID, getKapuaId(9), true); + tmpPerm = new Permission((String) null, Actions.execute, SYS_SCOPE_ID, getKapuaId(9), true); Assert.assertNotNull(tmpPerm); Assert.assertEquals(Actions.execute, tmpPerm.getAction()); Assert.assertTrue(tmpPerm.getForwardable()); tmpDomain.setName(null); - tmpPerm = permissionFactory.newPermission(tmpDomain.getName(), Actions.connect, SYS_SCOPE_ID, getKapuaId()); + tmpPerm = new Permission(tmpDomain.getName(), Actions.connect, SYS_SCOPE_ID, getKapuaId()); Assert.assertNotNull(tmpPerm); Assert.assertEquals(Actions.connect, tmpPerm.getAction()); } @@ -1574,44 +1554,46 @@ public void permissionFactorySanityChecks() throws KapuaException { // As such this step is of limited usefulness and should be taken with a grain of salt. @Then("I can compare permission objects") public void checkPermissionComparison() { - Permission perm1 = permissionFactory.newPermission("test_domain_1", Actions.read, getKapuaId(10), getKapuaId(100)); - Permission perm2 = permissionFactory.newPermission("test_domain_1", Actions.read, getKapuaId(10), getKapuaId(100)); + Permission perm1 = new Permission("test_domain_1", Actions.read, getKapuaId(10), getKapuaId(100)); + Permission perm2 = new Permission("test_domain_1", Actions.read, getKapuaId(10), getKapuaId(100)); Assert.assertTrue(perm1.equals(perm1)); Assert.assertFalse(perm1.equals(null)); Assert.assertFalse(perm1.equals(Integer.valueOf(10))); Assert.assertTrue(perm1.equals(perm2)); - perm1.setDomain(null); + perm1 = new Permission(null, perm1.getAction(), perm1.getTargetScopeId(), perm1.getGroupId(), perm1.getForwardable()); Assert.assertFalse(perm1.equals(perm2)); - perm2.setDomain(null); + perm2 = new Permission(null, perm2.getAction(), perm2.getTargetScopeId(), perm2.getGroupId(), perm2.getForwardable()); Assert.assertTrue(perm1.equals(perm2)); - perm1.setDomain("test_1"); + perm1 = new Permission("test_1", perm1.getAction(), perm1.getTargetScopeId(), perm1.getGroupId(), perm1.getForwardable()); Assert.assertFalse(perm1.equals(perm2)); - perm2.setDomain("test_2"); + perm2 = new Permission("test_2", perm2.getAction(), perm2.getTargetScopeId(), perm2.getGroupId(), perm2.getForwardable()); Assert.assertFalse(perm1.equals(perm2)); - perm1.setDomain("test"); - perm2.setDomain("test"); - perm1.setTargetScopeId(null); + perm1 = new Permission("test", perm1.getAction(), perm1.getTargetScopeId(), perm1.getGroupId(), perm1.getForwardable()); + perm2 = new Permission("test", perm2.getAction(), perm2.getTargetScopeId(), perm2.getGroupId(), perm2.getForwardable()); + Assert.assertTrue(perm1.equals(perm2)); + perm1 = new Permission(perm1.getDomain(), perm1.getAction(), null, perm1.getGroupId(), perm1.getForwardable()); Assert.assertFalse(perm1.equals(perm2)); - perm2.setTargetScopeId(null); + perm2 = new Permission(perm2.getDomain(), perm2.getAction(), null, perm2.getGroupId(), perm2.getForwardable()); Assert.assertTrue(perm1.equals(perm2)); - perm1.setTargetScopeId(getKapuaId(10)); + perm1 = new Permission(perm1.getDomain(), perm1.getAction(), getKapuaId(10), perm1.getGroupId(), perm1.getForwardable()); Assert.assertFalse(perm1.equals(perm2)); - perm2.setTargetScopeId(getKapuaId(15)); + perm2 = new Permission(perm2.getDomain(), perm2.getAction(), getKapuaId(15), perm2.getGroupId(), perm2.getForwardable()); Assert.assertFalse(perm1.equals(perm2)); - perm1.setTargetScopeId(getKapuaId(10)); - perm2.setTargetScopeId(getKapuaId(10)); - perm1.setGroupId(null); + perm1 = new Permission(perm1.getDomain(), perm1.getAction(), getKapuaId(10), perm1.getGroupId(), perm1.getForwardable()); + perm2 = new Permission(perm2.getDomain(), perm2.getAction(), getKapuaId(10), perm2.getGroupId(), perm2.getForwardable()); + Assert.assertTrue(perm1.equals(perm2)); + perm1 = new Permission(perm1.getDomain(), perm1.getAction(), perm1.getTargetScopeId(), null, perm1.getForwardable()); Assert.assertFalse(perm1.equals(perm2)); - perm2.setGroupId(null); + perm2 = new Permission(perm2.getDomain(), perm2.getAction(), perm2.getTargetScopeId(), null, perm2.getForwardable()); Assert.assertTrue(perm1.equals(perm2)); - perm1.setGroupId(getKapuaId(100)); + perm1 = new Permission(perm1.getDomain(), perm1.getAction(), perm1.getTargetScopeId(), getKapuaId(100), perm1.getForwardable()); Assert.assertFalse(perm1.equals(perm2)); - perm2.setGroupId(getKapuaId(101)); + perm2 = new Permission(perm2.getDomain(), perm2.getAction(), perm2.getTargetScopeId(), getKapuaId(101), perm2.getForwardable()); Assert.assertFalse(perm1.equals(perm2)); - perm2.setGroupId(getKapuaId(100)); + perm2 = new Permission(perm2.getDomain(), perm2.getAction(), perm2.getTargetScopeId(), getKapuaId(100), perm2.getForwardable()); Assert.assertTrue(perm1.equals(perm2)); - perm1.setAction(Actions.read); - perm2.setAction(Actions.write); + perm1 = new Permission(perm1.getDomain(), Actions.read, perm1.getTargetScopeId(), perm1.getGroupId(), perm1.getForwardable()); + perm2 = new Permission(perm2.getDomain(), Actions.write, perm2.getTargetScopeId(), perm2.getGroupId(), perm2.getForwardable()); Assert.assertFalse(perm1.equals(perm2)); } @@ -1619,10 +1601,10 @@ public void checkPermissionComparison() { public void accessRoleWithNameIsFinded(String roleName) throws Exception { try { primeException(); - RoleQuery roleQuery = roleFactory.newQuery(getCurrentScopeId()); + final KapuaQuery roleQuery = new KapuaQuery(getCurrentScopeId()); roleQuery.setPredicate(roleQuery.attributePredicate(KapuaNamedEntityAttributes.NAME, roleName)); RoleListResult roleList = roleService.query(roleQuery); - AccessRoleQuery accessRoleQuery = accessRoleFactory.newQuery(getCurrentScopeId()); + final KapuaQuery accessRoleQuery = new KapuaQuery(getCurrentScopeId()); accessRoleQuery.setPredicate(accessRoleQuery.attributePredicate(AccessRoleAttributes.ROLE_ID, roleList.getFirstItem().getId())); AccessRoleListResult searchAccessRole = accessRoleService.query(accessRoleQuery); Assert.assertTrue(searchAccessRole.getSize() > 0); @@ -1633,7 +1615,7 @@ public void accessRoleWithNameIsFinded(String roleName) throws Exception { @And("I create the roles") public void iCreateTheRoles(List roleNames) throws Exception { - RoleCreator roleCreator = roleFactory.newCreator(getCurrentScopeId()); + RoleCreator roleCreator = new RoleCreator(getCurrentScopeId()); ArrayList roleArrayList = new ArrayList(); stepData.remove(ROLE_LIST); Role role = null; @@ -1657,7 +1639,7 @@ public void iAddPermissionsToTheRole() throws Exception { Role role = (Role) stepData.get("Role"); Set permissions = (Set) stepData.get(PERMISSIONS); Set rolePermissionList = new HashSet<>(); - RolePermissionCreator rolePermissionCreator = rolePermissionFactory.newCreator(getCurrentScopeId()); + RolePermissionCreator rolePermissionCreator = new RolePermissionCreator(getCurrentScopeId()); for (Permission permission : permissions) { rolePermissionCreator.setPermission(permission); rolePermissionCreator.setRoleId(role.getId()); @@ -1680,7 +1662,7 @@ public void iAddAccessRolesToUser(String userName) throws Exception { List roleList = (List) stepData.get(ROLE_LIST); User user = (User) stepData.get("User"); Assert.assertEquals(userName, user.getName()); - AccessRoleCreator accessRoleCreator = accessRoleFactory.newCreator(getCurrentScopeId()); + AccessRoleCreator accessRoleCreator = new AccessRoleCreator(getCurrentScopeId()); for (Role role : roleList) { accessRoleCreator.setAccessInfoId(accessInfo.getId()); accessRoleCreator.setRoleId(role.getId()); @@ -1723,7 +1705,7 @@ public void iFindLastCreatedGroup(String groupName) throws Exception { public void iFindRoleWithName(String roleName) throws Exception { try { primeException(); - RoleQuery roleQuery = roleFactory.newQuery(getCurrentScopeId()); + final RoleQuery roleQuery = new RoleQuery(getCurrentScopeId()); roleQuery.setPredicate(roleQuery.attributePredicate(KapuaNamedEntityAttributes.NAME, roleName, AttributePredicate.Operator.EQUAL)); stepData.remove(ROLE_LIST_RESULT); stepData.remove("Role"); @@ -1738,7 +1720,7 @@ public void iFindRoleWithName(String roleName) throws Exception { @And("I create a group with name {string}") public void iCreateAGroupWithName(String groupName) throws Exception { - GroupCreator groupCreator = groupFactory.newCreator(getCurrentScopeId()); + GroupCreator groupCreator = new GroupCreator(getCurrentScopeId()); groupCreator.setName(groupName); try { primeException(); @@ -1752,7 +1734,7 @@ public void iCreateAGroupWithName(String groupName) throws Exception { @And("I try to create groups with invalid characters in name") public void iTryToCreateInvalidGroups() throws Exception { - GroupCreator groupCreator = groupFactory.newCreator(getCurrentScopeId()); + GroupCreator groupCreator = new GroupCreator(getCurrentScopeId()); String invalidCharacters = "!\"#$%&'()=»Ç>:;<-.,⁄@‹›€*ı–°·‚_±Œ„‰?“‘”’ÉØ∏{}|ÆæÒÔÓÌÏÎÍÅ«"; for (int i = 0; i < invalidCharacters.length(); i++) { String groupName = GROUP + invalidCharacters.charAt(i); @@ -1786,7 +1768,7 @@ public void iSearchForThePermissionsOfTheRole(String roleName) throws Exception Role role = (Role) stepData.get("Role"); ArrayList rolePermissionList = new ArrayList<>(); Assert.assertEquals(roleName, role.getName()); - RolePermissionQuery rolePermissionQuery = rolePermissionFactory.newQuery(getCurrentScopeId()); + final KapuaQuery rolePermissionQuery = new KapuaQuery(getCurrentScopeId()); rolePermissionQuery.setPredicate(rolePermissionQuery.attributePredicate(RolePermissionAttributes.ROLE_ID, role.getId(), AttributePredicate.Operator.EQUAL)); RolePermissionListResult rolePermissions = rolePermissionService.query(rolePermissionQuery); stepData.remove(ROLE_PERMISSIONS); @@ -1834,7 +1816,7 @@ public void iDeleteTheLastCreatedAdminRolePermissions() throws Exception { public void iCountTheAccessRolesFromUser(String userName) throws Exception { User lastUser = (User) stepData.get("User"); AccessInfo accessInfo = (AccessInfo) stepData.get(ACCESS_INFO); - AccessRoleQuery tmpQuery = accessRoleFactory.newQuery(getCurrentScopeId()); + final KapuaQuery tmpQuery = new KapuaQuery(getCurrentScopeId()); tmpQuery.setPredicate(tmpQuery.attributePredicate(AccessRoleAttributes.ACCESS_INFO_ID, accessInfo.getId(), AttributePredicate.Operator.EQUAL)); Assert.assertEquals(userName, lastUser.getName()); updateCount(() -> (int) accessRoleService.count(tmpQuery)); @@ -1846,7 +1828,7 @@ public void iSearchGrantedUserToRole() throws Exception { int grantedUsersCount = 0; try { primeException(); - AccessRoleQuery accessRoleQuery = accessRoleFactory.newQuery(getCurrentScopeId()); + final KapuaQuery accessRoleQuery = new KapuaQuery(getCurrentScopeId()); AccessRoleListResult accessRoleList = accessRoleService.query(accessRoleQuery); for (AccessRole a : accessRoleList.getItems()) { AccessInfo accessInfo = accessInfoService.find(getCurrentScopeId(), a.getAccessInfoId()); @@ -1880,7 +1862,7 @@ public void iFindGrantedUsersWithName(List grantedUsers) throws Excepti public void iFindSpecificRoleInChildAccount(String roleName, String accountName) throws Exception { Account account = (Account) stepData.get(LAST_ACCOUNT); Assert.assertEquals(accountName, account.getName()); - RoleQuery roleQuery = roleFactory.newQuery(account.getId()); + final RoleQuery roleQuery = new RoleQuery(account.getId()); roleQuery.setPredicate(roleQuery.attributePredicate(KapuaNamedEntityAttributes.NAME, roleName, AttributePredicate.Operator.EQUAL)); RoleListResult childRolesList = roleService.query(roleQuery); stepData.put("ChildRolesList", childRolesList); @@ -1891,7 +1873,7 @@ public void iCreateRoleInSubaccount(String roleName, String accountName) throws Account account = (Account) stepData.get(LAST_ACCOUNT); Assert.assertEquals(accountName, account.getName()); RoleCreator roleCreator = null; - roleCreator = roleFactory.newCreator(account.getId()); + roleCreator = new RoleCreator(account.getId()); roleCreator.setName(roleName); try { Role role = roleService.create(roleCreator); @@ -1917,9 +1899,9 @@ public void iCreateTheFollowingRolePermissionInSubaccount(String accountName, Li Assert.assertNotNull(tmpCPerm.getScopeId()); Assert.assertNotNull(tmpCPerm.getAction()); domain.setScopeId(tmpCPerm.getScopeId()); - RolePermissionCreator rolePermissionCreator = rolePermissionFactory.newCreator(account.getId()); + RolePermissionCreator rolePermissionCreator = new RolePermissionCreator(account.getId()); rolePermissionCreator.setRoleId(role.getId()); - rolePermissionCreator.setPermission(permissionFactory.newPermission(domain.getDomain().getName(), tmpCPerm.getAction(), tmpCPerm.getTargetScopeId())); + rolePermissionCreator.setPermission(new Permission(domain.getDomain().getName(), tmpCPerm.getAction(), tmpCPerm.getTargetScopeId())); try { stepData.remove("ChildAccountRolePermissions"); rolePermission = rolePermissionService.create(rolePermissionCreator); @@ -1938,7 +1920,7 @@ public void iSearchForThePermissionsOfFoundedRoleInSubaccount(String roleName, S Account account = (Account) stepData.get(LAST_ACCOUNT); Assert.assertEquals(accountName, account.getName()); ArrayList rolePermissionList = new ArrayList<>(); - RolePermissionQuery rolePermissionQuery = rolePermissionFactory.newQuery(account.getId()); + final KapuaQuery rolePermissionQuery = new KapuaQuery(account.getId()); rolePermissionQuery.setPredicate(rolePermissionQuery.attributePredicate(RolePermissionAttributes.ROLE_ID, role.getId(), AttributePredicate.Operator.EQUAL)); RolePermissionListResult rolePermissions = rolePermissionService.query(rolePermissionQuery); stepData.remove(CHILD_ACCOUNT_ROLE_PERMISSION); @@ -1968,7 +1950,7 @@ public void iAddAccessRoleToUserInChildAccount(String roleName, String childUser Account account = (Account) stepData.get(LAST_ACCOUNT); User childUser = (User) stepData.get("ChildAccountUser"); Role role = (Role) stepData.get("Role"); - AccessRoleCreator accessRoleCreator = accessRoleFactory.newCreator(account.getId()); + AccessRoleCreator accessRoleCreator = new AccessRoleCreator(account.getId()); accessRoleCreator.setAccessInfoId(accessInfo.getId()); accessRoleCreator.setRoleId(role.getId()); stepData.put("ChildAccountAccessRoleCreator", accessRoleCreator); @@ -1990,7 +1972,7 @@ public void iAddAccessRoleToUserInChildAccount(String roleName, String childUser public void iCreateTheAccessInfoEntityInChildAccount(String accountName) throws Exception { Account account = (Account) stepData.get(LAST_ACCOUNT); User tmpUser = (User) stepData.get("ChildAccountUser"); - AccessInfoCreator accessInfoCreator = accessInfoFactory.newCreator(account.getId()); + AccessInfoCreator accessInfoCreator = new AccessInfoCreator(account.getId()); accessInfoCreator.setUserId(tmpUser.getId()); Assert.assertEquals(accountName, account.getName()); Set permissions = (Set) stepData.get(PERMISSIONS); @@ -2021,7 +2003,7 @@ public void iSearchForAccessRolesFromTheLastUser(String userName) throws Excepti AccessInfo accessInfo = (AccessInfo) stepData.get(ACCESS_INFO); User user = (User) stepData.get("User"); Assert.assertEquals(userName, user.getName()); - AccessRoleQuery accessRoleQuery = accessRoleFactory.newQuery(getCurrentScopeId()); + final KapuaQuery accessRoleQuery = new KapuaQuery(getCurrentScopeId()); accessRoleQuery.setPredicate(accessRoleQuery.attributePredicate(AccessRoleAttributes.ACCESS_INFO_ID, accessInfo.getId(), AttributePredicate.Operator.EQUAL)); try { primeException(); @@ -2052,7 +2034,7 @@ public void iCountTheAccessRolesFromUserInChildAccount(String accountName) throw Account account = (Account) stepData.get(LAST_ACCOUNT); AccessInfo accessInfo = (AccessInfo) stepData.get(CHILD_ACCOUNT_ACCESS_INFO); Assert.assertEquals(accountName, account.getName()); - AccessRoleQuery tmpQuery = accessRoleFactory.newQuery(account.getId()); + final KapuaQuery tmpQuery = new KapuaQuery(account.getId()); tmpQuery.setPredicate(tmpQuery.attributePredicate(AccessRoleAttributes.ACCESS_INFO_ID, accessInfo.getId(), AttributePredicate.Operator.EQUAL)); updateCount(() -> (int) accessRoleService.count(tmpQuery)); } @@ -2075,7 +2057,7 @@ public void iUpdateTheRoleName(String newRoleName) throws Exception { public void iCreateTheAccessInfoEntities() throws Exception { KapuaId currScope = (KapuaId) stepData.get(LAST_ACCOUNT_ID); ArrayList userArray = (ArrayList) stepData.get("UserList"); - AccessInfoCreator accessInfoCreator = accessInfoFactory.newCreator(currScope); + AccessInfoCreator accessInfoCreator = new AccessInfoCreator(currScope); ArrayList accessInfoList = new ArrayList<>(); Set permissions = (Set) stepData.get(PERMISSIONS); Set roleIds = (Set) stepData.get(ROLE_IDS); @@ -2107,7 +2089,7 @@ public void iCreateTheAccessInfoEntities() throws Exception { @Given("I prepare a role creator with name {string} and description {string}") public void iPrepareARoleCreatorWithNameAndDescription(String name, String description) { - RoleCreator roleCreator = roleFactory.newCreator(SYS_SCOPE_ID); + RoleCreator roleCreator = new RoleCreator(SYS_SCOPE_ID); roleCreator.setName(name); roleCreator.setDescription(description); stepData.put(ROLE_CREATOR, roleCreator); @@ -2133,7 +2115,7 @@ public void iCreateRoles(int num) throws Exception { primeException(); try { for (int i = 0; i < num; i++) { - RoleCreator tmpCreator = roleFactory.newCreator(getCurrentScopeId()); + RoleCreator tmpCreator = new RoleCreator(getCurrentScopeId()); tmpCreator.setName(String.format("TestRoleNum%d", i)); roleService.create(tmpCreator); } @@ -2144,7 +2126,7 @@ public void iCreateRoles(int num) throws Exception { @When("I count the roles in the database") public void iCountTheRolesInTheDatabase() throws Exception { - updateCount(() -> (int) (roleService.count(roleFactory.newQuery(getCurrentScopeId())) - 1)); + updateCount(() -> (int) (roleService.count(new RoleQuery(getCurrentScopeId())) - 1)); } @And("I update the role description to {string}") @@ -2179,7 +2161,7 @@ public void iDeleteTheRoleWithNameAndDescription(String roleName, String roleDes public void iFindARoleWithDescription(String roleDesc) throws Throwable { try { primeException(); - RoleQuery roleQuery = roleFactory.newQuery(getCurrentScopeId()); + RoleQuery roleQuery = new RoleQuery(getCurrentScopeId()); roleQuery.setPredicate(roleQuery.attributePredicate(KapuaNamedEntityAttributes.DESCRIPTION, roleDesc, AttributePredicate.Operator.EQUAL)); stepData.remove(ROLE_LIST_RESULT); stepData.remove(ROLE_FOUND); @@ -2193,7 +2175,7 @@ public void iFindARoleWithDescription(String roleDesc) throws Throwable { @Given("I try to create roles with invalid characters {string} in name") public void iTryToCreateRolesWithInvalidCharactersInName(String invalidCharacters) throws Exception { - RoleCreator roleCreator = roleFactory.newCreator(SYS_SCOPE_ID); + RoleCreator roleCreator = new RoleCreator(SYS_SCOPE_ID); for (int i = 0; i < invalidCharacters.length(); i++) { String roleName = ROLE_NAME + invalidCharacters.charAt(i); roleCreator.setName(roleName); @@ -2210,7 +2192,7 @@ public void iTryToCreateRolesWithInvalidCharactersInName(String invalidCharacter @Given("I try to create roles with invalid characters {string} in description") public void iTryToCreateRolesWithInvalidCharactersInDescription(String invalidCharacters) throws Exception { - RoleCreator roleCreator = roleFactory.newCreator(SYS_SCOPE_ID); + RoleCreator roleCreator = new RoleCreator(SYS_SCOPE_ID); for (int i = 0; i < invalidCharacters.length(); i++) { String roleDescription = "roleDescription" + invalidCharacters.charAt(i); roleCreator.setDescription(roleDescription); @@ -2228,7 +2210,7 @@ public void iTryToCreateRolesWithInvalidCharactersInDescription(String invalidCh @Then("I update the role name with special characters {string}") public void iUpdateTheRoleNameWithSpecialCharacters(String invalidSymbols) throws Exception { - RoleCreator roleCreator = roleFactory.newCreator(SYS_SCOPE_ID); + RoleCreator roleCreator = new RoleCreator(SYS_SCOPE_ID); for (int i = 0; i < invalidSymbols.length(); i++) { String roleName = ROLE_NAME + invalidSymbols.charAt(i); roleCreator.setName(ROLE_NAME + i); @@ -2248,7 +2230,7 @@ public void iUpdateTheRoleNameWithSpecialCharacters(String invalidSymbols) throw @And("I change the group name from {string} to {string}") public void iChangeTheGroupNameTo(String groupName, String newGroupName) throws Exception { try { - GroupQuery query = groupFactory.newQuery(SYS_SCOPE_ID); + final KapuaQuery query = new KapuaQuery(SYS_SCOPE_ID); query.setPredicate(query.attributePredicate(KapuaNamedEntityAttributes.NAME, groupName, AttributePredicate.Operator.EQUAL)); GroupListResult queryResult = groupService.query(query); Group group = queryResult.getFirstItem(); @@ -2263,7 +2245,7 @@ public void iChangeTheGroupNameTo(String groupName, String newGroupName) throws @And("I change the description of group with name {string} to {string}") public void iChangeTheGroupDescriptionTo(String groupName, String groupDescription) throws Exception { try { - GroupQuery query = groupFactory.newQuery(SYS_SCOPE_ID); + final KapuaQuery query = new KapuaQuery(SYS_SCOPE_ID); query.setPredicate(query.attributePredicate(KapuaNamedEntityAttributes.NAME, groupName, AttributePredicate.Operator.EQUAL)); GroupListResult queryResult = groupService.query(query); Group group = queryResult.getFirstItem(); @@ -2278,7 +2260,7 @@ public void iChangeTheGroupDescriptionTo(String groupName, String groupDescripti public void iSearchForAGroupNamed(String groupName) throws Exception { try { stepData.remove(GROUP_SECOND); - GroupQuery query = groupFactory.newQuery(SYS_SCOPE_ID); + final KapuaQuery query = new KapuaQuery(SYS_SCOPE_ID); query.setPredicate(query.attributePredicate(KapuaNamedEntityAttributes.NAME, groupName, AttributePredicate.Operator.EQUAL)); GroupListResult queryResult = groupService.query(query); Group foundGroup = queryResult.getFirstItem(); @@ -2303,7 +2285,7 @@ public void iChangeDevicesGroup() throws Exception { @Given("I create the group with name {string} and description {string}") public void iCreateTheGroupWithName(String groupName, String groupDescription) throws Exception { - GroupCreator groupCreator = groupFactory.newCreator(getCurrentScopeId()); + GroupCreator groupCreator = new GroupCreator(getCurrentScopeId()); groupCreator.setName(groupName); groupCreator.setDescription(groupDescription); try { @@ -2369,7 +2351,7 @@ public void iUpdateTheGroupDescriptionFromTo(String description1, String descrip @And("I try to create the group with invalid characters {string} in name and description {string}") public void iTryToCreateTheGroupWithInvalidCharactersInNameAndDescription(String invalidSymbols, String description) throws Exception { - GroupCreator groupCreator = groupFactory.newCreator(getCurrentScopeId()); + GroupCreator groupCreator = new GroupCreator(getCurrentScopeId()); for (int i = 0; i < invalidSymbols.length(); i++) { String groupName = GROUP_NAME + invalidSymbols.charAt(i); groupCreator.setName(groupName); @@ -2405,7 +2387,7 @@ public void iUpdateTheGroupNameFromToNameWithSpecialCharacters(String name, Stri @Given("I try to create the group with special characters {string} in description") public void iTryToCreateTheGroupWithSpecialCharactersInDescription(String invalidSymbols) throws Exception { - GroupCreator groupCreator = groupFactory.newCreator(SYS_SCOPE_ID); + GroupCreator groupCreator = new GroupCreator(SYS_SCOPE_ID); for (int i = 0; i < invalidSymbols.length(); i++) { String groupDescription = "description" + invalidSymbols.charAt(i); groupCreator.setDescription(groupDescription); @@ -2423,7 +2405,7 @@ public void iTryToCreateTheGroupWithSpecialCharactersInDescription(String invali @When("I update the group description to description with special characters {string}") public void iUpdateTheGroupDescriptionFromToDescriptionWithSpecialCharacters(String invalidSymbols) throws Exception { - GroupCreator groupCreator = groupFactory.newCreator(SYS_SCOPE_ID); + GroupCreator groupCreator = new GroupCreator(SYS_SCOPE_ID); for (int i = 0; i < invalidSymbols.length(); i++) { String groupDescription = "description" + invalidSymbols.charAt(i); groupCreator.setDescription(groupDescription); diff --git a/service/security/test/pom.xml b/service/security/test/pom.xml index 2aca64b4dcd..18d4475552b 100644 --- a/service/security/test/pom.xml +++ b/service/security/test/pom.xml @@ -20,7 +20,7 @@ org.eclipse.kapua kapua-security - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-security-test diff --git a/service/security/test/src/test/java/org/eclipse/kapua/service/security/test/SecurityLocatorConfiguration.java b/service/security/test/src/test/java/org/eclipse/kapua/service/security/test/SecurityLocatorConfiguration.java index 786b191dc6e..eb8e97f4b26 100644 --- a/service/security/test/src/test/java/org/eclipse/kapua/service/security/test/SecurityLocatorConfiguration.java +++ b/service/security/test/src/test/java/org/eclipse/kapua/service/security/test/SecurityLocatorConfiguration.java @@ -32,13 +32,11 @@ import org.eclipse.kapua.commons.metric.CommonsMetric; import org.eclipse.kapua.commons.metric.MetricsService; import org.eclipse.kapua.commons.metric.MetricsServiceImpl; -import org.eclipse.kapua.commons.model.query.QueryFactoryImpl; import org.eclipse.kapua.commons.service.event.store.internal.EventStoreRecordImplJpaRepository; import org.eclipse.kapua.commons.service.internal.cache.CacheManagerProvider; import org.eclipse.kapua.commons.setting.system.SystemSetting; import org.eclipse.kapua.commons.util.xml.XmlUtil; import org.eclipse.kapua.locator.KapuaLocator; -import org.eclipse.kapua.model.query.QueryFactory; import org.eclipse.kapua.qa.common.MockedLocator; import org.eclipse.kapua.qa.common.TestJAXBContextProvider; import org.eclipse.kapua.service.authentication.credential.CredentialFactory; @@ -74,7 +72,6 @@ import org.eclipse.kapua.service.authorization.group.shiro.GroupImplJpaRepository; import org.eclipse.kapua.service.authorization.group.shiro.GroupServiceImpl; import org.eclipse.kapua.service.authorization.permission.Permission; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; import org.eclipse.kapua.service.authorization.permission.shiro.PermissionValidator; import org.eclipse.kapua.service.authorization.role.RoleFactory; import org.eclipse.kapua.service.authorization.role.RolePermissionFactory; @@ -137,19 +134,13 @@ protected void configure() { // skip } - bind(QueryFactory.class).toInstance(new QueryFactoryImpl()); bind(KapuaJpaRepositoryConfiguration.class).toInstance(new KapuaJpaRepositoryConfiguration()); bind(AuthorizationService.class).toInstance(mockedAuthorization); - // Inject mocked Permission Factory - PermissionFactory mockPermissionFactory = Mockito.mock(PermissionFactory.class); - bind(PermissionFactory.class).toInstance(mockPermissionFactory); - // Inject actual Role service related services final KapuaJpaRepositoryConfiguration jpaRepoConfig = new KapuaJpaRepositoryConfiguration(); final TxManager txManager = new KapuaJpaTxManagerFactory(maxInsertAttempts).create("kapua-authorization"); bind(RoleService.class).toInstance(new RoleServiceImpl( - mockPermissionFactory, mockedAuthorization, new RolePermissionFactoryImpl(), new AccessRoleFactoryImpl(), @@ -166,7 +157,6 @@ protected void configure() { bind(RolePermissionFactory.class).toInstance(new RolePermissionFactoryImpl()); bind(GroupService.class).toInstance(new GroupServiceImpl( - mockPermissionFactory, mockedAuthorization, Mockito.mock(ServiceConfigurationManager.class), txManager, @@ -192,7 +182,6 @@ protected void configure() { bind(CredentialService.class).toInstance(new CredentialServiceImpl( credentialServiceConfigurationManager, mockedAuthorization, - mockPermissionFactory, txManager, credentialRepository, credentialFactory, @@ -232,7 +221,6 @@ passwordValidator, new KapuaAuthenticationSetting(), bind(UserService.class).toInstance(new UserServiceImpl( Mockito.mock(ServiceConfigurationManager.class), mockedAuthorization, - mockPermissionFactory, new KapuaJpaTxManagerFactory(maxInsertAttempts).create("kapua-user"), new UserImplJpaRepository(jpaRepoConfig), userFactory, diff --git a/service/stream/api/pom.xml b/service/stream/api/pom.xml index e1f47334393..1f2e4c90273 100644 --- a/service/stream/api/pom.xml +++ b/service/stream/api/pom.xml @@ -18,7 +18,7 @@ kapua-stream org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-stream-api diff --git a/service/stream/internal/pom.xml b/service/stream/internal/pom.xml index fb6e01f4527..c3dd3c32ba8 100644 --- a/service/stream/internal/pom.xml +++ b/service/stream/internal/pom.xml @@ -18,7 +18,7 @@ kapua-stream org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-stream-internal diff --git a/service/stream/internal/src/main/java/org/eclipse/kapua/service/stream/internal/StreamServiceImpl.java b/service/stream/internal/src/main/java/org/eclipse/kapua/service/stream/internal/StreamServiceImpl.java index 5d526827e8f..86a1bfe0243 100644 --- a/service/stream/internal/src/main/java/org/eclipse/kapua/service/stream/internal/StreamServiceImpl.java +++ b/service/stream/internal/src/main/java/org/eclipse/kapua/service/stream/internal/StreamServiceImpl.java @@ -13,7 +13,13 @@ *******************************************************************************/ package org.eclipse.kapua.service.stream.internal; -import com.google.common.base.Strings; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +import javax.inject.Inject; +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaEntityNotFoundException; import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.KapuaIllegalArgumentException; @@ -23,7 +29,7 @@ import org.eclipse.kapua.message.device.data.KapuaDataMessage; import org.eclipse.kapua.model.domain.Actions; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; +import org.eclipse.kapua.service.authorization.permission.Permission; import org.eclipse.kapua.service.device.call.kura.exception.KuraDeviceCallErrorCodes; import org.eclipse.kapua.service.device.call.kura.exception.KuraDeviceCallException; import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponseMessage; @@ -33,7 +39,6 @@ import org.eclipse.kapua.service.device.registry.DeviceRegistryService; import org.eclipse.kapua.service.endpoint.EndpointInfo; import org.eclipse.kapua.service.endpoint.EndpointInfoAttributes; -import org.eclipse.kapua.service.endpoint.EndpointInfoFactory; import org.eclipse.kapua.service.endpoint.EndpointInfoQuery; import org.eclipse.kapua.service.endpoint.EndpointInfoService; import org.eclipse.kapua.service.stream.StreamService; @@ -45,11 +50,7 @@ import org.eclipse.kapua.transport.exception.TransportClientGetException; import org.eclipse.kapua.transport.message.TransportMessage; -import javax.inject.Inject; -import javax.inject.Singleton; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; +import com.google.common.base.Strings; /** * {@link StreamService} implementation. @@ -60,27 +61,21 @@ public class StreamServiceImpl implements StreamService { private final AuthorizationService authorizationService; - private final PermissionFactory permissionFactory; private final DeviceRegistryService deviceRegistryService; private final EndpointInfoService endpointInfoService; - private final EndpointInfoFactory endpointInfoFactory; private final TransportClientFactory transportClientFactory; private final TranslatorHub translatorHub; @Inject public StreamServiceImpl( AuthorizationService authorizationService, - PermissionFactory permissionFactory, DeviceRegistryService deviceRegistryService, EndpointInfoService endpointInfoService, - EndpointInfoFactory endpointInfoFactory, TransportClientFactory transportClientFactory, TranslatorHub translatorHub) { this.authorizationService = authorizationService; - this.permissionFactory = permissionFactory; this.deviceRegistryService = deviceRegistryService; this.endpointInfoService = endpointInfoService; - this.endpointInfoFactory = endpointInfoFactory; this.transportClientFactory = transportClientFactory; this.translatorHub = translatorHub; } @@ -92,7 +87,7 @@ public StreamServiceImpl( ArgumentValidator.notNull(kapuaDataMessage.getScopeId(), "dataMessage.scopeId"); ArgumentValidator.notNull(kapuaDataMessage.getChannel(), "dataMessage.channel"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.STREAM, Actions.write, kapuaDataMessage.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.STREAM, Actions.write, kapuaDataMessage.getScopeId())); // Do publish try (TransportFacade transportFacade = borrowClient(kapuaDataMessage)) { // Get Kura to transport translator for the request and vice versa @@ -119,9 +114,11 @@ public StreamServiceImpl( /** * Picks a {@link TransportFacade} to send the {@link KuraResponseMessage}. * - * @param kapuaDataMessage The K + * @param kapuaDataMessage + * The K * @return The {@link TransportFacade} to use to send the {@link KuraDataMessage}. - * @throws KuraDeviceCallException If getting the {@link TransportFacade} causes any {@link Exception}. + * @throws KuraDeviceCallException + * If getting the {@link TransportFacade} causes any {@link Exception}. * @since 1.0.0 */ protected TransportFacade borrowClient(KapuaDataMessage kapuaDataMessage) throws KuraDeviceCallException { @@ -159,11 +156,15 @@ public StreamServiceImpl( *
      • Both specified: The {@link Device#getClientId()} and the {@link KapuaDataMessage#getClientId()} must match
      • * * - * @param dataMessage The {@link KapuaDataMessage} to publish + * @param dataMessage + * The {@link KapuaDataMessage} to publish * @return The {@link Device} matching the {@link KapuaDataMessage#getDeviceId()} or {@link KapuaDataMessage#getClientId()} - * @throws KapuaEntityNotFoundException if {@link KapuaDataMessage#getDeviceId()} does not match any existing {@link Device} - * @throws KapuaIllegalArgumentException if {@link KapuaDataMessage#getClientId()} does not match the {@link Device#getClientId()} - * @throws KapuaException If any other error occurs. + * @throws KapuaEntityNotFoundException + * if {@link KapuaDataMessage#getDeviceId()} does not match any existing {@link Device} + * @throws KapuaIllegalArgumentException + * if {@link KapuaDataMessage#getClientId()} does not match the {@link Device#getClientId()} + * @throws KapuaException + * If any other error occurs. * @since 1.2.0 */ private Device checkDeviceInfo(KapuaDataMessage dataMessage) throws KapuaException { @@ -187,14 +188,16 @@ private Device checkDeviceInfo(KapuaDataMessage dataMessage) throws KapuaExcepti /** * Looks for the available {@link EndpointInfo} with {@link EndpointInfo#getSchema()} = "mqtt" * - * @param dataMessage The {@link KapuaDataMessage} to publish + * @param dataMessage + * The {@link KapuaDataMessage} to publish * @return The {@link String} {@link java.net.URI} to connect to. - * @throws KapuaException If no {@link EndpointInfo} is available + * @throws KapuaException + * If no {@link EndpointInfo} is available * @since 1.2.0 */ private String getEndpointInfoDNS(KapuaDataMessage dataMessage) throws KapuaException { String serverURI; - EndpointInfoQuery query = endpointInfoFactory.newQuery(dataMessage.getScopeId()); + EndpointInfoQuery query = new EndpointInfoQuery(dataMessage.getScopeId()); query.setPredicate( query.andPredicate( query.attributePredicate(EndpointInfoAttributes.SCHEMA, "mqtt"), @@ -210,16 +213,20 @@ private String getEndpointInfoDNS(KapuaDataMessage dataMessage) throws KapuaExce return serverURI; } - /** * Gets the translator for the given {@link Message} types. * - * @param from The {@link Message} type from which to translate. - * @param to The {@link Message} type to which to translate. - * @param The {@link Message} {@code class}from which to translate. - * @param The {@link Message} {@code class} to which to translate. + * @param from + * The {@link Message} type from which to translate. + * @param to + * The {@link Message} type to which to translate. + * @param + * The {@link Message} {@code class}from which to translate. + * @param + * The {@link Message} {@code class} to which to translate. * @return The {@link Translator} found. - * @throws KuraDeviceCallException If error occurs while loojing for the {@link Translator}. + * @throws KuraDeviceCallException + * If error occurs while loojing for the {@link Translator}. * @since 1.0.0 */ protected , T extends Message> Translator getTranslator(Class from, Class to) throws KuraDeviceCallException { diff --git a/service/stream/pom.xml b/service/stream/pom.xml index 0a316c3fc9b..b439a7c140e 100644 --- a/service/stream/pom.xml +++ b/service/stream/pom.xml @@ -16,7 +16,7 @@ kapua-service org.eclipse.kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT 4.0.0 diff --git a/service/system/api/pom.xml b/service/system/api/pom.xml index 493a801d368..4638249277e 100644 --- a/service/system/api/pom.xml +++ b/service/system/api/pom.xml @@ -17,7 +17,7 @@ org.eclipse.kapua kapua-system - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-system-api diff --git a/service/system/api/src/main/java/org/eclipse/kapua/service/systeminfo/SystemInfo.java b/service/system/api/src/main/java/org/eclipse/kapua/service/systeminfo/SystemInfo.java index fbc4a0f0726..b18de68348b 100644 --- a/service/system/api/src/main/java/org/eclipse/kapua/service/systeminfo/SystemInfo.java +++ b/service/system/api/src/main/java/org/eclipse/kapua/service/systeminfo/SystemInfo.java @@ -27,30 +27,58 @@ */ @XmlRootElement(name = "systemInfo") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = SystemInfoXmlRegistry.class, factoryMethod = "newSystemInfo") -public interface SystemInfo { +@XmlType +public class SystemInfo { + + private String version; + private String buildNumber; + private String buildDate; + private String buildBranch; + private String buildRevision; + @XmlElement(name = "version") - String getVersion(); + public String getVersion() { + return version; + } - void setVersion(String version); + public void setVersion(String version) { + this.version = version; + } @XmlElement(name = "revision") - String getRevision(); + public String getRevision() { + return buildRevision; + } - void setRevision(String revision); + public void setRevision(String revision) { + this.buildRevision = revision; + } @XmlElement(name = "buildDate") - String getBuildTimestamp(); + public String getBuildTimestamp() { + return buildDate; + } - void setBuildTimestamp(String buildDate); + public void setBuildTimestamp(String buildDate) { + this.buildDate = buildDate; + } @XmlElement(name = "buildBranch") - String getBuildBranch(); + public String getBuildBranch() { + return buildBranch; + } - void setBuildBranch(String buildBranch); + public void setBuildBranch(String buildBranch) { + this.buildBranch = buildBranch; + } @XmlElement(name = "buildNumber") - String getBuildNumber(); + public String getBuildNumber() { + return buildNumber; + } + + public void setBuildNumber(String buildNumber) { + this.buildNumber = buildNumber; + } - void setBuildNumber(String buildNumber); } diff --git a/service/system/api/src/main/java/org/eclipse/kapua/service/systeminfo/SystemInfoFactory.java b/service/system/api/src/main/java/org/eclipse/kapua/service/systeminfo/SystemInfoFactory.java deleted file mode 100644 index 08b4f0c2de2..00000000000 --- a/service/system/api/src/main/java/org/eclipse/kapua/service/systeminfo/SystemInfoFactory.java +++ /dev/null @@ -1,19 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2023, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.systeminfo; - -import org.eclipse.kapua.model.KapuaObjectFactory; - -public interface SystemInfoFactory extends KapuaObjectFactory { - SystemInfo newSystemInfo(); -} diff --git a/service/system/api/src/main/java/org/eclipse/kapua/service/systeminfo/SystemInfoXmlRegistry.java b/service/system/api/src/main/java/org/eclipse/kapua/service/systeminfo/SystemInfoXmlRegistry.java deleted file mode 100644 index d0a6c602c9c..00000000000 --- a/service/system/api/src/main/java/org/eclipse/kapua/service/systeminfo/SystemInfoXmlRegistry.java +++ /dev/null @@ -1,33 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2023, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.systeminfo; - -import org.eclipse.kapua.locator.KapuaLocator; - -import javax.xml.bind.annotation.XmlRegistry; - -@XmlRegistry -public class SystemInfoXmlRegistry { - - private final SystemInfoFactory systemInfoFactory = KapuaLocator.getInstance().getFactory(SystemInfoFactory.class); - - - /** - * Creates a new SystemInfo instance. - * - * @return new SystemInfo instance. - */ - public SystemInfo newSystemInfo() { - return systemInfoFactory.newSystemInfo(); - } -} diff --git a/service/system/internal/pom.xml b/service/system/internal/pom.xml index e78e48bb76f..22a81ebf0cf 100644 --- a/service/system/internal/pom.xml +++ b/service/system/internal/pom.xml @@ -17,7 +17,7 @@ org.eclipse.kapua kapua-system - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-system-internal diff --git a/service/system/internal/src/main/java/org/eclipse/kapua/service/systeminfo/internal/SystemInfoFactoryImpl.java b/service/system/internal/src/main/java/org/eclipse/kapua/service/systeminfo/internal/SystemInfoFactoryImpl.java deleted file mode 100644 index a983d397cf7..00000000000 --- a/service/system/internal/src/main/java/org/eclipse/kapua/service/systeminfo/internal/SystemInfoFactoryImpl.java +++ /dev/null @@ -1,26 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2023, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.systeminfo.internal; - -import org.eclipse.kapua.service.systeminfo.SystemInfo; -import org.eclipse.kapua.service.systeminfo.SystemInfoFactory; - -import javax.inject.Singleton; - -@Singleton -public class SystemInfoFactoryImpl implements SystemInfoFactory { - @Override - public SystemInfo newSystemInfo() { - return new SystemInfoImpl(); - } -} diff --git a/service/system/internal/src/main/java/org/eclipse/kapua/service/systeminfo/internal/SystemInfoImpl.java b/service/system/internal/src/main/java/org/eclipse/kapua/service/systeminfo/internal/SystemInfoImpl.java deleted file mode 100644 index 7ed2a5323c8..00000000000 --- a/service/system/internal/src/main/java/org/eclipse/kapua/service/systeminfo/internal/SystemInfoImpl.java +++ /dev/null @@ -1,83 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2023, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.systeminfo.internal; - -import org.eclipse.kapua.service.systeminfo.SystemInfo; - -public class SystemInfoImpl implements SystemInfo { - private String version; - private String buildNumber; - private String buildDate; - private String buildBranch; - private String buildRevision; - - - @Override - public String getVersion() { - return version; - } - - - @Override - public void setVersion(String version) { - this.version = version; - } - - - @Override - public String getRevision() { - return buildRevision; - } - - - @Override - public void setRevision(String revision) { - this.buildRevision = revision; - } - - - @Override - public String getBuildTimestamp() { - return buildDate; - } - - - @Override - public void setBuildTimestamp(String buildDate) { - this.buildDate = buildDate; - } - - - @Override - public String getBuildNumber() { - return buildNumber; - } - - - @Override - public void setBuildNumber(String buildNumber) { - this.buildNumber = buildNumber; - } - - - @Override - public String getBuildBranch() { - return buildBranch; - } - - - @Override - public void setBuildBranch(String buildBranch) { - this.buildBranch = buildBranch; - } -} \ No newline at end of file diff --git a/service/system/internal/src/main/java/org/eclipse/kapua/service/systeminfo/internal/SystemInfoModule.java b/service/system/internal/src/main/java/org/eclipse/kapua/service/systeminfo/internal/SystemInfoModule.java index 236cb4abab9..591fdf42ca1 100644 --- a/service/system/internal/src/main/java/org/eclipse/kapua/service/systeminfo/internal/SystemInfoModule.java +++ b/service/system/internal/src/main/java/org/eclipse/kapua/service/systeminfo/internal/SystemInfoModule.java @@ -14,14 +14,13 @@ import org.eclipse.kapua.commons.core.AbstractKapuaModule; import org.eclipse.kapua.commons.setting.system.SystemSetting; -import org.eclipse.kapua.service.systeminfo.SystemInfoFactory; import org.eclipse.kapua.service.systeminfo.SystemInfoService; public class SystemInfoModule extends AbstractKapuaModule { + @Override protected void configureModule() { bind(SystemInfoService.class).to(SystemInfoServiceImpl.class); - bind(SystemInfoFactory.class).to(SystemInfoFactoryImpl.class); bind(SystemSetting.class).toInstance(SystemSetting.getInstance()); } } diff --git a/service/system/internal/src/main/java/org/eclipse/kapua/service/systeminfo/internal/SystemInfoServiceImpl.java b/service/system/internal/src/main/java/org/eclipse/kapua/service/systeminfo/internal/SystemInfoServiceImpl.java index 42f8236f8e2..fe9b4bee560 100644 --- a/service/system/internal/src/main/java/org/eclipse/kapua/service/systeminfo/internal/SystemInfoServiceImpl.java +++ b/service/system/internal/src/main/java/org/eclipse/kapua/service/systeminfo/internal/SystemInfoServiceImpl.java @@ -12,24 +12,21 @@ *******************************************************************************/ package org.eclipse.kapua.service.systeminfo.internal; +import javax.inject.Inject; +import javax.inject.Singleton; + import org.eclipse.kapua.commons.setting.system.SystemSetting; import org.eclipse.kapua.commons.setting.system.SystemSettingKey; import org.eclipse.kapua.service.systeminfo.SystemInfo; -import org.eclipse.kapua.service.systeminfo.SystemInfoFactory; import org.eclipse.kapua.service.systeminfo.SystemInfoService; -import javax.inject.Inject; -import javax.inject.Singleton; - @Singleton public class SystemInfoServiceImpl implements SystemInfoService { - private final SystemInfoFactory systemInfoFactory; private final SystemSetting systemSetting; @Inject - public SystemInfoServiceImpl(SystemInfoFactory systemInfoFactory, SystemSetting systemSetting) { - this.systemInfoFactory = systemInfoFactory; + public SystemInfoServiceImpl(SystemSetting systemSetting) { this.systemSetting = systemSetting; } @@ -41,7 +38,7 @@ public SystemInfo getSystemInfo() { String timestamp = systemSetting.getString(SystemSettingKey.BUILD_TIMESTAMP); String buildNumber = systemSetting.getString(SystemSettingKey.BUILD_NUMBER); - SystemInfo systemInfo = systemInfoFactory.newSystemInfo(); + SystemInfo systemInfo = new SystemInfo(); systemInfo.setVersion(version); systemInfo.setRevision(revision); systemInfo.setBuildBranch(branch); diff --git a/service/system/pom.xml b/service/system/pom.xml index fb5df7322d0..ba4fc81bf5c 100644 --- a/service/system/pom.xml +++ b/service/system/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-service - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT pom diff --git a/service/system/test-steps/pom.xml b/service/system/test-steps/pom.xml index 0bec73d65cb..cb45ac417c9 100644 --- a/service/system/test-steps/pom.xml +++ b/service/system/test-steps/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-system - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-system-test-steps diff --git a/service/system/test/pom.xml b/service/system/test/pom.xml index 9fac00589f2..0903d256fb3 100644 --- a/service/system/test/pom.xml +++ b/service/system/test/pom.xml @@ -20,7 +20,7 @@ org.eclipse.kapua kapua-system - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-system-test diff --git a/service/system/test/src/test/java/org/eclipse/kapua/service/systeminfo/test/SystemInfoLocatorConfiguration.java b/service/system/test/src/test/java/org/eclipse/kapua/service/systeminfo/test/SystemInfoLocatorConfiguration.java index 4c6eeb797a6..8f47f44f2d2 100644 --- a/service/system/test/src/test/java/org/eclipse/kapua/service/systeminfo/test/SystemInfoLocatorConfiguration.java +++ b/service/system/test/src/test/java/org/eclipse/kapua/service/systeminfo/test/SystemInfoLocatorConfiguration.java @@ -19,11 +19,9 @@ import org.eclipse.kapua.commons.metric.CommonsMetric; import org.eclipse.kapua.commons.metric.MetricsService; import org.eclipse.kapua.commons.metric.MetricsServiceImpl; -import org.eclipse.kapua.commons.model.query.QueryFactoryImpl; import org.eclipse.kapua.commons.service.internal.cache.CacheManagerProvider; import org.eclipse.kapua.commons.setting.system.SystemSetting; import org.eclipse.kapua.locator.KapuaLocator; -import org.eclipse.kapua.model.query.QueryFactory; import org.eclipse.kapua.qa.common.MockedLocator; import org.eclipse.kapua.service.account.AccountFactory; import org.eclipse.kapua.service.account.AccountService; @@ -34,10 +32,7 @@ import org.eclipse.kapua.service.authorization.AuthorizationService; import org.eclipse.kapua.service.authorization.domain.DomainRegistryService; import org.eclipse.kapua.service.authorization.permission.Permission; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; -import org.eclipse.kapua.service.systeminfo.SystemInfoFactory; import org.eclipse.kapua.service.systeminfo.SystemInfoService; -import org.eclipse.kapua.service.systeminfo.internal.SystemInfoFactoryImpl; import org.eclipse.kapua.service.systeminfo.internal.SystemInfoServiceImpl; import org.mockito.Matchers; import org.mockito.Mockito; @@ -85,20 +80,14 @@ protected void configure() { // skip } - bind(QueryFactory.class).toInstance(new QueryFactoryImpl()); - bind(AuthorizationService.class).toInstance(mockedAuthorization); - // Inject mocked Permission Factory - bind(PermissionFactory.class).toInstance(Mockito.mock(PermissionFactory.class)); // binding Account related services bind(AccountService.class).toInstance(Mockito.mock(AccountService.class)); bind(AccountFactory.class).toInstance(Mockito.spy(new AccountFactoryImpl())); // Inject actual System Info service related services - bind(SystemInfoService.class).toInstance(new SystemInfoServiceImpl(new SystemInfoFactoryImpl(), SystemSetting.getInstance())); - bind(SystemInfoFactory.class).toInstance(new SystemInfoFactoryImpl()); - + bind(SystemInfoService.class).toInstance(new SystemInfoServiceImpl(SystemSetting.getInstance())); } }; diff --git a/service/tag/api/pom.xml b/service/tag/api/pom.xml index 9154588db01..f14dedd6f86 100644 --- a/service/tag/api/pom.xml +++ b/service/tag/api/pom.xml @@ -17,7 +17,7 @@ org.eclipse.kapua kapua-tag - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-tag-api diff --git a/service/tag/api/src/main/java/org/eclipse/kapua/service/tag/Tag.java b/service/tag/api/src/main/java/org/eclipse/kapua/service/tag/Tag.java index a0cfd2bca3d..b85a8ef89df 100644 --- a/service/tag/api/src/main/java/org/eclipse/kapua/service/tag/Tag.java +++ b/service/tag/api/src/main/java/org/eclipse/kapua/service/tag/Tag.java @@ -12,35 +12,25 @@ *******************************************************************************/ package org.eclipse.kapua.service.tag; -import org.eclipse.kapua.model.KapuaNamedEntity; -import org.eclipse.kapua.model.id.KapuaId; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlTransient; import javax.xml.bind.annotation.XmlType; +import org.eclipse.kapua.model.KapuaNamedEntityBase; + /** * {@link Tag} {@link org.eclipse.kapua.model.KapuaEntity} definition *

        - * {@link Tag}s serve as tag for entities marked as {@link Taggable}. - * It is possible to assign a {@link Tag} to a {@link org.eclipse.kapua.model.KapuaEntity}. + * {@link Tag}s serve as tag for entities marked as {@link Taggable}. It is possible to assign a {@link Tag} to a {@link org.eclipse.kapua.model.KapuaEntity}. * * @since 1.0.0 */ @XmlRootElement(name = "tag") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = TagXmlRegistry.class, factoryMethod = "newTag") -public interface Tag extends KapuaNamedEntity { - - @XmlTransient - KapuaId ANY = KapuaId.ANY; +@XmlType +public class Tag extends KapuaNamedEntityBase { - String TYPE = "tag"; + private static final long serialVersionUID = -3760818776351242930L; - @Override - default String getType() { - return TYPE; - } } diff --git a/service/tag/api/src/main/java/org/eclipse/kapua/service/tag/TagCreator.java b/service/tag/api/src/main/java/org/eclipse/kapua/service/tag/TagCreator.java index 410e85b2e54..bd58d96e59c 100644 --- a/service/tag/api/src/main/java/org/eclipse/kapua/service/tag/TagCreator.java +++ b/service/tag/api/src/main/java/org/eclipse/kapua/service/tag/TagCreator.java @@ -12,13 +12,14 @@ *******************************************************************************/ package org.eclipse.kapua.service.tag; -import org.eclipse.kapua.model.KapuaNamedEntityCreator; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; +import org.eclipse.kapua.model.KapuaNamedEntityCreator; +import org.eclipse.kapua.model.id.KapuaId; + /** * {@link TagCreator} definition *

        @@ -28,6 +29,19 @@ */ @XmlRootElement(name = "tagCreator") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = TagXmlRegistry.class, factoryMethod = "newTagCreator") -public interface TagCreator extends KapuaNamedEntityCreator { +@XmlType +public class TagCreator extends KapuaNamedEntityCreator { + + private static final long serialVersionUID = -4676187845961673421L; + + public TagCreator() { + } + + public TagCreator(KapuaId scopeId) { + super(scopeId); + } + + public TagCreator(KapuaId scopeId, String name) { + super(scopeId, name); + } } diff --git a/service/tag/api/src/main/java/org/eclipse/kapua/service/tag/TagFactory.java b/service/tag/api/src/main/java/org/eclipse/kapua/service/tag/TagFactory.java deleted file mode 100644 index c8f36fb1aab..00000000000 --- a/service/tag/api/src/main/java/org/eclipse/kapua/service/tag/TagFactory.java +++ /dev/null @@ -1,35 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2017, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.tag; - -import org.eclipse.kapua.model.KapuaEntityFactory; -import org.eclipse.kapua.model.id.KapuaId; - -/** - * {@link TagFactory} definition. - * - * @see org.eclipse.kapua.model.KapuaEntityFactory - * @since 1.0.0 - */ -public interface TagFactory extends KapuaEntityFactory { - - /** - * Instantiates a new {@link TagCreator}. - * - * @param scopeId The scope {@link KapuaId} to set into the {@link TagCreator} - * @param name The name to set into the {@link TagCreator}. - * @return The newly instantiated {@link TagCreator} - * @since 1.0.0 - */ - TagCreator newCreator(KapuaId scopeId, String name); -} diff --git a/service/tag/api/src/main/java/org/eclipse/kapua/service/tag/TagListResult.java b/service/tag/api/src/main/java/org/eclipse/kapua/service/tag/TagListResult.java index c8b50fe1832..7ec807ac997 100644 --- a/service/tag/api/src/main/java/org/eclipse/kapua/service/tag/TagListResult.java +++ b/service/tag/api/src/main/java/org/eclipse/kapua/service/tag/TagListResult.java @@ -12,18 +12,26 @@ *******************************************************************************/ package org.eclipse.kapua.service.tag; -import org.eclipse.kapua.model.query.KapuaListResult; +import java.util.ArrayList; +import java.util.List; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; +import org.eclipse.kapua.model.query.KapuaListResult; + /** * {@link Tag} list result definition. * * @since 1.0.0 */ @XmlRootElement(name = "tags") -@XmlType(factoryClass = TagXmlRegistry.class, factoryMethod = "newTagListResult") -public interface TagListResult extends KapuaListResult { +@XmlType +public class TagListResult extends KapuaListResult { + + private static final long serialVersionUID = 791258978210911362L; + public void setItems(List items) { + this.items = new ArrayList<>(items); + } } diff --git a/service/tag/api/src/main/java/org/eclipse/kapua/service/tag/TagMatchPredicate.java b/service/tag/api/src/main/java/org/eclipse/kapua/service/tag/TagMatchPredicate.java index a1df13b4279..f28794fb894 100644 --- a/service/tag/api/src/main/java/org/eclipse/kapua/service/tag/TagMatchPredicate.java +++ b/service/tag/api/src/main/java/org/eclipse/kapua/service/tag/TagMatchPredicate.java @@ -12,7 +12,24 @@ *******************************************************************************/ package org.eclipse.kapua.service.tag; -import org.eclipse.kapua.model.query.predicate.MatchPredicate; -public interface TagMatchPredicate extends MatchPredicate { +import java.util.Arrays; + +import org.eclipse.kapua.model.query.predicate.AbstractMatchPredicate; + +public class TagMatchPredicate extends AbstractMatchPredicate { + + /** + * Constructor. + * + * @param matchTerm + * @since 2.1.0 + */ + public TagMatchPredicate(T matchTerm) { + this.attributeNames = Arrays.asList( + TagAttributes.DESCRIPTION, + TagAttributes.NAME + ); + this.matchTerm = matchTerm; + } } diff --git a/service/tag/api/src/main/java/org/eclipse/kapua/service/tag/TagQuery.java b/service/tag/api/src/main/java/org/eclipse/kapua/service/tag/TagQuery.java index 0bbfc29faeb..dea8bfbf590 100644 --- a/service/tag/api/src/main/java/org/eclipse/kapua/service/tag/TagQuery.java +++ b/service/tag/api/src/main/java/org/eclipse/kapua/service/tag/TagQuery.java @@ -12,13 +12,14 @@ *******************************************************************************/ package org.eclipse.kapua.service.tag; -import org.eclipse.kapua.model.query.KapuaQuery; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; +import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.query.KapuaQuery; + /** * {@link Tag} {@link KapuaQuery} definition. * @@ -27,17 +28,35 @@ */ @XmlRootElement(name = "query") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = TagXmlRegistry.class, factoryMethod = "newQuery") -public interface TagQuery extends KapuaQuery { +@XmlType +public class TagQuery extends KapuaQuery { + + public TagQuery() { + } + + /** + * Constructor. + * + * @param scopeId + * The {@link #getScopeId()}. + * @since 1.0.0 + */ + public TagQuery(KapuaId scopeId) { + super(scopeId); + } /** * Instantiates a new {@link TagMatchPredicate}. * - * @param matchTerm The term to use to match. - * @param The type of the term + * @param matchTerm + * The term to use to match. + * @param + * The type of the term * @return The newly instantiated {@link TagMatchPredicate}. * @since 2.1.0 */ - TagMatchPredicate matchPredicate(T matchTerm); + public TagMatchPredicate matchPredicate(T matchTerm) { + return new TagMatchPredicate<>(matchTerm); + } } diff --git a/service/tag/api/src/main/java/org/eclipse/kapua/service/tag/TagXmlRegistry.java b/service/tag/api/src/main/java/org/eclipse/kapua/service/tag/TagXmlRegistry.java deleted file mode 100644 index e0934428188..00000000000 --- a/service/tag/api/src/main/java/org/eclipse/kapua/service/tag/TagXmlRegistry.java +++ /dev/null @@ -1,54 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2017, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.tag; - -import org.eclipse.kapua.locator.KapuaLocator; - -import javax.xml.bind.annotation.XmlRegistry; - -@XmlRegistry -public class TagXmlRegistry { - - private final TagFactory tagFactory = KapuaLocator.getInstance().getFactory(TagFactory.class); - - /** - * Creates a new tag instance - * - * @return - */ - public Tag newTag() { - return tagFactory.newEntity(null); - } - - /** - * Creates a new tag creator instance - * - * @return - */ - public TagCreator newTagCreator() { - return tagFactory.newCreator(null, null); - } - - /** - * Creates a new tag creator instance - * - * @return - */ - public TagListResult newTagListResult() { - return tagFactory.newListResult(); - } - - public TagQuery newQuery() { - return tagFactory.newQuery(null); - } -} diff --git a/service/tag/internal/pom.xml b/service/tag/internal/pom.xml index 3c16a9f0504..8ffbbfd394b 100644 --- a/service/tag/internal/pom.xml +++ b/service/tag/internal/pom.xml @@ -17,7 +17,7 @@ org.eclipse.kapua kapua-tag - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-tag-internal @@ -56,4 +56,34 @@ test + + + + org.apache.maven.plugins + maven-compiler-plugin + + + + org.mapstruct + mapstruct-processor + ${mapstruct.version} + + + + org.hibernate + hibernate-jpamodelgen + ${hibernate-jpamodelgen.version} + + + + -Amapstruct.unmappedTargetPolicy=ERROR + -Amapstruct.unmappedSourcePolicy=WARN + -Amapstruct.suppressGeneratorTimestamp=true + -Amapstruct.suppressGeneratorVersionInfoComment=true + + + + + + diff --git a/service/tag/internal/src/main/java/org/eclipse/kapua/service/tag/internal/TagCreatorImpl.java b/service/tag/internal/src/main/java/org/eclipse/kapua/service/tag/internal/TagCreatorImpl.java deleted file mode 100644 index 25921ac8762..00000000000 --- a/service/tag/internal/src/main/java/org/eclipse/kapua/service/tag/internal/TagCreatorImpl.java +++ /dev/null @@ -1,51 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2017, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.tag.internal; - -import org.eclipse.kapua.commons.model.AbstractKapuaNamedEntityCreator; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.authorization.domain.DomainCreator; -import org.eclipse.kapua.service.tag.Tag; -import org.eclipse.kapua.service.tag.TagCreator; - -/** - * {@link TagCreator} implementation. - * - * @since 1.0.0 - */ -public class TagCreatorImpl extends AbstractKapuaNamedEntityCreator implements TagCreator { - - private static final long serialVersionUID = -4676187845961673421L; - - /** - * Constructor. - * - * @param scopeId The scope id to set. - * @param name The name to set for this {@link DomainCreator}. - * @since 1.0.0 - */ - public TagCreatorImpl(KapuaId scopeId, String name) { - super(scopeId); - - setName(name); - } - - /** - * Constructor - * - * @param scopeId The scopeId {@link KapuaId} - */ - public TagCreatorImpl(KapuaId scopeId) { - super(scopeId); - } -} diff --git a/service/tag/internal/src/main/java/org/eclipse/kapua/service/tag/internal/TagFactoryImpl.java b/service/tag/internal/src/main/java/org/eclipse/kapua/service/tag/internal/TagFactoryImpl.java deleted file mode 100644 index 5931fd10e3f..00000000000 --- a/service/tag/internal/src/main/java/org/eclipse/kapua/service/tag/internal/TagFactoryImpl.java +++ /dev/null @@ -1,70 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.tag.internal; - -import org.eclipse.kapua.KapuaEntityCloneException; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.tag.Tag; -import org.eclipse.kapua.service.tag.TagCreator; -import org.eclipse.kapua.service.tag.TagFactory; -import org.eclipse.kapua.service.tag.TagListResult; -import org.eclipse.kapua.service.tag.TagQuery; - -import javax.inject.Singleton; - -/** - * {@link TagFactory} implementation. - * - * @since 1.0.0 - */ -@Singleton -public class TagFactoryImpl implements TagFactory { - - @Override - public TagCreator newCreator(KapuaId scopeId, String name) { - TagCreator creator = newCreator(scopeId); - - creator.setName(name); - - return creator; - } - - @Override - public Tag newEntity(KapuaId scopeId) { - return new TagImpl(scopeId); - } - - @Override - public TagListResult newListResult() { - return new TagListResultImpl(); - } - - @Override - public TagQuery newQuery(KapuaId scopeId) { - return new TagQueryImpl(scopeId); - } - - @Override - public TagCreator newCreator(KapuaId scopeId) { - return new TagCreatorImpl(scopeId); - } - - @Override - public Tag clone(Tag tag) { - try { - return new TagImpl(tag); - } catch (Exception e) { - throw new KapuaEntityCloneException(e, Tag.TYPE, tag); - } - } -} diff --git a/service/tag/internal/src/main/java/org/eclipse/kapua/service/tag/internal/TagImpl.java b/service/tag/internal/src/main/java/org/eclipse/kapua/service/tag/internal/TagImpl.java index c8fdd674aac..ad812abb744 100644 --- a/service/tag/internal/src/main/java/org/eclipse/kapua/service/tag/internal/TagImpl.java +++ b/service/tag/internal/src/main/java/org/eclipse/kapua/service/tag/internal/TagImpl.java @@ -12,14 +12,13 @@ *******************************************************************************/ package org.eclipse.kapua.service.tag.internal; -import org.eclipse.kapua.KapuaException; +import javax.persistence.Entity; +import javax.persistence.Table; + import org.eclipse.kapua.commons.model.AbstractKapuaNamedEntity; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.tag.Tag; -import javax.persistence.Entity; -import javax.persistence.Table; - /** * {@link Tag} implementation. * @@ -27,9 +26,14 @@ */ @Entity(name = "Tag") @Table(name = "tag_tag") -public class TagImpl extends AbstractKapuaNamedEntity implements Tag { +public class TagImpl extends AbstractKapuaNamedEntity { + + public static final String TYPE = "tag"; - private static final long serialVersionUID = -3760818776351242930L; + @Override + public String getType() { + return TYPE; + } /** * Constructor. @@ -43,21 +47,11 @@ protected TagImpl() { /** * Constructor. * - * @param scopeId The scope {@link KapuaId} + * @param scopeId + * The scope {@link KapuaId} * @since 1.0.0 */ public TagImpl(KapuaId scopeId) { super(scopeId); } - - /** - * Clone constructor. - * - * @param tag The {@link Tag} from which to create the new {@link Tag}. - * @throws KapuaException - * @since 1.0.0 - */ - public TagImpl(Tag tag) throws KapuaException { - super(tag); - } } diff --git a/service/tag/internal/src/main/java/org/eclipse/kapua/service/tag/internal/TagImplJpaRepository.java b/service/tag/internal/src/main/java/org/eclipse/kapua/service/tag/internal/TagImplJpaRepository.java index ee9965fb26a..205ba65cd8b 100644 --- a/service/tag/internal/src/main/java/org/eclipse/kapua/service/tag/internal/TagImplJpaRepository.java +++ b/service/tag/internal/src/main/java/org/eclipse/kapua/service/tag/internal/TagImplJpaRepository.java @@ -12,20 +12,18 @@ *******************************************************************************/ package org.eclipse.kapua.service.tag.internal; +import javax.inject.Singleton; + import org.eclipse.kapua.commons.jpa.KapuaJpaRepositoryConfiguration; import org.eclipse.kapua.commons.jpa.KapuaNamedEntityJpaRepository; -import org.eclipse.kapua.service.tag.Tag; -import org.eclipse.kapua.service.tag.TagListResult; -import org.eclipse.kapua.service.tag.TagRepository; - -import javax.inject.Singleton; @Singleton public class TagImplJpaRepository - extends KapuaNamedEntityJpaRepository + extends KapuaNamedEntityJpaRepository implements TagRepository { + public TagImplJpaRepository(KapuaJpaRepositoryConfiguration jpaRepoConfig) { - super(TagImpl.class, Tag.TYPE, TagListResultImpl::new, jpaRepoConfig); + super(TagImpl.class, TagImpl.TYPE, TagImplListResult::new, jpaRepoConfig); } } diff --git a/service/tag/internal/src/main/java/org/eclipse/kapua/service/tag/internal/TagListResultImpl.java b/service/tag/internal/src/main/java/org/eclipse/kapua/service/tag/internal/TagImplListResult.java similarity index 71% rename from service/tag/internal/src/main/java/org/eclipse/kapua/service/tag/internal/TagListResultImpl.java rename to service/tag/internal/src/main/java/org/eclipse/kapua/service/tag/internal/TagImplListResult.java index 3bbf92f544c..028f03af46e 100644 --- a/service/tag/internal/src/main/java/org/eclipse/kapua/service/tag/internal/TagListResultImpl.java +++ b/service/tag/internal/src/main/java/org/eclipse/kapua/service/tag/internal/TagImplListResult.java @@ -12,16 +12,21 @@ *******************************************************************************/ package org.eclipse.kapua.service.tag.internal; -import org.eclipse.kapua.commons.model.query.KapuaListResultImpl; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; + +import org.eclipse.kapua.model.query.KapuaListResult; import org.eclipse.kapua.service.tag.Tag; -import org.eclipse.kapua.service.tag.TagListResult; /** - * {@link TagListResult} implementation. + * {@link Tag} list result definition. * * @since 1.0.0 */ -public class TagListResultImpl extends KapuaListResultImpl implements TagListResult { +@XmlRootElement(name = "tags") +@XmlType +public class TagImplListResult extends KapuaListResult { private static final long serialVersionUID = 791258978210911362L; + } diff --git a/service/tag/internal/src/main/java/org/eclipse/kapua/service/tag/internal/TagMapper.java b/service/tag/internal/src/main/java/org/eclipse/kapua/service/tag/internal/TagMapper.java new file mode 100644 index 00000000000..917a8d603e5 --- /dev/null +++ b/service/tag/internal/src/main/java/org/eclipse/kapua/service/tag/internal/TagMapper.java @@ -0,0 +1,37 @@ +/******************************************************************************* + * Copyright (c) 2017, 2022 Eurotech and/or its affiliates and others + * + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Eurotech - initial API and implementation + *******************************************************************************/ +package org.eclipse.kapua.service.tag.internal; + +import org.eclipse.kapua.commons.model.mappers.KapuaBaseMapper; +import org.eclipse.kapua.service.tag.Tag; +import org.eclipse.kapua.service.tag.TagCreator; +import org.eclipse.kapua.service.tag.TagListResult; +import org.mapstruct.CollectionMappingStrategy; +import org.mapstruct.InjectionStrategy; +import org.mapstruct.Mapper; +import org.mapstruct.MappingConstants; +import org.mapstruct.MappingTarget; + +@Mapper(uses = KapuaBaseMapper.class, componentModel = MappingConstants.ComponentModel.JSR330, injectionStrategy = InjectionStrategy.CONSTRUCTOR, collectionMappingStrategy = CollectionMappingStrategy.TARGET_IMMUTABLE) +public interface TagMapper { + + Tag map(TagImpl tag); + + @KapuaBaseMapper.IgnoreKapuaUpdatableEntityReadonlyFields + TagImpl map(TagCreator tag); + + TagListResult map(TagImplListResult tagImplListResult); + + @KapuaBaseMapper.IgnoreKapuaUpdatableEntityReadonlyFields + void merge(@MappingTarget TagImpl existingTag, Tag tag); +} diff --git a/service/tag/internal/src/main/java/org/eclipse/kapua/service/tag/internal/TagMatchPredicateImpl.java b/service/tag/internal/src/main/java/org/eclipse/kapua/service/tag/internal/TagMatchPredicateImpl.java deleted file mode 100644 index e785c278463..00000000000 --- a/service/tag/internal/src/main/java/org/eclipse/kapua/service/tag/internal/TagMatchPredicateImpl.java +++ /dev/null @@ -1,35 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2017, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.tag.internal; - -import org.eclipse.kapua.commons.model.query.predicate.AbstractMatchPredicate; -import org.eclipse.kapua.service.tag.TagAttributes; -import org.eclipse.kapua.service.tag.TagMatchPredicate; -import java.util.Arrays; - -public class TagMatchPredicateImpl extends AbstractMatchPredicate implements TagMatchPredicate { - -/** - * Constructor. - * - * @param matchTerm - * @since 2.1.0 - */ - public TagMatchPredicateImpl(T matchTerm) { - this.attributeNames = Arrays.asList( - TagAttributes.DESCRIPTION, - TagAttributes.NAME - ); - this.matchTerm = matchTerm; - } -} diff --git a/service/tag/internal/src/main/java/org/eclipse/kapua/service/tag/internal/TagModule.java b/service/tag/internal/src/main/java/org/eclipse/kapua/service/tag/internal/TagModule.java index 8db25b3cb76..6db12b44d33 100644 --- a/service/tag/internal/src/main/java/org/eclipse/kapua/service/tag/internal/TagModule.java +++ b/service/tag/internal/src/main/java/org/eclipse/kapua/service/tag/internal/TagModule.java @@ -25,9 +25,6 @@ import org.eclipse.kapua.model.domain.Domain; import org.eclipse.kapua.model.domain.DomainEntry; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; -import org.eclipse.kapua.service.tag.TagFactory; -import org.eclipse.kapua.service.tag.TagRepository; import org.eclipse.kapua.service.tag.TagService; import com.google.inject.Provides; @@ -37,22 +34,21 @@ public class TagModule extends AbstractKapuaModule { @Override protected void configureModule() { - bind(TagFactory.class).to(TagFactoryImpl.class); + bind(TagMapper.class).to(TagMapperImpl.class).in(Singleton.class); } @Provides @Singleton TagService tagService( - PermissionFactory permissionFactory, AuthorizationService authorizationService, Map, ServiceConfigurationManager> serviceConfigurationManagersByServiceClass, TagRepository tagRepository, - TagFactory tagFactory, - KapuaJpaTxManagerFactory jpaTxManagerFactory) { - return new TagServiceImpl(permissionFactory, authorizationService, serviceConfigurationManagersByServiceClass.get(TagService.class), + KapuaJpaTxManagerFactory jpaTxManagerFactory, + TagMapper tagMapper) { + return new TagServiceImpl(authorizationService, serviceConfigurationManagersByServiceClass.get(TagService.class), jpaTxManagerFactory.create("kapua-tag"), tagRepository, - tagFactory); + tagMapper); } @ProvidesIntoSet diff --git a/service/tag/internal/src/main/java/org/eclipse/kapua/service/tag/internal/TagQueryImpl.java b/service/tag/internal/src/main/java/org/eclipse/kapua/service/tag/internal/TagQueryImpl.java deleted file mode 100644 index 612e77fe43f..00000000000 --- a/service/tag/internal/src/main/java/org/eclipse/kapua/service/tag/internal/TagQueryImpl.java +++ /dev/null @@ -1,42 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2017, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.tag.internal; - -import org.eclipse.kapua.commons.model.query.AbstractKapuaNamedQuery; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.tag.TagMatchPredicate; -import org.eclipse.kapua.service.tag.TagQuery; - -/** - * {@link TagQuery} implementation. - * - * @since 1.0.0 - */ -public class TagQueryImpl extends AbstractKapuaNamedQuery implements TagQuery { - - /** - * Constructor. - * - * @param scopeId The {@link #getScopeId()}. - * @since 1.0.0 - */ - public TagQueryImpl(KapuaId scopeId) { - super(scopeId); - } - - @Override - public TagMatchPredicate matchPredicate(T matchTerm) { - return new TagMatchPredicateImpl<>(matchTerm); - } - -} diff --git a/service/tag/api/src/main/java/org/eclipse/kapua/service/tag/TagRepository.java b/service/tag/internal/src/main/java/org/eclipse/kapua/service/tag/internal/TagRepository.java similarity index 84% rename from service/tag/api/src/main/java/org/eclipse/kapua/service/tag/TagRepository.java rename to service/tag/internal/src/main/java/org/eclipse/kapua/service/tag/internal/TagRepository.java index 00d0ef8cba8..16720981d19 100644 --- a/service/tag/api/src/main/java/org/eclipse/kapua/service/tag/TagRepository.java +++ b/service/tag/internal/src/main/java/org/eclipse/kapua/service/tag/internal/TagRepository.java @@ -10,10 +10,11 @@ * Contributors: * Eurotech - initial API and implementation *******************************************************************************/ -package org.eclipse.kapua.service.tag; +package org.eclipse.kapua.service.tag.internal; import org.eclipse.kapua.storage.KapuaNamedEntityRepository; public interface TagRepository extends - KapuaNamedEntityRepository { + KapuaNamedEntityRepository { + } diff --git a/service/tag/internal/src/main/java/org/eclipse/kapua/service/tag/internal/TagServiceConfigurationManagerModule.java b/service/tag/internal/src/main/java/org/eclipse/kapua/service/tag/internal/TagServiceConfigurationManagerModule.java index fb36f11d584..d5dbd64cd2c 100644 --- a/service/tag/internal/src/main/java/org/eclipse/kapua/service/tag/internal/TagServiceConfigurationManagerModule.java +++ b/service/tag/internal/src/main/java/org/eclipse/kapua/service/tag/internal/TagServiceConfigurationManagerModule.java @@ -29,8 +29,6 @@ import org.eclipse.kapua.commons.jpa.KapuaJpaTxManagerFactory; import org.eclipse.kapua.commons.model.domains.Domains; import org.eclipse.kapua.commons.util.xml.XmlUtil; -import org.eclipse.kapua.service.tag.TagFactory; -import org.eclipse.kapua.service.tag.TagRepository; import org.eclipse.kapua.service.tag.TagService; import com.google.inject.Module; @@ -54,7 +52,6 @@ protected void configureModule() { @Singleton ServiceConfigurationManager tagServiceConfigurationManager( KapuaJpaTxManagerFactory jpaTxManagerFactory, - TagFactory factory, RootUserTester rootUserTester, AccountRelativeFinder accountRelativeFinder, TagRepository tagRepository, @@ -73,7 +70,6 @@ ServiceConfigurationManager tagServiceConfigurationManager( rootUserTester, accountRelativeFinder, new UsedEntitiesCounterImpl( - factory, tagRepository ), new ResourceBasedServiceConfigurationMetadataProvider(xmlUtil))); diff --git a/service/tag/internal/src/main/java/org/eclipse/kapua/service/tag/internal/TagServiceImpl.java b/service/tag/internal/src/main/java/org/eclipse/kapua/service/tag/internal/TagServiceImpl.java index 13fecbb6686..94536def3a6 100644 --- a/service/tag/internal/src/main/java/org/eclipse/kapua/service/tag/internal/TagServiceImpl.java +++ b/service/tag/internal/src/main/java/org/eclipse/kapua/service/tag/internal/TagServiceImpl.java @@ -12,7 +12,11 @@ *******************************************************************************/ package org.eclipse.kapua.service.tag.internal; +import javax.inject.Inject; +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaDuplicateNameException; +import org.eclipse.kapua.KapuaEntityNotFoundException; import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.commons.configuration.KapuaConfigurableServiceBase; import org.eclipse.kapua.commons.configuration.ServiceConfigurationManager; @@ -22,18 +26,13 @@ import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; +import org.eclipse.kapua.service.authorization.permission.Permission; import org.eclipse.kapua.service.tag.Tag; import org.eclipse.kapua.service.tag.TagCreator; -import org.eclipse.kapua.service.tag.TagFactory; import org.eclipse.kapua.service.tag.TagListResult; -import org.eclipse.kapua.service.tag.TagRepository; import org.eclipse.kapua.service.tag.TagService; import org.eclipse.kapua.storage.TxManager; -import javax.inject.Inject; -import javax.inject.Singleton; - /** * {@link TagService} implementation. * @@ -42,37 +41,34 @@ @Singleton public class TagServiceImpl extends KapuaConfigurableServiceBase implements TagService { - private final PermissionFactory permissionFactory; private final AuthorizationService authorizationService; - private final TagFactory tagFactory; private final TxManager txManager; private final TagRepository tagRepository; + private final TagMapper tagMapper; /** * Injectable Constructor * - * @param permissionFactory The {@link PermissionFactory} instance - * @param authorizationService The {@link AuthorizationService} instance - * @param serviceConfigurationManager The {@link ServiceConfigurationManager} instance + * @param authorizationService + * The {@link AuthorizationService} instance + * @param serviceConfigurationManager + * The {@link ServiceConfigurationManager} instance * @param txManager - * @param tagRepository The {@link TagRepository} instance - * @param tagFactory + * @param tagRepository + * The {@link TagRepository} instance * @since 2.0.0 */ @Inject public TagServiceImpl( - PermissionFactory permissionFactory, AuthorizationService authorizationService, ServiceConfigurationManager serviceConfigurationManager, TxManager txManager, - TagRepository tagRepository, - TagFactory tagFactory) { - super(txManager, serviceConfigurationManager, Domains.TAG, authorizationService, permissionFactory); - this.permissionFactory = permissionFactory; + TagRepository tagRepository, TagMapper tagMapper) { + super(txManager, serviceConfigurationManager, Domains.TAG, authorizationService); this.authorizationService = authorizationService; this.tagRepository = tagRepository; - this.tagFactory = tagFactory; this.txManager = txManager; + this.tagMapper = tagMapper; } @Override @@ -82,8 +78,8 @@ public Tag create(TagCreator tagCreator) throws KapuaException { ArgumentValidator.notNull(tagCreator.getScopeId(), "tagCreator.scopeId"); ArgumentValidator.validateEntityName(tagCreator.getName(), "tagCreator.name"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.TAG, Actions.write, tagCreator.getScopeId())); - return txManager.execute(tx -> { + authorizationService.checkPermission(new Permission(Domains.TAG, Actions.write, tagCreator.getScopeId())); + final TagImpl newTag = txManager.execute(tx -> { // Check entity limit serviceConfigurationManager.checkAllowedEntities(tx, tagCreator.getScopeId(), "Tags"); // Check duplicate name @@ -92,12 +88,14 @@ public Tag create(TagCreator tagCreator) throws KapuaException { throw new KapuaDuplicateNameException(tagCreator.getName()); } - final Tag toBeCreated = tagFactory.newEntity(tagCreator.getScopeId()); + final TagImpl toBeCreated = new TagImpl(tagCreator.getScopeId()); toBeCreated.setName(tagCreator.getName()); toBeCreated.setDescription(tagCreator.getDescription()); // Do create - return tagRepository.create(tx, toBeCreated); + final TagImpl created = tagRepository.create(tx, toBeCreated); + return created; }); + return tagMapper.map(newTag); } @Override @@ -110,19 +108,25 @@ public Tag update(Tag tag) throws KapuaException { // Check Access authorizationService.checkPermission( - permissionFactory.newPermission(Domains.TAG, Actions.write, tag.getScopeId())); + new Permission(Domains.TAG, Actions.write, tag.getScopeId())); // Check duplicate name - return txManager.execute(tx -> { + final TagImpl updatedTag = txManager.execute(tx -> { // Check duplicate name final long otherEntitiesWithSameName = tagRepository.countOtherEntitiesWithNameInScope( tx, tag.getScopeId(), tag.getId(), tag.getName()); if (otherEntitiesWithSameName > 0) { throw new KapuaDuplicateNameException(tag.getName()); } + final TagImpl existingTag = tagRepository.find(tx, tag.getScopeId(), tag.getId()) + .orElseThrow(() -> new KapuaEntityNotFoundException("tag", tag.getId())); + //merge tag info + tagMapper.merge(existingTag, tag); + // Do Update - return tagRepository.update(tx, tag); + return tagRepository.update(tx, existingTag); }); + return tagMapper.map(updatedTag); } @Override @@ -131,7 +135,7 @@ public void delete(KapuaId scopeId, KapuaId tagId) throws KapuaException { ArgumentValidator.notNull(scopeId, "scopeId"); ArgumentValidator.notNull(tagId, "tagId"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.TAG, Actions.delete, scopeId)); + authorizationService.checkPermission(new Permission(Domains.TAG, Actions.delete, scopeId)); // Check existence txManager.execute(tx -> tagRepository.delete(tx, scopeId, tagId)); } @@ -142,9 +146,10 @@ public Tag find(KapuaId scopeId, KapuaId tagId) throws KapuaException { ArgumentValidator.notNull(scopeId, "scopeId"); ArgumentValidator.notNull(tagId, "tagId"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.TAG, Actions.read, scopeId)); + authorizationService.checkPermission(new Permission(Domains.TAG, Actions.read, scopeId)); // Do find return txManager.execute(tx -> tagRepository.find(tx, scopeId, tagId)) + .map(tagMapper::map) .orElse(null); } @@ -153,9 +158,9 @@ public TagListResult query(KapuaQuery query) throws KapuaException { // Argument validation ArgumentValidator.notNull(query, "query"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.TAG, Actions.read, query.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.TAG, Actions.read, query.getScopeId())); // Do query - return txManager.execute(tx -> tagRepository.query(tx, query)); + return tagMapper.map(txManager.execute(tx -> tagRepository.query(tx, query))); } @Override @@ -163,7 +168,7 @@ public long count(KapuaQuery query) throws KapuaException { // Argument validation ArgumentValidator.notNull(query, "query"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.TAG, Actions.read, query.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.TAG, Actions.read, query.getScopeId())); // Do count return txManager.execute(tx -> tagRepository.count(tx, query)); } diff --git a/service/tag/internal/src/test/java/org/eclipse/kapua/service/tag/internal/StubPermission.java b/service/tag/internal/src/test/java/org/eclipse/kapua/service/tag/internal/StubPermission.java deleted file mode 100644 index 9cfe851f3ad..00000000000 --- a/service/tag/internal/src/test/java/org/eclipse/kapua/service/tag/internal/StubPermission.java +++ /dev/null @@ -1,102 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2017, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.tag.internal; - -import org.eclipse.kapua.model.domain.Actions; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.authorization.permission.Permission; - -import java.util.Objects; - -public class StubPermission implements Permission { - private final String domain; - private final Actions action; - private final KapuaId targetScopeId; - private final KapuaId groupId; - private final Boolean forwardable; - - public StubPermission(String domain, Actions actions, KapuaId targetScopeId, KapuaId groupId, Boolean forwardable) { - this.domain = domain; - this.action = actions; - this.targetScopeId = targetScopeId; - this.groupId = groupId; - this.forwardable = forwardable; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - final StubPermission stubPermission = (StubPermission) o; - return Objects.equals(domain, stubPermission.domain) && action == stubPermission.action && Objects.equals(targetScopeId, stubPermission.targetScopeId) && Objects.equals(groupId, stubPermission.groupId) && Objects.equals(forwardable, stubPermission.forwardable); - } - - @Override - public int hashCode() { - return Objects.hash(domain, action, targetScopeId, groupId, forwardable); - } - - @Override - public void setDomain(String domain) { - - } - - @Override - public String getDomain() { - return domain; - } - - @Override - public void setAction(Actions action) { - - } - - @Override - public Actions getAction() { - return action; - } - - @Override - public void setTargetScopeId(KapuaId targetScopeId) { - - } - - @Override - public KapuaId getTargetScopeId() { - return targetScopeId; - } - - @Override - public void setGroupId(KapuaId groupId) { - - } - - @Override - public KapuaId getGroupId() { - return groupId; - } - - @Override - public void setForwardable(boolean forwardable) { - - } - - @Override - public boolean getForwardable() { - return forwardable; - } -} diff --git a/service/tag/internal/src/test/java/org/eclipse/kapua/service/tag/internal/TagServiceImplTest.java b/service/tag/internal/src/test/java/org/eclipse/kapua/service/tag/internal/TagServiceImplTest.java index 9e8df12ee9b..133c87d783c 100644 --- a/service/tag/internal/src/test/java/org/eclipse/kapua/service/tag/internal/TagServiceImplTest.java +++ b/service/tag/internal/src/test/java/org/eclipse/kapua/service/tag/internal/TagServiceImplTest.java @@ -12,18 +12,17 @@ *******************************************************************************/ package org.eclipse.kapua.service.tag.internal; +import java.math.BigInteger; +import java.util.function.BiConsumer; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.KapuaIllegalNullArgumentException; import org.eclipse.kapua.commons.configuration.ServiceConfigurationManager; -import org.eclipse.kapua.model.domain.Actions; -import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.commons.model.mappers.KapuaBaseMapperImpl; import org.eclipse.kapua.model.id.KapuaIdImpl; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.Permission; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; import org.eclipse.kapua.service.tag.Tag; -import org.eclipse.kapua.service.tag.TagFactory; -import org.eclipse.kapua.service.tag.TagRepository; +import org.eclipse.kapua.service.tag.TagCreator; import org.eclipse.kapua.storage.TxContext; import org.eclipse.kapua.storage.TxManager; import org.junit.jupiter.api.Assertions; @@ -32,9 +31,6 @@ import org.mockito.MockSettings; import org.mockito.Mockito; -import java.math.BigInteger; -import java.util.function.BiConsumer; - @org.junit.jupiter.api.Tag("org.eclipse.kapua.qa.markers.junit.JUnitTests") public class TagServiceImplTest { @@ -42,26 +38,20 @@ public class TagServiceImplTest { .defaultAnswer(invocation -> { throw new UnsupportedOperationException(invocation.toString()); }); - public static final Permission FAKE_PERMISSION = new StubPermission("fakeDomain", Actions.execute, new KapuaIdImpl(BigInteger.ONE), new KapuaIdImpl(BigInteger.TEN), true); - private PermissionFactory permissionFactory; private AuthorizationService authorizationService; private ServiceConfigurationManager serviceConfigurationManager; private TagRepository tagRepository; private TagServiceImpl instance; - private TagFactory tagFactory; @BeforeEach public void setUp() throws KapuaException { - permissionFactory = Mockito.mock(PermissionFactory.class); - Mockito.when(permissionFactory.newPermission(Mockito.any(), Mockito.any(), Mockito.any())) - .thenReturn(FAKE_PERMISSION); authorizationService = Mockito.mock(AuthorizationService.class); serviceConfigurationManager = Mockito.mock(ServiceConfigurationManager.class); tagRepository = Mockito.mock(TagRepository.class); - Mockito.when(tagRepository.create(Mockito.any(), Mockito.any())) + Mockito.when(tagRepository.create(Mockito.any(), Mockito.any())) .thenAnswer(invocation -> invocation.getArgumentAt(0, Tag.class)); - tagFactory = Mockito.mock(TagFactory.class); final TxManager txManager = new TxManager() { + @Override public R execute(TxConsumer transactionConsumer, BiConsumer... afterCommitConsumers) throws KapuaException { return null; @@ -72,18 +62,13 @@ public TxContext getTxContext() { return null; } }; - Mockito.when(tagFactory.newCreator(Mockito.any(), Mockito.any())) - .thenAnswer(invocation -> new TagCreatorImpl(invocation.getArgumentAt(0, KapuaId.class), invocation.getArgumentAt(1, String.class))); - Mockito.when(tagFactory.newEntity(Mockito.any())) - .thenAnswer(invocation -> new TagImpl(invocation.getArgumentAt(0, KapuaId.class))); instance = new TagServiceImpl( - permissionFactory, authorizationService, serviceConfigurationManager, txManager, tagRepository, - tagFactory + new TagMapperImpl(new KapuaBaseMapperImpl()) ); } @@ -93,10 +78,10 @@ public void createTagPerformsInputValidation() { () -> instance.create(null), "Does not accept null tagCreator"); Assertions.assertThrows(KapuaIllegalNullArgumentException.class, - () -> instance.create(new TagCreatorImpl(null, "testTag")), + () -> instance.create(new TagCreator(null, "testTag")), "Does not accept tagCreator with null scope id"); Assertions.assertThrows(KapuaIllegalNullArgumentException.class, - () -> instance.create(new TagCreatorImpl(new KapuaIdImpl(BigInteger.ONE), null)), + () -> instance.create(new TagCreator(new KapuaIdImpl(BigInteger.ONE), null)), "Does not accept tagCreator with null name"); } } \ No newline at end of file diff --git a/service/tag/pom.xml b/service/tag/pom.xml index a47591d2763..993db684972 100644 --- a/service/tag/pom.xml +++ b/service/tag/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-service - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT pom diff --git a/service/tag/test-steps/pom.xml b/service/tag/test-steps/pom.xml index 14f40a33555..a4eb7b8018d 100644 --- a/service/tag/test-steps/pom.xml +++ b/service/tag/test-steps/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-tag - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-tag-test-steps diff --git a/service/tag/test-steps/src/main/java/org/eclipse/kapua/service/tag/steps/TagServiceSteps.java b/service/tag/test-steps/src/main/java/org/eclipse/kapua/service/tag/steps/TagServiceSteps.java index bb7750467d1..4c9d7ec737e 100644 --- a/service/tag/test-steps/src/main/java/org/eclipse/kapua/service/tag/steps/TagServiceSteps.java +++ b/service/tag/test-steps/src/main/java/org/eclipse/kapua/service/tag/steps/TagServiceSteps.java @@ -12,14 +12,13 @@ *******************************************************************************/ package org.eclipse.kapua.service.tag.steps; -import com.google.inject.Singleton; -import io.cucumber.java.After; -import io.cucumber.java.Before; -import io.cucumber.java.Scenario; -import io.cucumber.java.en.And; -import io.cucumber.java.en.Given; -import io.cucumber.java.en.Then; -import io.cucumber.java.en.When; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.inject.Inject; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.locator.KapuaLocator; import org.eclipse.kapua.model.id.KapuaId; @@ -32,17 +31,20 @@ import org.eclipse.kapua.service.tag.Tag; import org.eclipse.kapua.service.tag.TagAttributes; import org.eclipse.kapua.service.tag.TagCreator; -import org.eclipse.kapua.service.tag.TagFactory; import org.eclipse.kapua.service.tag.TagListResult; import org.eclipse.kapua.service.tag.TagQuery; import org.eclipse.kapua.service.tag.TagService; import org.junit.Assert; -import javax.inject.Inject; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; +import com.google.inject.Singleton; + +import io.cucumber.java.After; +import io.cucumber.java.Before; +import io.cucumber.java.Scenario; +import io.cucumber.java.en.And; +import io.cucumber.java.en.Given; +import io.cucumber.java.en.Then; +import io.cucumber.java.en.When; /** * Implementation of Gherkin steps used in TagService.feature scenarios. @@ -54,7 +56,6 @@ public class TagServiceSteps extends TestBase { * Tag service. */ private TagService tagService; - private TagFactory tagFactory; @Inject public TagServiceSteps(StepData stepData) { @@ -65,7 +66,6 @@ public TagServiceSteps(StepData stepData) { public void setServices() { KapuaLocator locator = KapuaLocator.getInstance(); tagService = locator.getService(TagService.class); - tagFactory = locator.getFactory(TagFactory.class); } // ************************************* @@ -170,7 +170,7 @@ public void tagWithNameIfSearched(String tagName) throws Throwable { try { stepData.remove("tag"); primeException(); - TagQuery query = tagFactory.newQuery(SYS_SCOPE_ID); + TagQuery query = new TagQuery(SYS_SCOPE_ID); query.setPredicate(query.attributePredicate(TagAttributes.NAME, tagName, AttributePredicate.Operator.EQUAL)); //TODO: #LAYER_VIOLATION - isn't this a find by name? TagListResult queryResult = tagService.query(query); @@ -186,7 +186,7 @@ public void tagWithNameIfSearched(String tagName) throws Throwable { public void deleteTagWithName(String tagName) throws Throwable { try { primeException(); - TagQuery query = tagFactory.newQuery(getCurrentScopeId()); + TagQuery query = new TagQuery(getCurrentScopeId()); query.setPredicate(query.attributePredicate(TagAttributes.NAME, tagName, AttributePredicate.Operator.EQUAL)); //TODO: #LAYER_VIOLATION - isn't this a find by name? TagListResult queryResult = tagService.query(query); @@ -232,17 +232,18 @@ public void tagWithNameIsDeleted(String tagName) throws Throwable { /** * Create TagCreator for creating tag with specified name. * - * @param tagName name of tag + * @param tagName + * name of tag * @return tag creator for tag with specified name */ private TagCreator tagCreatorCreatorWithoutDescription(String tagName) { - TagCreator tagCreator = tagFactory.newCreator(getCurrentScopeId()); + TagCreator tagCreator = new TagCreator(getCurrentScopeId()); tagCreator.setName(tagName); return tagCreator; } public TagCreator tagCreatorCreatorWithDescription(String tagName, String tagDescription) { - TagCreator tagCreator = tagFactory.newCreator(SYS_SCOPE_ID); + TagCreator tagCreator = new TagCreator(SYS_SCOPE_ID); tagCreator.setName(tagName); tagCreator.setDescription(tagDescription); return tagCreator; @@ -266,7 +267,7 @@ public void tagNameIsChangedIntoName(String tagName) throws Exception { public void nameOfTagIsChangedInto(String tagName, String newTagName) throws Exception { try { primeException(); - TagQuery query = tagFactory.newQuery(getCurrentScopeId()); + TagQuery query = new TagQuery(getCurrentScopeId()); query.setPredicate(query.attributePredicate(TagAttributes.NAME, tagName, AttributePredicate.Operator.EQUAL)); TagListResult queryResult = tagService.query(query); Tag foundTag = queryResult.getFirstItem(); @@ -296,7 +297,7 @@ public void tagDescriptionIsChangedInto(String description) throws Exception { @And("Description of tag {string} is changed into {string}") public void descriptionOfTagIsChangedInto(String tagName, String newDescription) throws Exception { try { - TagQuery query = tagFactory.newQuery(getCurrentScopeId()); + TagQuery query = new TagQuery(getCurrentScopeId()); query.setPredicate(query.attributePredicate(TagAttributes.NAME, tagName, AttributePredicate.Operator.EQUAL)); TagListResult queryResult = tagService.query(query); Tag foundTag = queryResult.getFirstItem(); diff --git a/service/tag/test/pom.xml b/service/tag/test/pom.xml index f7322e9ca7c..239fbfa5c60 100644 --- a/service/tag/test/pom.xml +++ b/service/tag/test/pom.xml @@ -20,7 +20,7 @@ org.eclipse.kapua kapua-tag - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-tag-test diff --git a/service/tag/test/src/test/java/org/eclipse/kapua/service/tag/test/TagLocatorConfiguration.java b/service/tag/test/src/test/java/org/eclipse/kapua/service/tag/test/TagLocatorConfiguration.java index 4c939064cbf..35788f4d13d 100644 --- a/service/tag/test/src/test/java/org/eclipse/kapua/service/tag/test/TagLocatorConfiguration.java +++ b/service/tag/test/src/test/java/org/eclipse/kapua/service/tag/test/TagLocatorConfiguration.java @@ -30,14 +30,13 @@ import org.eclipse.kapua.commons.metric.CommonsMetric; import org.eclipse.kapua.commons.metric.MetricsService; import org.eclipse.kapua.commons.metric.MetricsServiceImpl; -import org.eclipse.kapua.commons.model.query.QueryFactoryImpl; +import org.eclipse.kapua.commons.model.mappers.KapuaBaseMapperImpl; import org.eclipse.kapua.commons.service.event.store.internal.EventStoreRecordImplJpaRepository; import org.eclipse.kapua.commons.service.internal.cache.CacheManagerProvider; import org.eclipse.kapua.commons.setting.system.SystemSetting; import org.eclipse.kapua.locator.KapuaLocator; import org.eclipse.kapua.message.KapuaMessageFactory; import org.eclipse.kapua.message.internal.KapuaMessageFactoryImpl; -import org.eclipse.kapua.model.query.QueryFactory; import org.eclipse.kapua.qa.common.MockedLocator; import org.eclipse.kapua.service.account.AccountFactory; import org.eclipse.kapua.service.account.AccountService; @@ -50,7 +49,6 @@ import org.eclipse.kapua.service.authorization.domain.DomainRegistryService; import org.eclipse.kapua.service.authorization.group.GroupService; import org.eclipse.kapua.service.authorization.permission.Permission; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; import org.eclipse.kapua.service.device.registry.DeviceFactory; import org.eclipse.kapua.service.device.registry.DeviceRegistryService; import org.eclipse.kapua.service.device.registry.DeviceRepository; @@ -73,11 +71,10 @@ import org.eclipse.kapua.service.device.registry.internal.DeviceFactoryImpl; import org.eclipse.kapua.service.device.registry.internal.DeviceImplJpaRepository; import org.eclipse.kapua.service.device.registry.internal.DeviceRegistryServiceImpl; -import org.eclipse.kapua.service.tag.TagFactory; -import org.eclipse.kapua.service.tag.TagRepository; import org.eclipse.kapua.service.tag.TagService; -import org.eclipse.kapua.service.tag.internal.TagFactoryImpl; import org.eclipse.kapua.service.tag.internal.TagImplJpaRepository; +import org.eclipse.kapua.service.tag.internal.TagMapperImpl; +import org.eclipse.kapua.service.tag.internal.TagRepository; import org.eclipse.kapua.service.tag.internal.TagServiceImpl; import org.mockito.Matchers; import org.mockito.Mockito; @@ -124,15 +121,11 @@ protected void configure() { bind(KapuaJpaRepositoryConfiguration.class).toInstance(new KapuaJpaRepositoryConfiguration()); bind(AuthorizationService.class).toInstance(mockedAuthorization); - // Inject mocked Permission Factory - final PermissionFactory permissionFactory = Mockito.mock(PermissionFactory.class); - bind(PermissionFactory.class).toInstance(permissionFactory); try { Mockito.doNothing().when(mockedAuthorization).checkPermission(Matchers.any(Permission.class)); } catch (KapuaException e) { // skip } - bind(QueryFactory.class).toInstance(new QueryFactoryImpl()); // binding Account related services bind(AccountRelativeFinder.class).toInstance(Mockito.mock(AccountRelativeFinder.class)); @@ -155,7 +148,6 @@ protected void configure() { final DeviceConnectionServiceImpl deviceConnectionService = new DeviceConnectionServiceImpl( classServiceConfigurationManagerMap, mockedAuthorization, - permissionFactory, new DeviceConnectionFactoryImpl(), new KapuaJpaTxManagerFactory(maxInsertAttempts).create("kapua-device"), new DeviceConnectionImplJpaRepository(jpaRepoConfig), @@ -164,7 +156,6 @@ protected void configure() { bind(DeviceEventRepository.class).toInstance(new DeviceEventImplJpaRepository(jpaRepoConfig)); final DeviceEventServiceImpl deviceEventService = new DeviceEventServiceImpl( mockedAuthorization, - permissionFactory, new KapuaJpaTxManagerFactory(maxInsertAttempts).create("kapua-device"), new DeviceImplJpaRepository(jpaRepoConfig), new DeviceEventFactoryImpl(), @@ -175,25 +166,22 @@ protected void configure() { new KapuaDeviceRegistrySettings().getInt(KapuaDeviceRegistrySettingKeys.DEVICE_LIFECYCLE_BIRTH_VAR_FIELDS_LENGTH_MAX), new KapuaDeviceRegistrySettings().getInt(KapuaDeviceRegistrySettingKeys.DEVICE_LIFECYCLE_BIRTH_EXTENDED_PROPERTIES_LENGTH_MAX), mockedAuthorization, - permissionFactory, Mockito.mock(GroupService.class), deviceConnectionService, deviceEventService, new DeviceImplJpaRepository(jpaRepoConfig), - new DeviceFactoryImpl(), new TagServiceImpl( - permissionFactory, mockedAuthorization, Mockito.mock(ServiceConfigurationManager.class), new KapuaJpaTxManagerFactory(maxInsertAttempts).create("kapua-tag"), new TagImplJpaRepository(jpaRepoConfig), - new TagFactoryImpl()) + new TagMapperImpl(new KapuaBaseMapperImpl()) + ) ); bind(DeviceRegistryService.class).toInstance( new DeviceRegistryServiceImpl( Mockito.mock(ServiceConfigurationManager.class), mockedAuthorization, - permissionFactory, new KapuaJpaTxManagerFactory(maxInsertAttempts).create("kapua-device"), new DeviceImplJpaRepository(jpaRepoConfig), new DeviceFactoryImpl(), @@ -210,14 +198,12 @@ protected void configure() { bind(DeviceEventService.class).toInstance(deviceEventService); bind(DeviceEventFactory.class).toInstance(new DeviceEventFactoryImpl()); bind(KapuaMessageFactory.class).toInstance(new KapuaMessageFactoryImpl()); - bind(TagFactory.class).to(TagFactoryImpl.class); bind(TagService.class).toInstance(new TagServiceImpl( - permissionFactory, mockedAuthorization, Mockito.mock(ServiceConfigurationManager.class), new KapuaJpaTxManagerFactory(maxInsertAttempts).create("kapua-tag"), new TagImplJpaRepository(new KapuaJpaRepositoryConfiguration()), - new TagFactoryImpl() + new TagMapperImpl(new KapuaBaseMapperImpl()) )); } }; diff --git a/service/user/api/pom.xml b/service/user/api/pom.xml index f1465c6e034..cb22ad8396a 100644 --- a/service/user/api/pom.xml +++ b/service/user/api/pom.xml @@ -19,7 +19,7 @@ org.eclipse.kapua kapua-user - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-user-api diff --git a/service/user/api/src/main/java/org/eclipse/kapua/service/user/UserCreator.java b/service/user/api/src/main/java/org/eclipse/kapua/service/user/UserCreator.java index c22db31cff5..1f9aa95acf3 100644 --- a/service/user/api/src/main/java/org/eclipse/kapua/service/user/UserCreator.java +++ b/service/user/api/src/main/java/org/eclipse/kapua/service/user/UserCreator.java @@ -12,8 +12,7 @@ *******************************************************************************/ package org.eclipse.kapua.service.user; -import org.eclipse.kapua.model.KapuaNamedEntityCreator; -import org.eclipse.kapua.model.xml.DateXmlAdapter; +import java.util.Date; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; @@ -21,7 +20,10 @@ import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; -import java.util.Date; + +import org.eclipse.kapua.model.KapuaNamedEntityCreator; +import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.xml.DateXmlAdapter; /** * {@link UserCreator} {@link org.eclipse.kapua.model.KapuaEntityCreator} definition @@ -30,8 +32,39 @@ */ @XmlRootElement(name = "userCreator") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = UserXmlRegistry.class, factoryMethod = "newUserCreator") -public interface UserCreator extends KapuaNamedEntityCreator { +@XmlType +public class UserCreator extends KapuaNamedEntityCreator { + + private static final long serialVersionUID = 4664940282892151008L; + + private UserStatus status; + private String displayName; + private String email; + private String phoneNumber; + private UserType userType = UserType.INTERNAL; + private String externalId; + private String externalUsername; + private Date expirationDate; + + public UserCreator() { + this(null, null); + } + + public UserCreator(KapuaId scopeId) { + this(scopeId, null); + } + + /** + * Constructor + * + * @param accountId + * @param name + */ + public UserCreator(KapuaId accountId, String name) { + super(accountId, name); + setStatus(UserStatus.ENABLED); + setUserType(UserType.INTERNAL); + } /** * Return the display name (may be a friendly username to show in the UI) @@ -39,14 +72,18 @@ public interface UserCreator extends KapuaNamedEntityCreator { * @return */ @XmlElement(name = "displayName") - String getDisplayName(); + public String getDisplayName() { + return displayName; + } /** * Set the display name * * @param displayName */ - void setDisplayName(String displayName); + public void setDisplayName(String displayName) { + this.displayName = displayName; + } /** * Get the email @@ -54,14 +91,18 @@ public interface UserCreator extends KapuaNamedEntityCreator { * @return */ @XmlElement(name = "email") - String getEmail(); + public String getEmail() { + return email; + } /** * Set the email * * @param email */ - void setEmail(String email); + public void setEmail(String email) { + this.email = email; + } /** * Get the phone number @@ -69,14 +110,18 @@ public interface UserCreator extends KapuaNamedEntityCreator { * @return */ @XmlElement(name = "phoneNumber") - String getPhoneNumber(); + public String getPhoneNumber() { + return phoneNumber; + } /** * Set the phone number * * @param phoneNumber */ - void setPhoneNumber(String phoneNumber); + public void setPhoneNumber(String phoneNumber) { + this.phoneNumber = phoneNumber; + } /** * Get the user type @@ -84,14 +129,18 @@ public interface UserCreator extends KapuaNamedEntityCreator { * @return */ @XmlElement(name = "userType") - UserType getUserType(); + public UserType getUserType() { + return userType; + } /** * Set the user type * * @param userType */ - void setUserType(UserType userType); + public void setUserType(UserType userType) { + this.userType = userType; + } /** * Get the external ID @@ -99,14 +148,18 @@ public interface UserCreator extends KapuaNamedEntityCreator { * @return */ @XmlElement(name = "externalId") - String getExternalId(); + public String getExternalId() { + return externalId; + } /** * Set the external ID * * @param externalId */ - void setExternalId(String externalId); + public void setExternalId(String externalId) { + this.externalId = externalId; + } /** * Gets the external username. @@ -115,25 +168,37 @@ public interface UserCreator extends KapuaNamedEntityCreator { * @since 2.0.0 */ @XmlElement(name = "externalUsername") - String getExternalUsername(); + public String getExternalUsername() { + return externalUsername; + } /** * Sets the external username. * - * @param externalUsername The external username. + * @param externalUsername + * The external username. * @since 2.0.0 */ - void setExternalUsername(String externalUsername); - + public void setExternalUsername(String externalUsername) { + this.externalUsername = externalUsername; + } @XmlElement(name = "expirationDate") @XmlJavaTypeAdapter(DateXmlAdapter.class) - Date getExpirationDate(); + public Date getExpirationDate() { + return expirationDate; + } - void setExpirationDate(Date expirationDate); + public void setExpirationDate(Date expirationDate) { + this.expirationDate = expirationDate; + } @XmlElement(name = "status") - UserStatus getStatus(); + public UserStatus getStatus() { + return status; + } - void setStatus(UserStatus status); + public void setStatus(UserStatus status) { + this.status = status; + } } diff --git a/service/user/api/src/main/java/org/eclipse/kapua/service/user/UserFactory.java b/service/user/api/src/main/java/org/eclipse/kapua/service/user/UserFactory.java index 763f88f819b..559a9b2f816 100644 --- a/service/user/api/src/main/java/org/eclipse/kapua/service/user/UserFactory.java +++ b/service/user/api/src/main/java/org/eclipse/kapua/service/user/UserFactory.java @@ -13,7 +13,6 @@ package org.eclipse.kapua.service.user; import org.eclipse.kapua.model.KapuaEntityFactory; -import org.eclipse.kapua.model.id.KapuaId; /** * {@link UserFactory} definition. @@ -21,16 +20,6 @@ * @see org.eclipse.kapua.model.KapuaEntityFactory * @since 1.0.0 */ -public interface UserFactory extends KapuaEntityFactory { - - /** - * Instantiates a new {@link UserCreator} - * - * @param scopedId The scope {@link KapuaId} to set into the {@link UserCreator}. - * @param name The name to set into the {@link UserCreator}. - * @return The newly instantiated {@link UserCreator} - * @since 1.0.0 - */ - UserCreator newCreator(KapuaId scopedId, String name); +public interface UserFactory extends KapuaEntityFactory { } diff --git a/service/user/api/src/main/java/org/eclipse/kapua/service/user/UserListResult.java b/service/user/api/src/main/java/org/eclipse/kapua/service/user/UserListResult.java index 37dc26c836a..3f92b0e8099 100644 --- a/service/user/api/src/main/java/org/eclipse/kapua/service/user/UserListResult.java +++ b/service/user/api/src/main/java/org/eclipse/kapua/service/user/UserListResult.java @@ -23,7 +23,9 @@ * @since 1.0 */ @XmlRootElement(name = "users") -@XmlType(factoryClass = UserXmlRegistry.class, factoryMethod = "newUserListResult") -public interface UserListResult extends KapuaListResult { +@XmlType +public class UserListResult extends KapuaListResult { + + private static final long serialVersionUID = 2231053707705207563L; } diff --git a/service/user/api/src/main/java/org/eclipse/kapua/service/user/UserMatchPredicate.java b/service/user/api/src/main/java/org/eclipse/kapua/service/user/UserMatchPredicate.java index 22739e77ed8..185bd4afbfb 100644 --- a/service/user/api/src/main/java/org/eclipse/kapua/service/user/UserMatchPredicate.java +++ b/service/user/api/src/main/java/org/eclipse/kapua/service/user/UserMatchPredicate.java @@ -12,8 +12,28 @@ *******************************************************************************/ package org.eclipse.kapua.service.user; -import org.eclipse.kapua.model.query.predicate.MatchPredicate; +import java.util.Arrays; -public interface UserMatchPredicate extends MatchPredicate { +import org.eclipse.kapua.model.query.predicate.AbstractMatchPredicate; +public class UserMatchPredicate extends AbstractMatchPredicate { + + /** + * Constructor. + * + * @param matchTerm + * @since 1.3.0 + */ + public UserMatchPredicate(T matchTerm) { + this.attributeNames = Arrays.asList( + UserAttributes.NAME, + UserAttributes.EMAIL, + UserAttributes.PHONE_NUMBER, + UserAttributes.DISPLAY_NAME, + UserAttributes.EXTERNAL_ID, + UserAttributes.DESCRIPTION, + UserAttributes.EXTERNAL_USERNAME + ); + this.matchTerm = matchTerm; + } } diff --git a/service/user/api/src/main/java/org/eclipse/kapua/service/user/UserQuery.java b/service/user/api/src/main/java/org/eclipse/kapua/service/user/UserQuery.java index aba06704af3..95d24a3246d 100644 --- a/service/user/api/src/main/java/org/eclipse/kapua/service/user/UserQuery.java +++ b/service/user/api/src/main/java/org/eclipse/kapua/service/user/UserQuery.java @@ -12,13 +12,14 @@ *******************************************************************************/ package org.eclipse.kapua.service.user; -import org.eclipse.kapua.model.query.KapuaQuery; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; +import org.eclipse.kapua.model.id.KapuaId; +import org.eclipse.kapua.model.query.KapuaQuery; + /** * {@link User} {@link KapuaQuery} definition. * @@ -27,17 +28,41 @@ */ @XmlRootElement(name = "query") @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = UserXmlRegistry.class, factoryMethod = "newQuery") -public interface UserQuery extends KapuaQuery { +@XmlType +public class UserQuery extends KapuaQuery { + + /** + * Constructor. + * + * @since 1.0.0 + */ + private UserQuery() { + super(); + } + + /** + * Constructor + * + * @param scopeId + * The {@link #getScopeId()}. + * @since 1.0.0 + */ + public UserQuery(KapuaId scopeId) { + this(); + setScopeId(scopeId); + } /** * Instantiates a new {@link UserMatchPredicate}. * - * @param matchTerm The term to use to match. - * @param The type of the term + * @param matchTerm + * The term to use to match. + * @param + * The type of the term * @return The newly instantiated {@link UserMatchPredicate}. * @since 1.3.0 */ - UserMatchPredicate matchPredicate(T matchTerm); - + public UserMatchPredicate matchPredicate(T matchTerm) { + return new UserMatchPredicate<>(matchTerm); + } } diff --git a/service/user/api/src/main/java/org/eclipse/kapua/service/user/UserXmlRegistry.java b/service/user/api/src/main/java/org/eclipse/kapua/service/user/UserXmlRegistry.java index a9b33088658..db1f2101d8a 100644 --- a/service/user/api/src/main/java/org/eclipse/kapua/service/user/UserXmlRegistry.java +++ b/service/user/api/src/main/java/org/eclipse/kapua/service/user/UserXmlRegistry.java @@ -12,10 +12,10 @@ *******************************************************************************/ package org.eclipse.kapua.service.user; -import org.eclipse.kapua.locator.KapuaLocator; - import javax.xml.bind.annotation.XmlRegistry; +import org.eclipse.kapua.locator.KapuaLocator; + /** * {@link User} xml factory class * @@ -35,25 +35,7 @@ public User newUser() { return userFactory.newEntity(null); } - /** - * Creates a new user creator instance - * - * @return - */ - public UserCreator newUserCreator() { - return userFactory.newCreator(null, null); - } - - /** - * Creates new user list result - * - * @return - */ - public UserListResult newUserListResult() { - return userFactory.newListResult(); - } - public UserQuery newQuery() { - return userFactory.newQuery(null); + return new UserQuery(null); } } diff --git a/service/user/api/src/main/java/org/eclipse/kapua/service/user/profile/UserProfile.java b/service/user/api/src/main/java/org/eclipse/kapua/service/user/profile/UserProfile.java index 35a082918b7..48a8045a7ee 100644 --- a/service/user/api/src/main/java/org/eclipse/kapua/service/user/profile/UserProfile.java +++ b/service/user/api/src/main/java/org/eclipse/kapua/service/user/profile/UserProfile.java @@ -20,22 +20,38 @@ @XmlRootElement @XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(factoryClass = UserProfileXmlRegistry.class, factoryMethod = "newUserProfile") -public interface UserProfile { - String TYPE = "userProfile"; +@XmlType +public class UserProfile { + + private String displayName; + private String phoneNumber; + private String email; @XmlElement(name = "displayName") - String getDisplayName(); + public String getDisplayName() { + return displayName; + } - void setDisplayName(String displayName); + public void setDisplayName(String displayName) { + this.displayName = displayName; + } @XmlElement(name = "phoneNumber") - String getPhoneNumber(); + public String getPhoneNumber() { + return phoneNumber; + } - void setPhoneNumber(String phoneNumber); + public void setPhoneNumber(String phoneNumber) { + this.phoneNumber = phoneNumber; + } @XmlElement(name = "email") - String getEmail(); + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } - void setEmail(String email); } diff --git a/service/user/api/src/main/java/org/eclipse/kapua/service/user/profile/UserProfileFactory.java b/service/user/api/src/main/java/org/eclipse/kapua/service/user/profile/UserProfileFactory.java deleted file mode 100644 index 20ee29390b9..00000000000 --- a/service/user/api/src/main/java/org/eclipse/kapua/service/user/profile/UserProfileFactory.java +++ /dev/null @@ -1,19 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2023, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.user.profile; - -import org.eclipse.kapua.model.KapuaObjectFactory; - -public interface UserProfileFactory extends KapuaObjectFactory { - UserProfile newUserProfile(); -} diff --git a/service/user/api/src/main/java/org/eclipse/kapua/service/user/profile/UserProfileXmlRegistry.java b/service/user/api/src/main/java/org/eclipse/kapua/service/user/profile/UserProfileXmlRegistry.java deleted file mode 100644 index 63aaa4f3865..00000000000 --- a/service/user/api/src/main/java/org/eclipse/kapua/service/user/profile/UserProfileXmlRegistry.java +++ /dev/null @@ -1,27 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2023, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.user.profile; - -import org.eclipse.kapua.locator.KapuaLocator; - -import javax.xml.bind.annotation.XmlRegistry; - -@XmlRegistry -public class UserProfileXmlRegistry { - - private final UserProfileFactory userProfileFactory = KapuaLocator.getInstance().getFactory(UserProfileFactory.class); - - public UserProfile newUserProfile() { - return userProfileFactory.newUserProfile(); - } -} diff --git a/service/user/internal/pom.xml b/service/user/internal/pom.xml index f68f05937fb..ceb2718242f 100644 --- a/service/user/internal/pom.xml +++ b/service/user/internal/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-user - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-user-internal diff --git a/service/user/internal/src/main/java/org/eclipse/kapua/service/user/internal/UserCreatorImpl.java b/service/user/internal/src/main/java/org/eclipse/kapua/service/user/internal/UserCreatorImpl.java deleted file mode 100644 index 7a1a6cbfa94..00000000000 --- a/service/user/internal/src/main/java/org/eclipse/kapua/service/user/internal/UserCreatorImpl.java +++ /dev/null @@ -1,138 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.user.internal; - -import org.eclipse.kapua.commons.model.AbstractKapuaNamedEntityCreator; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.user.User; -import org.eclipse.kapua.service.user.UserCreator; -import org.eclipse.kapua.service.user.UserStatus; -import org.eclipse.kapua.service.user.UserType; - -import java.util.Date; - -/** - * {@link UserCreator} implementation. - * - * @since 1.0.0 - */ -public class UserCreatorImpl extends AbstractKapuaNamedEntityCreator implements UserCreator { - - private static final long serialVersionUID = 4664940282892151008L; - - private UserStatus status; - private String displayName; - private String email; - private String phoneNumber; - private UserType userType = UserType.INTERNAL; - private String externalId; - private String externalUsername; - private Date expirationDate; - - /** - * Constructor - * - * @param accountId - * @param name - */ - public UserCreatorImpl(KapuaId accountId, String name) { - super(accountId, name); - - setStatus(UserStatus.ENABLED); - setUserType(UserType.INTERNAL); - } - - public UserCreatorImpl(KapuaId scopeId) { - this(scopeId, null); - } - - @Override - public UserStatus getStatus() { - return status; - } - - @Override - public void setStatus(UserStatus status) { - this.status = status; - } - - @Override - public String getDisplayName() { - return displayName; - } - - @Override - public void setDisplayName(String displayName) { - this.displayName = displayName; - } - - @Override - public String getEmail() { - return email; - } - - @Override - public void setEmail(String email) { - this.email = email; - } - - @Override - public String getPhoneNumber() { - return phoneNumber; - } - - @Override - public void setPhoneNumber(String phoneNumber) { - this.phoneNumber = phoneNumber; - } - - @Override - public UserType getUserType() { - return userType; - } - - @Override - public void setUserType(UserType userType) { - this.userType = userType; - } - - @Override - public String getExternalId() { - return externalId; - } - - @Override - public void setExternalId(String externalId) { - this.externalId = externalId; - } - - @Override - public String getExternalUsername() { - return externalUsername; - } - - @Override - public void setExternalUsername(String externalUsername) { - this.externalUsername = externalUsername; - } - - @Override - public Date getExpirationDate() { - return expirationDate; - } - - @Override - public void setExpirationDate(Date expirationDate) { - this.expirationDate = expirationDate; - } -} diff --git a/service/user/internal/src/main/java/org/eclipse/kapua/service/user/internal/UserFactoryImpl.java b/service/user/internal/src/main/java/org/eclipse/kapua/service/user/internal/UserFactoryImpl.java index e31df74a8dd..4c117eebef6 100644 --- a/service/user/internal/src/main/java/org/eclipse/kapua/service/user/internal/UserFactoryImpl.java +++ b/service/user/internal/src/main/java/org/eclipse/kapua/service/user/internal/UserFactoryImpl.java @@ -12,15 +12,12 @@ *******************************************************************************/ package org.eclipse.kapua.service.user.internal; +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaEntityCloneException; import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.service.user.User; -import org.eclipse.kapua.service.user.UserCreator; import org.eclipse.kapua.service.user.UserFactory; -import org.eclipse.kapua.service.user.UserListResult; -import org.eclipse.kapua.service.user.UserQuery; - -import javax.inject.Singleton; /** * {@link UserFactory} implementation. @@ -30,35 +27,11 @@ @Singleton public class UserFactoryImpl implements UserFactory { - @Override - public UserCreator newCreator(KapuaId scopeId, String name) { - UserCreator creator = newCreator(scopeId); - - creator.setName(name); - - return creator; - } - - @Override - public UserQuery newQuery(KapuaId scopeId) { - return new UserQueryImpl(scopeId); - } - - @Override - public UserListResult newListResult() { - return new UserListResultImpl(); - } - @Override public User newEntity(KapuaId scopeId) { return new UserImpl(scopeId); } - @Override - public UserCreator newCreator(KapuaId scopeId) { - return new UserCreatorImpl(scopeId); - } - @Override public User clone(User user) { try { diff --git a/service/user/internal/src/main/java/org/eclipse/kapua/service/user/internal/UserImplJpaRepository.java b/service/user/internal/src/main/java/org/eclipse/kapua/service/user/internal/UserImplJpaRepository.java index 4b5f2c2de8c..0e88bb9457c 100644 --- a/service/user/internal/src/main/java/org/eclipse/kapua/service/user/internal/UserImplJpaRepository.java +++ b/service/user/internal/src/main/java/org/eclipse/kapua/service/user/internal/UserImplJpaRepository.java @@ -12,6 +12,8 @@ *******************************************************************************/ package org.eclipse.kapua.service.user.internal; +import java.util.Optional; + import org.eclipse.kapua.commons.jpa.KapuaJpaRepositoryConfiguration; import org.eclipse.kapua.commons.jpa.KapuaNamedEntityJpaRepository; import org.eclipse.kapua.model.id.KapuaId; @@ -21,13 +23,12 @@ import org.eclipse.kapua.service.user.UserRepository; import org.eclipse.kapua.storage.TxContext; -import java.util.Optional; - public class UserImplJpaRepository extends KapuaNamedEntityJpaRepository implements UserRepository { + public UserImplJpaRepository(KapuaJpaRepositoryConfiguration jpaRepoConfig) { - super(UserImpl.class, User.TYPE, () -> new UserListResultImpl(), jpaRepoConfig); + super(UserImpl.class, User.TYPE, () -> new UserListResult(), jpaRepoConfig); } @Override diff --git a/service/user/internal/src/main/java/org/eclipse/kapua/service/user/internal/UserListResultImpl.java b/service/user/internal/src/main/java/org/eclipse/kapua/service/user/internal/UserListResultImpl.java deleted file mode 100644 index ac333e8b44e..00000000000 --- a/service/user/internal/src/main/java/org/eclipse/kapua/service/user/internal/UserListResultImpl.java +++ /dev/null @@ -1,28 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.user.internal; - -import org.eclipse.kapua.commons.model.query.KapuaListResultImpl; -import org.eclipse.kapua.service.user.User; -import org.eclipse.kapua.service.user.UserListResult; - -/** - * User list result implementation. - * - * @since 1.0 - * - */ -public class UserListResultImpl extends KapuaListResultImpl implements UserListResult { - - private static final long serialVersionUID = 2231053707705207563L; -} diff --git a/service/user/internal/src/main/java/org/eclipse/kapua/service/user/internal/UserMatchPredicateImpl.java b/service/user/internal/src/main/java/org/eclipse/kapua/service/user/internal/UserMatchPredicateImpl.java deleted file mode 100644 index 4c7d940880a..00000000000 --- a/service/user/internal/src/main/java/org/eclipse/kapua/service/user/internal/UserMatchPredicateImpl.java +++ /dev/null @@ -1,42 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2020, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.user.internal; - -import org.eclipse.kapua.commons.model.query.predicate.AbstractMatchPredicate; -import org.eclipse.kapua.service.user.UserAttributes; -import org.eclipse.kapua.service.user.UserMatchPredicate; - -import java.util.Arrays; - -public class UserMatchPredicateImpl extends AbstractMatchPredicate implements UserMatchPredicate { - - /** - * Constructor. - * - * @param matchTerm - * @since 1.3.0 - */ - public UserMatchPredicateImpl(T matchTerm) { - this.attributeNames = Arrays.asList( - UserAttributes.NAME, - UserAttributes.EMAIL, - UserAttributes.PHONE_NUMBER, - UserAttributes.DISPLAY_NAME, - UserAttributes.EXTERNAL_ID, - UserAttributes.DESCRIPTION, - UserAttributes.EXTERNAL_USERNAME - ); - this.matchTerm = matchTerm; - } - -} diff --git a/service/user/internal/src/main/java/org/eclipse/kapua/service/user/internal/UserModule.java b/service/user/internal/src/main/java/org/eclipse/kapua/service/user/internal/UserModule.java index 2a66764a54e..15bf9853960 100644 --- a/service/user/internal/src/main/java/org/eclipse/kapua/service/user/internal/UserModule.java +++ b/service/user/internal/src/main/java/org/eclipse/kapua/service/user/internal/UserModule.java @@ -28,7 +28,6 @@ import org.eclipse.kapua.commons.jpa.KapuaJpaTxManagerFactory; import org.eclipse.kapua.commons.jpa.NamedCacheFactory; import org.eclipse.kapua.commons.model.domains.Domains; -import org.eclipse.kapua.commons.service.event.store.api.EventStoreFactory; import org.eclipse.kapua.commons.service.event.store.api.EventStoreRecordRepository; import org.eclipse.kapua.commons.service.event.store.internal.EventStoreServiceImpl; import org.eclipse.kapua.event.ServiceEventBus; @@ -37,7 +36,6 @@ import org.eclipse.kapua.model.domain.Domain; import org.eclipse.kapua.model.domain.DomainEntry; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; import org.eclipse.kapua.service.user.UserFactory; import org.eclipse.kapua.service.user.UserRepository; import org.eclipse.kapua.service.user.UserService; @@ -72,7 +70,6 @@ public Domain userDomain() { public UserService userService( Map, ServiceConfigurationManager> serviceConfigurationManagersByServiceClass, AuthorizationService authorizationService, - PermissionFactory permissionFactory, UserRepository userRepository, UserFactory userFactory, EventStorer eventStorer, @@ -80,7 +77,6 @@ public UserService userService( return new UserServiceImpl( serviceConfigurationManagersByServiceClass.get(UserService.class), authorizationService, - permissionFactory, jpaTxManagerFactory.create("kapua-user"), userRepository, userFactory, @@ -90,9 +86,7 @@ public UserService userService( @ProvidesIntoSet public ServiceModule userServiceModule(UserService userService, AuthorizationService authorizationService, - PermissionFactory permissionFactory, KapuaJpaTxManagerFactory txManagerFactory, - EventStoreFactory eventStoreFactory, EventStoreRecordRepository eventStoreRecordRepository, ServiceEventBus serviceEventBus, KapuaUserSetting kapuaUserSetting, @@ -104,9 +98,7 @@ public ServiceModule userServiceModule(UserService userService, new ServiceEventHouseKeeperFactoryImpl( new EventStoreServiceImpl( authorizationService, - permissionFactory, txManagerFactory.create("kapua-user"), - eventStoreFactory, eventStoreRecordRepository ), txManagerFactory.create("kapua-user"), diff --git a/service/user/internal/src/main/java/org/eclipse/kapua/service/user/internal/UserQueryImpl.java b/service/user/internal/src/main/java/org/eclipse/kapua/service/user/internal/UserQueryImpl.java deleted file mode 100644 index b7ad5afa1a6..00000000000 --- a/service/user/internal/src/main/java/org/eclipse/kapua/service/user/internal/UserQueryImpl.java +++ /dev/null @@ -1,50 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.user.internal; - -import org.eclipse.kapua.commons.model.query.AbstractKapuaNamedQuery; -import org.eclipse.kapua.model.id.KapuaId; -import org.eclipse.kapua.service.user.UserQuery; - -/** - * {@link UserQuery} implementation. - * - * @since 1.0.0 - */ -public class UserQueryImpl extends AbstractKapuaNamedQuery implements UserQuery { - - /** - * Constructor. - * - * @since 1.0.0 - */ - private UserQueryImpl() { - super(); - } - - /** - * Constructor - * - * @param scopeId The {@link #getScopeId()}. - * @since 1.0.0 - */ - public UserQueryImpl(KapuaId scopeId) { - this(); - setScopeId(scopeId); - } - - @Override - public UserMatchPredicateImpl matchPredicate(T matchTerm) { - return new UserMatchPredicateImpl<>(matchTerm); - } -} diff --git a/service/user/internal/src/main/java/org/eclipse/kapua/service/user/internal/UserServiceConfigurationManagerModule.java b/service/user/internal/src/main/java/org/eclipse/kapua/service/user/internal/UserServiceConfigurationManagerModule.java index b64ed24b26b..f8fc1a14f82 100644 --- a/service/user/internal/src/main/java/org/eclipse/kapua/service/user/internal/UserServiceConfigurationManagerModule.java +++ b/service/user/internal/src/main/java/org/eclipse/kapua/service/user/internal/UserServiceConfigurationManagerModule.java @@ -29,7 +29,6 @@ import org.eclipse.kapua.commons.jpa.KapuaJpaTxManagerFactory; import org.eclipse.kapua.commons.model.domains.Domains; import org.eclipse.kapua.commons.util.xml.XmlUtil; -import org.eclipse.kapua.service.user.UserFactory; import org.eclipse.kapua.service.user.UserRepository; import org.eclipse.kapua.service.user.UserService; @@ -54,7 +53,6 @@ protected void configureModule() { @Singleton ServiceConfigurationManager userServiceConfigurationManager( KapuaJpaTxManagerFactory jpaTxManagerFactory, - UserFactory userFactory, RootUserTester rootUserTester, AccountRelativeFinder accountRelativeFinder, UserRepository userRepository, @@ -73,7 +71,6 @@ ServiceConfigurationManager userServiceConfigurationManager( rootUserTester, accountRelativeFinder, new UsedEntitiesCounterImpl( - userFactory, userRepository ), new ResourceBasedServiceConfigurationMetadataProvider(xmlUtil))); diff --git a/service/user/internal/src/main/java/org/eclipse/kapua/service/user/internal/UserServiceImpl.java b/service/user/internal/src/main/java/org/eclipse/kapua/service/user/internal/UserServiceImpl.java index ffcce384bd4..e1a5324e87b 100644 --- a/service/user/internal/src/main/java/org/eclipse/kapua/service/user/internal/UserServiceImpl.java +++ b/service/user/internal/src/main/java/org/eclipse/kapua/service/user/internal/UserServiceImpl.java @@ -13,6 +13,11 @@ *******************************************************************************/ package org.eclipse.kapua.service.user.internal; +import java.util.Objects; +import java.util.Optional; + +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaDuplicateExternalIdException; import org.eclipse.kapua.KapuaDuplicateExternalUsernameException; import org.eclipse.kapua.KapuaDuplicateNameException; @@ -34,7 +39,7 @@ import org.eclipse.kapua.model.id.KapuaId; import org.eclipse.kapua.model.query.KapuaQuery; import org.eclipse.kapua.service.authorization.AuthorizationService; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; +import org.eclipse.kapua.service.authorization.permission.Permission; import org.eclipse.kapua.service.user.User; import org.eclipse.kapua.service.user.UserCreator; import org.eclipse.kapua.service.user.UserFactory; @@ -48,10 +53,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.inject.Singleton; -import java.util.Objects; -import java.util.Optional; - /** * {@link UserService} implementation. * @@ -68,11 +69,10 @@ public class UserServiceImpl extends KapuaConfigurableServiceBase implements Use public UserServiceImpl( ServiceConfigurationManager serviceConfigurationManager, AuthorizationService authorizationService, - PermissionFactory permissionFactory, TxManager txManager, UserRepository userRepository, UserFactory userFactory, EventStorer eventStorer) { - super(txManager, serviceConfigurationManager, Domains.USER, authorizationService, permissionFactory); + super(txManager, serviceConfigurationManager, Domains.USER, authorizationService); this.userRepository = userRepository; this.userFactory = userFactory; this.eventStorer = eventStorer; @@ -102,7 +102,7 @@ public User create(UserCreator userCreator) throws KapuaException { ArgumentValidator.isEmptyOrNull(userCreator.getExternalUsername(), "userCreator.externalUsername"); } // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.USER, Actions.write, userCreator.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.USER, Actions.write, userCreator.getScopeId())); return txManager.execute(tx -> { // Check entity limit @@ -174,7 +174,7 @@ public User update(User user) throws KapuaException { ArgumentValidator.isEmptyOrNull(user.getExternalUsername(), "user.externalUsername"); } // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.USER, Actions.write, user.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.USER, Actions.write, user.getScopeId())); return txManager.execute( tx -> { @@ -246,7 +246,7 @@ public void delete(KapuaId scopeId, KapuaId userId) throws KapuaException { ArgumentValidator.notNull(scopeId.getId(), "user.scopeId"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.USER, Actions.delete, scopeId)); + authorizationService.checkPermission(new Permission(Domains.USER, Actions.delete, scopeId)); txManager.execute( tx -> { @@ -273,7 +273,7 @@ public User find(KapuaId scopeId, KapuaId userId) ArgumentValidator.notNull(scopeId, "scopeId"); ArgumentValidator.notNull(userId, "userId"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.USER, Actions.read, scopeId)); + authorizationService.checkPermission(new Permission(Domains.USER, Actions.read, scopeId)); // Do the find return txManager.execute(tx -> userRepository.find(tx, scopeId, userId)) @@ -313,7 +313,7 @@ public UserListResult query(KapuaQuery query) // Argument Validation ArgumentValidator.notNull(query, "query"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.USER, Actions.read, query.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.USER, Actions.read, query.getScopeId())); // Do query return txManager.execute(tx -> userRepository.query(tx, query)); } @@ -324,7 +324,7 @@ public long count(KapuaQuery query) // Argument Validator ArgumentValidator.notNull(query, "query"); // Check Access - authorizationService.checkPermission(permissionFactory.newPermission(Domains.USER, Actions.read, query.getScopeId())); + authorizationService.checkPermission(new Permission(Domains.USER, Actions.read, query.getScopeId())); // Do count return txManager.execute(tx -> userRepository.count(tx, query)); } @@ -335,7 +335,7 @@ public long count(KapuaQuery query) private Optional checkReadAccess(Optional user) throws KapuaException { if (user.isPresent()) { - authorizationService.checkPermission(permissionFactory.newPermission(Domains.USER, Actions.read, user.get().getScopeId())); + authorizationService.checkPermission(new Permission(Domains.USER, Actions.read, user.get().getScopeId())); } return user; } @@ -366,7 +366,7 @@ public void onKapuaEvent(ServiceEvent kapuaEvent) throws KapuaException { } private void deleteUserByAccountId(KapuaId scopeId, KapuaId accountId) throws KapuaException { - UserQuery query = new UserQueryImpl(accountId); + UserQuery query = new UserQuery(accountId); UserListResult usersToDelete = query(query); for (User u : usersToDelete.getItems()) { diff --git a/service/user/internal/src/main/java/org/eclipse/kapua/service/user/internal/profile/UserProfileFactoryImpl.java b/service/user/internal/src/main/java/org/eclipse/kapua/service/user/internal/profile/UserProfileFactoryImpl.java deleted file mode 100644 index e0f690b580d..00000000000 --- a/service/user/internal/src/main/java/org/eclipse/kapua/service/user/internal/profile/UserProfileFactoryImpl.java +++ /dev/null @@ -1,26 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2023, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.user.internal.profile; - -import org.eclipse.kapua.service.user.profile.UserProfile; -import org.eclipse.kapua.service.user.profile.UserProfileFactory; - -import javax.inject.Singleton; - -@Singleton -public class UserProfileFactoryImpl implements UserProfileFactory { - @Override - public UserProfile newUserProfile() { - return new UserProfileImpl(); - } -} diff --git a/service/user/internal/src/main/java/org/eclipse/kapua/service/user/internal/profile/UserProfileImpl.java b/service/user/internal/src/main/java/org/eclipse/kapua/service/user/internal/profile/UserProfileImpl.java deleted file mode 100644 index 530d632c112..00000000000 --- a/service/user/internal/src/main/java/org/eclipse/kapua/service/user/internal/profile/UserProfileImpl.java +++ /dev/null @@ -1,57 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2023, 2022 Eurotech and/or its affiliates and others - * - * This program and the accompanying materials are made - * available under the terms of the Eclipse Public License 2.0 - * which is available at https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * Eurotech - initial API and implementation - *******************************************************************************/ -package org.eclipse.kapua.service.user.internal.profile; - -import org.eclipse.kapua.service.user.profile.UserProfile; - -public class UserProfileImpl implements UserProfile { - private String displayName; - private String phoneNumber; - private String email; - - - @Override - public String getDisplayName() { - return displayName; - } - - - @Override - public void setDisplayName(String displayName) { - this.displayName = displayName; - } - - - @Override - public String getPhoneNumber() { - return phoneNumber; - } - - - @Override - public void setPhoneNumber(String phoneNumber) { - this.phoneNumber = phoneNumber; - } - - - @Override - public String getEmail() { - return email; - } - - - @Override - public void setEmail(String email) { - this.email = email; - } -} diff --git a/service/user/internal/src/main/java/org/eclipse/kapua/service/user/internal/profile/UserProfileModule.java b/service/user/internal/src/main/java/org/eclipse/kapua/service/user/internal/profile/UserProfileModule.java index d1007628307..f4e53b0c895 100644 --- a/service/user/internal/src/main/java/org/eclipse/kapua/service/user/internal/profile/UserProfileModule.java +++ b/service/user/internal/src/main/java/org/eclipse/kapua/service/user/internal/profile/UserProfileModule.java @@ -13,13 +13,12 @@ package org.eclipse.kapua.service.user.internal.profile; import org.eclipse.kapua.commons.core.AbstractKapuaModule; -import org.eclipse.kapua.service.user.profile.UserProfileFactory; import org.eclipse.kapua.service.user.profile.UserProfileService; public class UserProfileModule extends AbstractKapuaModule { + @Override protected void configureModule() { bind(UserProfileService.class).to(UserProfileServiceImpl.class); - bind(UserProfileFactory.class).to(UserProfileFactoryImpl.class); } } diff --git a/service/user/internal/src/main/java/org/eclipse/kapua/service/user/internal/profile/UserProfileServiceImpl.java b/service/user/internal/src/main/java/org/eclipse/kapua/service/user/internal/profile/UserProfileServiceImpl.java index 0e67b2d734c..41852355686 100644 --- a/service/user/internal/src/main/java/org/eclipse/kapua/service/user/internal/profile/UserProfileServiceImpl.java +++ b/service/user/internal/src/main/java/org/eclipse/kapua/service/user/internal/profile/UserProfileServiceImpl.java @@ -12,7 +12,9 @@ *******************************************************************************/ package org.eclipse.kapua.service.user.internal.profile; -import com.google.common.base.Strings; +import javax.inject.Inject; +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaEntityNotFoundException; import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.commons.security.KapuaSecurityUtils; @@ -21,21 +23,18 @@ import org.eclipse.kapua.service.user.User; import org.eclipse.kapua.service.user.UserService; import org.eclipse.kapua.service.user.profile.UserProfile; -import org.eclipse.kapua.service.user.profile.UserProfileFactory; import org.eclipse.kapua.service.user.profile.UserProfileService; -import javax.inject.Inject; -import javax.inject.Singleton; +import com.google.common.base.Strings; @Singleton public class UserProfileServiceImpl implements UserProfileService { + private final UserService userService; - private final UserProfileFactory userProfileFactory; @Inject - public UserProfileServiceImpl(UserService userService, UserProfileFactory userProfileFactory) { + public UserProfileServiceImpl(UserService userService) { this.userService = userService; - this.userProfileFactory = userProfileFactory; } @Override @@ -57,7 +56,6 @@ public void changeUserProfile(UserProfile userProfile) throws KapuaException { }); } - @Override public UserProfile getUserProfile() throws KapuaException { return KapuaSecurityUtils.doPrivileged(() -> { @@ -66,7 +64,7 @@ public UserProfile getUserProfile() throws KapuaException { throw new KapuaEntityNotFoundException(User.TYPE, KapuaSecurityUtils.getSession().getUserId()); } - UserProfile userProfile = userProfileFactory.newUserProfile(); + UserProfile userProfile = new UserProfile(); userProfile.setDisplayName(user.getDisplayName()); userProfile.setEmail(user.getEmail()); userProfile.setPhoneNumber(user.getPhoneNumber()); diff --git a/service/user/pom.xml b/service/user/pom.xml index 30aa951bdc4..3af9b91ed7e 100644 --- a/service/user/pom.xml +++ b/service/user/pom.xml @@ -19,7 +19,7 @@ org.eclipse.kapua kapua-service - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT pom diff --git a/service/user/test-steps/pom.xml b/service/user/test-steps/pom.xml index 7043a39cf25..d4f79ac9e26 100644 --- a/service/user/test-steps/pom.xml +++ b/service/user/test-steps/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-user - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-user-test-steps diff --git a/service/user/test-steps/src/main/java/org/eclipse/kapua/service/user/steps/UserProfileServiceTest.java b/service/user/test-steps/src/main/java/org/eclipse/kapua/service/user/steps/UserProfileServiceTest.java index bc54270245d..cb0385f2c8f 100644 --- a/service/user/test-steps/src/main/java/org/eclipse/kapua/service/user/steps/UserProfileServiceTest.java +++ b/service/user/test-steps/src/main/java/org/eclipse/kapua/service/user/steps/UserProfileServiceTest.java @@ -12,52 +12,47 @@ *******************************************************************************/ package org.eclipse.kapua.service.user.steps; -import io.cucumber.java.After; -import io.cucumber.java.Before; -import io.cucumber.java.Scenario; -import io.cucumber.java.en.Then; +import javax.inject.Inject; +import javax.inject.Singleton; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.locator.KapuaLocator; import org.eclipse.kapua.qa.common.StepData; import org.eclipse.kapua.qa.common.TestBase; import org.eclipse.kapua.qa.common.cucumber.CucUserProfile; import org.eclipse.kapua.service.user.profile.UserProfile; -import org.eclipse.kapua.service.user.profile.UserProfileFactory; import org.eclipse.kapua.service.user.profile.UserProfileService; import org.junit.Assert; -import javax.inject.Inject; -import javax.inject.Singleton; +import io.cucumber.java.After; +import io.cucumber.java.Before; +import io.cucumber.java.Scenario; +import io.cucumber.java.en.Then; @Singleton public class UserProfileServiceTest extends TestBase { - private UserProfileService userProfileService; - private UserProfileFactory userProfileFactory; + private UserProfileService userProfileService; @Inject public UserProfileServiceTest(StepData stepData) { super(stepData); } - @After(value = "@setup") public void setServices() { KapuaLocator locator = KapuaLocator.getInstance(); userProfileService = locator.getService(UserProfileService.class); - userProfileFactory = locator.getFactory(UserProfileFactory.class); } - @Before public void beforeScenario(Scenario scenario) { updateScenario(scenario); } - @Then("I change the profile to the following") public void iChangeTheUserProfileToTheFollowing(CucUserProfile cucUserProfile) throws Exception { - UserProfile userProfile = userProfileFactory.newUserProfile(); + UserProfile userProfile = new UserProfile(); userProfile.setDisplayName(cucUserProfile.getDisplayName()); userProfile.setEmail(cucUserProfile.getEmail()); userProfile.setPhoneNumber(cucUserProfile.getPhoneNumber()); @@ -68,7 +63,6 @@ public void iChangeTheUserProfileToTheFollowing(CucUserProfile cucUserProfile) t } } - @Then("I read the following user profile") public void iReadTheFollowingUserProfile(CucUserProfile expectedUserProfile) throws KapuaException { UserProfile actualUserProfile = userProfileService.getUserProfile(); diff --git a/service/user/test-steps/src/main/java/org/eclipse/kapua/service/user/steps/UserRoleServiceSteps.java b/service/user/test-steps/src/main/java/org/eclipse/kapua/service/user/steps/UserRoleServiceSteps.java index aa3bef3a178..de8d193cb45 100644 --- a/service/user/test-steps/src/main/java/org/eclipse/kapua/service/user/steps/UserRoleServiceSteps.java +++ b/service/user/test-steps/src/main/java/org/eclipse/kapua/service/user/steps/UserRoleServiceSteps.java @@ -12,15 +12,19 @@ *******************************************************************************/ package org.eclipse.kapua.service.user.steps; +import java.util.ArrayList; + +import javax.inject.Inject; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.locator.KapuaLocator; -import org.eclipse.kapua.qa.common.TestBase; import org.eclipse.kapua.qa.common.StepData; -import org.eclipse.kapua.service.authorization.access.AccessRoleService; -import org.eclipse.kapua.service.authorization.access.AccessRoleFactory; +import org.eclipse.kapua.qa.common.TestBase; import org.eclipse.kapua.service.authorization.access.AccessInfo; -import org.eclipse.kapua.service.authorization.access.AccessRoleCreator; import org.eclipse.kapua.service.authorization.access.AccessRole; +import org.eclipse.kapua.service.authorization.access.AccessRoleCreator; +import org.eclipse.kapua.service.authorization.access.AccessRoleFactory; +import org.eclipse.kapua.service.authorization.access.AccessRoleService; import org.eclipse.kapua.service.authorization.role.Role; import org.eclipse.kapua.service.user.User; import org.junit.Assert; @@ -33,9 +37,6 @@ import io.cucumber.java.en.And; import io.cucumber.java.en.Then; -import javax.inject.Inject; -import java.util.ArrayList; - @Singleton public class UserRoleServiceSteps extends TestBase { @@ -49,7 +50,7 @@ public UserRoleServiceSteps(StepData stepData) { super(stepData); } - @After(value="@setup") + @After(value = "@setup") public void setServices() { KapuaLocator locator = KapuaLocator.getInstance(); accessRoleService = locator.getService(AccessRoleService.class); @@ -66,25 +67,25 @@ public void addRoleToUser(String roleName, String userName) throws Exception { AccessInfo accessInfo = (AccessInfo) stepData.get("AccessInfo"); Role role = (Role) stepData.get("Role"); User user = (User) stepData.get("User"); - AccessRoleCreator accessRoleCreator = accessRoleFactory.newCreator(getCurrentScopeId()); - accessRoleCreator.setAccessInfoId(accessInfo.getId()); - accessRoleCreator.setRoleId(role.getId()); - stepData.put("AccessRoleCreator", accessRoleCreator); - Assert.assertEquals(roleName, role.getName()); - Assert.assertEquals(userName, user.getName()); - try { - primeException(); - stepData.remove(ACCESS_ROLE); - AccessRole accessRole = accessRoleService.create(accessRoleCreator); - stepData.put(ACCESS_ROLE, accessRole); - stepData.put("AccessRoleId", accessRole.getId()); - } catch (KapuaException ex) { - verifyException(ex); - } + AccessRoleCreator accessRoleCreator = new AccessRoleCreator(getCurrentScopeId()); + accessRoleCreator.setAccessInfoId(accessInfo.getId()); + accessRoleCreator.setRoleId(role.getId()); + stepData.put("AccessRoleCreator", accessRoleCreator); + Assert.assertEquals(roleName, role.getName()); + Assert.assertEquals(userName, user.getName()); + try { + primeException(); + stepData.remove(ACCESS_ROLE); + AccessRole accessRole = accessRoleService.create(accessRoleCreator); + stepData.put(ACCESS_ROLE, accessRole); + stepData.put("AccessRoleId", accessRole.getId()); + } catch (KapuaException ex) { + verifyException(ex); + } } @Then("Access role is not found") - public void accessRoleIsNotFound() throws Exception{ + public void accessRoleIsNotFound() throws Exception { AccessRole accessRole = (AccessRole) stepData.get(ACCESS_ROLE); try { Assert.assertEquals(null, accessRoleService.find(getCurrentScopeId(), accessRole.getId())); @@ -98,7 +99,7 @@ public void iAddAccessRoleToUsers(String roleName) throws Exception { ArrayList accessInfoList = (ArrayList) stepData.get("AccessInfoList"); ArrayList accessRoleList = new ArrayList<>(); Role role = (Role) stepData.get("Role"); - AccessRoleCreator accessRoleCreator = accessRoleFactory.newCreator(getCurrentScopeId()); + AccessRoleCreator accessRoleCreator = new AccessRoleCreator(getCurrentScopeId()); accessRoleCreator.setRoleId(role.getId()); stepData.put("AccessRoleCreator", accessRoleCreator); Assert.assertEquals(roleName, role.getName()); diff --git a/service/user/test-steps/src/main/java/org/eclipse/kapua/service/user/steps/UserServiceSteps.java b/service/user/test-steps/src/main/java/org/eclipse/kapua/service/user/steps/UserServiceSteps.java index 645205764f2..89601a86587 100644 --- a/service/user/test-steps/src/main/java/org/eclipse/kapua/service/user/steps/UserServiceSteps.java +++ b/service/user/test-steps/src/main/java/org/eclipse/kapua/service/user/steps/UserServiceSteps.java @@ -12,14 +12,21 @@ *******************************************************************************/ package org.eclipse.kapua.service.user.steps; -import com.google.inject.Singleton; -import io.cucumber.java.After; -import io.cucumber.java.Before; -import io.cucumber.java.Scenario; -import io.cucumber.java.en.And; -import io.cucumber.java.en.Given; -import io.cucumber.java.en.Then; -import io.cucumber.java.en.When; +import java.math.BigInteger; +import java.text.MessageFormat; +import java.time.LocalDate; +import java.time.ZoneId; +import java.util.ArrayList; +import java.util.Date; +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 javax.inject.Inject; + import org.eclipse.kapua.KapuaException; import org.eclipse.kapua.commons.model.id.KapuaEid; import org.eclipse.kapua.commons.security.KapuaSecurityUtils; @@ -39,14 +46,12 @@ import org.eclipse.kapua.qa.common.cucumber.CucUser; import org.eclipse.kapua.service.account.Account; import org.eclipse.kapua.service.authentication.AuthenticationService; -import org.eclipse.kapua.service.authentication.CredentialsFactory; import org.eclipse.kapua.service.authentication.LoginCredentials; +import org.eclipse.kapua.service.authentication.UsernamePasswordCredentials; import org.eclipse.kapua.service.authentication.credential.Credential; import org.eclipse.kapua.service.authentication.credential.CredentialAttributes; import org.eclipse.kapua.service.authentication.credential.CredentialCreator; -import org.eclipse.kapua.service.authentication.credential.CredentialFactory; import org.eclipse.kapua.service.authentication.credential.CredentialListResult; -import org.eclipse.kapua.service.authentication.credential.CredentialQuery; import org.eclipse.kapua.service.authentication.credential.CredentialService; import org.eclipse.kapua.service.authentication.credential.CredentialStatus; import org.eclipse.kapua.service.authentication.credential.mfa.MfaOption; @@ -54,17 +59,13 @@ import org.eclipse.kapua.service.authentication.credential.mfa.MfaOptionFactory; import org.eclipse.kapua.service.authentication.credential.mfa.MfaOptionService; import org.eclipse.kapua.service.authentication.credential.mfa.shiro.MfaOptionFactoryImpl; -import org.eclipse.kapua.service.authentication.credential.shiro.CredentialQueryImpl; import org.eclipse.kapua.service.authorization.access.AccessInfoCreator; -import org.eclipse.kapua.service.authorization.access.AccessInfoFactory; import org.eclipse.kapua.service.authorization.access.AccessInfoService; import org.eclipse.kapua.service.authorization.access.AccessPermission; import org.eclipse.kapua.service.authorization.access.AccessPermissionAttributes; -import org.eclipse.kapua.service.authorization.access.AccessPermissionQuery; import org.eclipse.kapua.service.authorization.access.AccessPermissionService; -import org.eclipse.kapua.service.authorization.access.shiro.AccessPermissionQueryImpl; import org.eclipse.kapua.service.authorization.permission.Permission; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; +import org.eclipse.kapua.service.authorization.permission.shiro.PermissionImpl; import org.eclipse.kapua.service.user.User; import org.eclipse.kapua.service.user.UserAttributes; import org.eclipse.kapua.service.user.UserCreator; @@ -75,19 +76,15 @@ import org.eclipse.kapua.service.user.UserStatus; import org.junit.Assert; -import javax.inject.Inject; -import java.math.BigInteger; -import java.text.MessageFormat; -import java.time.LocalDate; -import java.time.ZoneId; -import java.util.ArrayList; -import java.util.Date; -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 com.google.inject.Singleton; + +import io.cucumber.java.After; +import io.cucumber.java.Before; +import io.cucumber.java.Scenario; +import io.cucumber.java.en.And; +import io.cucumber.java.en.Given; +import io.cucumber.java.en.Then; +import io.cucumber.java.en.When; /** * Implementation of Gherkin steps used in user test scenarios. @@ -122,11 +119,7 @@ public class UserServiceSteps extends TestBase { */ private AccessInfoService accessInfoService; private AuthenticationService authenticationService; - private AccessInfoFactory accessInfoFactory; - private PermissionFactory permissionFactory; private CredentialService credentialService; - private CredentialFactory credentialFactory; - private CredentialsFactory credentialsFactory; private AccessPermissionService accessPermissionService; @Inject @@ -146,10 +139,6 @@ public void setServices() { authenticationService = locator.getService(AuthenticationService.class); credentialService = locator.getService(CredentialService.class); accessInfoService = locator.getService(AccessInfoService.class); - accessInfoFactory = locator.getFactory(AccessInfoFactory.class); - permissionFactory = locator.getFactory(PermissionFactory.class); - credentialFactory = locator.getFactory(CredentialFactory.class); - credentialsFactory = locator.getFactory(CredentialsFactory.class); accessPermissionService = locator.getService(AccessPermissionService.class); } @@ -164,7 +153,7 @@ public void crateUserWithName(String userName, int scopeId) { String userEmail = MessageFormat.format("testuser_{0,number,#}@organization.com", now); String displayName = MessageFormat.format("User Display Name {0}", now); KapuaEid scpId = new KapuaEid(BigInteger.valueOf(scopeId)); - UserCreator uc = userFactory.newCreator(scpId, userName); + UserCreator uc = new UserCreator(scpId, userName); uc.setDisplayName(displayName); uc.setEmail(userEmail); uc.setPhoneNumber("+1 555 123 4567"); @@ -242,7 +231,7 @@ public void searchForUsers() throws Exception { KapuaId scpId = DEFAULT_ID; Set iFoundUsers; stepData.remove(USER_LIST); - KapuaQuery query = userFactory.newQuery(scpId); + KapuaQuery query = new UserQuery(scpId); UserListResult queryResult = userService.query(query); iFoundUsers = new HashSet<>(); List users = queryResult.getItems(); @@ -335,7 +324,7 @@ public void searchUserByName() throws Exception { @When("I query for users in scope with id {int}") public void queryForUsers(int scopeId) throws Exception { stepData.remove(USER_LIST); - UserQuery query = userFactory.newQuery(new KapuaEid(BigInteger.valueOf(scopeId))); + UserQuery query = new UserQuery(new KapuaEid(BigInteger.valueOf(scopeId))); UserListResult queryResult = userService.query(query); Set iFoundUsers = new HashSet<>(); for (User userItem : queryResult.getItems()) { @@ -346,7 +335,7 @@ public void queryForUsers(int scopeId) throws Exception { @When("I count users in scope {int}") public void countUsersInScope(int scopeId) throws Exception { - UserQuery query = userFactory.newQuery(new KapuaEid(BigInteger.valueOf(scopeId))); + UserQuery query = new UserQuery(new KapuaEid(BigInteger.valueOf(scopeId))); stepData.updateCount((int) userService.count(query)); } @@ -464,7 +453,7 @@ public void searchForLastCreatedCredentials() throws Exception { ComparableUser comparableUser = (ComparableUser) stepData.get(LAST_USER); primeException(); try { - CredentialQuery credentialQuery = new CredentialQueryImpl(getCurrentScopeId()); + KapuaQuery credentialQuery = new KapuaQuery(getCurrentScopeId()); credentialQuery.setPredicate(credentialQuery.attributePredicate(CredentialAttributes.USER_ID, comparableUser.getUser().getId())); CredentialListResult credentials = credentialService.query(credentialQuery); stepData.put("CredentialsListFound", credentials); @@ -518,8 +507,8 @@ public void queryForLastAddedPermission() throws Exception { Permission permission = (Permission) stepData.get(LAST_PERMISSION_ADDED_TO_USER); primeException(); try { - AccessPermissionQuery query = new AccessPermissionQueryImpl(getCurrentScopeId()); - query.setPredicate(query.attributePredicate(AccessPermissionAttributes.PERMISSION, permission)); + KapuaQuery query = new KapuaQuery(getCurrentScopeId()); + query.setPredicate(query.attributePredicate(AccessPermissionAttributes.PERMISSION, new PermissionImpl(permission))); AccessPermission accessPermission = accessPermissionService.query(query).getFirstItem(); stepData.put(LAST_FOUND_ACCESS_PERMISSION, accessPermission); } catch (KapuaException ex) { @@ -577,7 +566,7 @@ public void givenGenericUser(List userList) throws Exception { @When("I login as user with name {string} and password {string}") public void loginUser(String userName, String password) throws Exception { - LoginCredentials credentials = credentialsFactory.newUsernamePasswordCredentials(userName, password); + LoginCredentials credentials = new UsernamePasswordCredentials(userName, password); authenticationService.logout(); primeException(); try { @@ -590,7 +579,7 @@ public void loginUser(String userName, String password) throws Exception { @When("I try to login as user with name {string} with wrong password {int} times") public void loginUserNTimes(String userName, int n) throws Exception { String password = "wrongPassword"; - LoginCredentials credentials = credentialsFactory.newUsernamePasswordCredentials(userName, password); + LoginCredentials credentials = new UsernamePasswordCredentials(userName, password); authenticationService.logout(); for (int i = 0; i < n; i++) { primeException(); @@ -717,12 +706,12 @@ public void logout() throws KapuaException { // ******************* /** - * Extract list of users form step parameter table and create those users in - * kapua. - * Operation is performed in privileged mode, without access and authorization checks. + * Extract list of users form step parameter table and create those users in kapua. Operation is performed in privileged mode, without access and authorization checks. * - * @param userList list of users in step - * @param account account in which users are created + * @param userList + * list of users in step + * @param account + * account in which users are created * @return Set of created users as ComparableUser Set * @throws Exception */ @@ -751,11 +740,12 @@ private HashSet createUsersInList(List userList, Accoun } /** - * Create User object with user data filed with quasi random data for user name, - * email, display name. Scope id and user id is set to test wide id. + * Create User object with user data filed with quasi random data for user name, email, display name. Scope id and user id is set to test wide id. * - * @param userId unique user id - * @param scopeId user scope id + * @param userId + * unique user id + * @param scopeId + * user scope id * @return User instance */ private User createUserInstance(int userId, int scopeId) { @@ -779,7 +769,7 @@ private User createUserInstance(int userId, int scopeId) { * @return UserCreator instance for creating user */ private UserCreator userCreatorCreator(String name, String displayName, String email, String phone, KapuaId scopeId) { - UserCreator userCreator = userFactory.newCreator(scopeId, name); + UserCreator userCreator = new UserCreator(scopeId, name); userCreator.setName(name); userCreator.setDisplayName(displayName); userCreator.setEmail(email); @@ -794,10 +784,10 @@ private UserCreator userCreatorCreator(String name, String displayName, String e } /** - * Create credentials for specific user, set users password. - * It finds user by name and sets its password. + * Create credentials for specific user, set users password. It finds user by name and sets its password. * - * @param cucCredentials username and open password + * @param cucCredentials + * username and open password * @return created credential */ private Credential createCredentials(CucCredentials cucCredentials) throws Exception { @@ -819,26 +809,33 @@ private Credential createCredentials(CucCredentials cucCredentials) throws Excep /** * Create credential creator for user with password. * - * @param scopeId scopeId in which user is - * @param userId userId for which credetntials are set - * @param password open password as credetntials - * @param status status of credentials enabled or disabled - * @param expirationDate credential expiration date + * @param scopeId + * scopeId in which user is + * @param userId + * userId for which credetntials are set + * @param password + * open password as credetntials + * @param status + * status of credentials enabled or disabled + * @param expirationDate + * credential expiration date * @return credential creator used for creating credentials */ private CredentialCreator credentialCreatorCreator(KapuaId scopeId, KapuaId userId, String password, CredentialStatus status, Date expirationDate) { CredentialCreator credentialCreator; - credentialCreator = credentialFactory.newCreator(scopeId, userId, "PASSWORD", password, status, expirationDate); + credentialCreator = new CredentialCreator(scopeId, userId, "PASSWORD", password, status, expirationDate); return credentialCreator; } /** * Creates permissions for user with specified account. Permissions are created in priveledged mode. * - * @param permissionList list of permissions for user, if targetScopeId is not set user scope that is - * specifed as account - * @param user user for whom permissions are set - * @param account account in which user is defined + * @param permissionList + * list of permissions for user, if targetScopeId is not set user scope that is specifed as account + * @param user + * user for whom permissions are set + * @param account + * account in which user is defined * @throws Exception */ private void createPermissions(List permissionList, ComparableUser user, Account account) throws Exception { @@ -855,16 +852,18 @@ private void createPermissions(List permissionList, ComparableUse } /** - * Create accessInfoCreator instance with data about user permissions. - * If target scope is not defined in permission list use account scope. + * Create accessInfoCreator instance with data about user permissions. If target scope is not defined in permission list use account scope. * - * @param permissionList list of all permissions - * @param user user for which permissions are set - * @param account that user belongs to + * @param permissionList + * list of all permissions + * @param user + * user for which permissions are set + * @param account + * that user belongs to * @return AccessInfoCreator instance for creating user permissions */ private AccessInfoCreator accessInfoCreatorCreator(List permissionList, ComparableUser user, Account account) throws KapuaException { - AccessInfoCreator accessInfoCreator = accessInfoFactory.newCreator(account.getId()); + AccessInfoCreator accessInfoCreator = new AccessInfoCreator(account.getId()); accessInfoCreator.setUserId(user.getUser().getId()); accessInfoCreator.setScopeId(user.getUser().getScopeId()); Set permissions = new HashSet<>(); @@ -876,13 +875,13 @@ private AccessInfoCreator accessInfoCreatorCreator(List permissio if (targetScopeId == null) { targetScopeId = (KapuaEid) account.getId(); } - Permission permission = permissionFactory.newPermission(cucPermission.getDomain(), + Permission permission = new Permission(cucPermission.getDomain(), action, targetScopeId); permissions.add(permission); stepData.put(LAST_PERMISSION_ADDED_TO_USER, permission); } } else { - Permission permission = permissionFactory.newPermission((String) null, null, null); + Permission permission = new Permission((String) null, null, null); permissions.add(permission); } accessInfoCreator.setPermissions(permissions); @@ -917,7 +916,7 @@ private boolean matchUserData(User user, CucUser cucUser) { @And("I create user with name {string}") public void iCreateUserWithName(String userName) throws Exception { stepData.remove(USER_CREATOR); - UserCreator userCreator = userFactory.newCreator(getCurrentScopeId()); + UserCreator userCreator = new UserCreator(getCurrentScopeId()); userCreator.setName(userName); stepData.put(USER_CREATOR, userCreator); try { @@ -948,7 +947,7 @@ public void iTryToEditUserWithName(String newUserName) throws Exception { public void iCreateUserWithNameInSubaccount(String name, String accountName) throws Exception { Account account = (Account) stepData.get(LAST_ACCOUNT); Assert.assertEquals(accountName, account.getName()); - UserCreator userCreator = userFactory.newCreator(account.getId()); + UserCreator userCreator = new UserCreator(account.getId()); userCreator.setName(name); primeException(); try { @@ -963,7 +962,7 @@ public void iCreateUserWithNameInSubaccount(String name, String accountName) thr @And("I create users with following names") public void iCreateUsersWithFollowingNames(List tmpUsers) throws Exception { - UserCreator userCreator = userFactory.newCreator(getCurrentScopeId()); + UserCreator userCreator = new UserCreator(getCurrentScopeId()); ArrayList userList = new ArrayList<>(); for (CucUser tmpUser : tmpUsers) { userCreator.setName(tmpUser.getName()); @@ -1037,7 +1036,7 @@ public void iSearchForTheUserWithExpirationDateInThePresent() throws KapuaExcept KapuaId scpId = DEFAULT_ID; Set iFoundUsers; stepData.remove(USER_LIST); - KapuaQuery query = userFactory.newQuery(scpId); + KapuaQuery query = new UserQuery(scpId); UserListResult queryResult = userService.query(query); iFoundUsers = new HashSet<>(); List users = queryResult.getItems(); @@ -1076,7 +1075,7 @@ public void iSearchForTheUserWithExpirationDateInThePast() throws KapuaException KapuaId scpId = DEFAULT_ID; Set iFoundUsers; stepData.remove(USER_LIST); - KapuaQuery query = userFactory.newQuery(scpId); + KapuaQuery query = new UserQuery(scpId); UserListResult queryResult = userService.query(query); iFoundUsers = new HashSet<>(); List users = queryResult.getItems(); @@ -1179,7 +1178,7 @@ public void iFindUsersWithPhoneNumber(List userList) { @And("I search users with phone number {string}") public void iSearchUsersWithPhoneNumber(String phoneNum) throws Throwable { - UserQuery userQuery = userFactory.newQuery(DEFAULT_ID); + UserQuery userQuery = new UserQuery(DEFAULT_ID); userQuery.setPredicate(userQuery.attributePredicate(UserAttributes.PHONE_NUMBER, phoneNum, AttributePredicate.Operator.EQUAL)); UserListResult userListResult = userService.query(userQuery); stepData.put(FOUND_USERS, userListResult); @@ -1187,7 +1186,7 @@ public void iSearchUsersWithPhoneNumber(String phoneNum) throws Throwable { @And("I search users with email {string}") public void iSearchForUsersWithEmail(String email) throws Throwable { - UserQuery userQuery = userFactory.newQuery(DEFAULT_ID); + UserQuery userQuery = new UserQuery(DEFAULT_ID); userQuery.setPredicate(userQuery.attributePredicate(UserAttributes.EMAIL, email, AttributePredicate.Operator.EQUAL)); UserListResult userListResult = userService.query(userQuery); stepData.put(FOUND_USERS, userListResult); @@ -1208,7 +1207,7 @@ public void iEnableMfa() { KapuaId scopeId = KapuaSecurityUtils.getSession().getScopeId(); MfaOptionFactory mfaFactory = KapuaLocator.getInstance().getFactory(MfaOptionFactoryImpl.class); - MfaOptionCreator mfaCreator = mfaFactory.newCreator(scopeId, userId); + MfaOptionCreator mfaCreator = new MfaOptionCreator(scopeId, userId); MfaOptionService mfaOptionService = KapuaLocator.getInstance().getService(MfaOptionService.class); try { mfaOptionService.create(mfaCreator); diff --git a/service/user/test/pom.xml b/service/user/test/pom.xml index 5a547010dd8..1638ca77b90 100644 --- a/service/user/test/pom.xml +++ b/service/user/test/pom.xml @@ -20,7 +20,7 @@ org.eclipse.kapua kapua-user - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-user-test diff --git a/service/user/test/src/test/java/org/eclipse/kapua/service/user/test/UserLocatorConfiguration.java b/service/user/test/src/test/java/org/eclipse/kapua/service/user/test/UserLocatorConfiguration.java index 2e5aa40ea45..b7458d21d61 100644 --- a/service/user/test/src/test/java/org/eclipse/kapua/service/user/test/UserLocatorConfiguration.java +++ b/service/user/test/src/test/java/org/eclipse/kapua/service/user/test/UserLocatorConfiguration.java @@ -29,13 +29,11 @@ import org.eclipse.kapua.commons.metric.MetricsService; import org.eclipse.kapua.commons.metric.MetricsServiceImpl; import org.eclipse.kapua.commons.model.domains.Domains; -import org.eclipse.kapua.commons.model.query.QueryFactoryImpl; import org.eclipse.kapua.commons.service.event.store.internal.EventStoreRecordImplJpaRepository; import org.eclipse.kapua.commons.service.internal.cache.CacheManagerProvider; import org.eclipse.kapua.commons.setting.system.SystemSetting; import org.eclipse.kapua.commons.util.xml.XmlUtil; import org.eclipse.kapua.locator.KapuaLocator; -import org.eclipse.kapua.model.query.QueryFactory; import org.eclipse.kapua.qa.common.MockedLocator; import org.eclipse.kapua.qa.common.TestJAXBContextProvider; import org.eclipse.kapua.service.account.AccountService; @@ -45,7 +43,6 @@ import org.eclipse.kapua.service.authorization.AuthorizationService; import org.eclipse.kapua.service.authorization.domain.DomainRegistryService; import org.eclipse.kapua.service.authorization.permission.Permission; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; import org.eclipse.kapua.service.user.UserFactory; import org.eclipse.kapua.service.user.UserRepository; import org.eclipse.kapua.service.user.UserService; @@ -102,12 +99,7 @@ protected void configure() { // skip } - bind(QueryFactory.class).toInstance(new QueryFactoryImpl()); - bind(AuthorizationService.class).toInstance(mockedAuthorization); - // Inject mocked Permission Factory - PermissionFactory mockPermissionFactory = Mockito.mock(PermissionFactory.class); - bind(PermissionFactory.class).toInstance(mockPermissionFactory); // binding Account related services final AccountRelativeFinder accountRelativeFinder = Mockito.mock(AccountRelativeFinder.class); @@ -129,7 +121,6 @@ protected void configure() { Mockito.mock(RootUserTester.class), accountRelativeFinder, new UsedEntitiesCounterImpl( - userFactory, userRepository), new ResourceBasedServiceConfigurationMetadataProvider(new XmlUtil(new TestJAXBContextProvider())) ); @@ -137,7 +128,6 @@ protected void configure() { new UserServiceImpl( userConfigurationManager, mockedAuthorization, - mockPermissionFactory, txManager, new UserImplJpaRepository(jpaRepoConfig), userFactory, diff --git a/simulator-kura/pom.xml b/simulator-kura/pom.xml index 1929cf82af1..d197d5717a7 100644 --- a/simulator-kura/pom.xml +++ b/simulator-kura/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-simulator-kura diff --git a/translator/api/pom.xml b/translator/api/pom.xml index e44ce6cf1d9..fd666a82994 100644 --- a/translator/api/pom.xml +++ b/translator/api/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-translator - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-translator-api diff --git a/translator/kapua/kura/pom.xml b/translator/kapua/kura/pom.xml index 1c7ebc9cc94..8359f1f5483 100644 --- a/translator/kapua/kura/pom.xml +++ b/translator/kapua/kura/pom.xml @@ -19,7 +19,7 @@ org.eclipse.kapua kapua-translator-kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-translator-kapua-kura diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/TranslatorAppAssetKapuaKura.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/TranslatorAppAssetKapuaKura.java index 87059b422ec..84424b4addf 100644 --- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/TranslatorAppAssetKapuaKura.java +++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/TranslatorAppAssetKapuaKura.java @@ -12,8 +12,14 @@ *******************************************************************************/ package org.eclipse.kapua.translator.kapua.kura; -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.IOException; +import java.io.StringWriter; +import java.io.UnsupportedEncodingException; +import java.util.Date; + +import javax.inject.Inject; +import javax.xml.bind.JAXBException; + import org.eclipse.kapua.service.device.call.kura.model.asset.AssetMetrics; import org.eclipse.kapua.service.device.call.kura.model.asset.KuraAsset; import org.eclipse.kapua.service.device.call.kura.model.asset.KuraAssetChannel; @@ -21,7 +27,6 @@ import org.eclipse.kapua.service.device.call.message.kura.app.request.KuraRequestChannel; import org.eclipse.kapua.service.device.call.message.kura.app.request.KuraRequestMessage; import org.eclipse.kapua.service.device.call.message.kura.app.request.KuraRequestPayload; -import org.eclipse.kapua.service.device.management.asset.DeviceAssetFactory; import org.eclipse.kapua.service.device.management.asset.DeviceAssets; import org.eclipse.kapua.service.device.management.asset.message.internal.AssetRequestChannel; import org.eclipse.kapua.service.device.management.asset.message.internal.AssetRequestMessage; @@ -30,12 +35,8 @@ import org.eclipse.kapua.translator.exception.InvalidPayloadException; import org.xml.sax.SAXException; -import javax.inject.Inject; -import javax.xml.bind.JAXBException; -import java.io.IOException; -import java.io.StringWriter; -import java.io.UnsupportedEncodingException; -import java.util.Date; +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.databind.ObjectMapper; /** * {@link org.eclipse.kapua.translator.Translator} implementation from {@link AssetRequestMessage} to {@link KuraRequestMessage} @@ -44,11 +45,8 @@ */ public class TranslatorAppAssetKapuaKura extends AbstractTranslatorKapuaKura { - private final DeviceAssetFactory deviceAssetFactory; - @Inject - public TranslatorAppAssetKapuaKura(DeviceAssetFactory deviceAssetFactory) { - this.deviceAssetFactory = deviceAssetFactory; + public TranslatorAppAssetKapuaKura() { } @Override @@ -79,7 +77,7 @@ protected KuraRequestPayload translatePayload(AssetRequestPayload kapuaPayload) try { DeviceAssets deviceAssets; try { - deviceAssets = kapuaPayload.getDeviceAssets().orElse(deviceAssetFactory.newAssetListResult()); + deviceAssets = kapuaPayload.getDeviceAssets().orElse(new DeviceAssets()); } catch (UnsupportedEncodingException | JAXBException | SAXException e) { throw new InvalidPayloadException(e, kapuaPayload); } diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/TranslatorAppConfigurationKapuaKura.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/TranslatorAppConfigurationKapuaKura.java index 461152995ba..24b3fb729c3 100644 --- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/TranslatorAppConfigurationKapuaKura.java +++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/TranslatorAppConfigurationKapuaKura.java @@ -22,9 +22,7 @@ import org.eclipse.kapua.commons.util.xml.XmlUtil; import org.eclipse.kapua.model.config.metatype.KapuaTad; -import org.eclipse.kapua.model.config.metatype.KapuaTicon; import org.eclipse.kapua.model.config.metatype.KapuaTocd; -import org.eclipse.kapua.model.config.metatype.KapuaToption; import org.eclipse.kapua.model.config.metatype.Password; import org.eclipse.kapua.service.device.call.kura.model.configuration.ConfigurationMetrics; import org.eclipse.kapua.service.device.call.kura.model.configuration.KuraDeviceComponentConfiguration; @@ -35,7 +33,6 @@ import org.eclipse.kapua.service.device.call.message.kura.app.request.KuraRequestPayload; import org.eclipse.kapua.service.device.management.configuration.DeviceComponentConfiguration; import org.eclipse.kapua.service.device.management.configuration.DeviceConfiguration; -import org.eclipse.kapua.service.device.management.configuration.DeviceConfigurationFactory; import org.eclipse.kapua.service.device.management.configuration.message.internal.ConfigurationRequestChannel; import org.eclipse.kapua.service.device.management.configuration.message.internal.ConfigurationRequestMessage; import org.eclipse.kapua.service.device.management.configuration.message.internal.ConfigurationRequestPayload; @@ -49,8 +46,6 @@ */ public class TranslatorAppConfigurationKapuaKura extends AbstractTranslatorKapuaKura { - @Inject - protected DeviceConfigurationFactory deviceConfigurationFactory; @Inject private XmlUtil xmlUtil; @@ -90,7 +85,7 @@ protected KuraRequestPayload translatePayload(ConfigurationRequestPayload kapuaP KuraRequestPayload kuraRequestPayload = new KuraRequestPayload(); if (kapuaPayload.hasBody()) { - DeviceConfiguration kapuaDeviceConfiguration = kapuaPayload.getDeviceConfigurations().orElse(deviceConfigurationFactory.newConfigurationInstance()); + DeviceConfiguration kapuaDeviceConfiguration = kapuaPayload.getDeviceConfigurations().orElse(new DeviceConfiguration()); KuraDeviceConfiguration kuraDeviceConfiguration = translate(kapuaDeviceConfiguration); byte[] body; @@ -153,7 +148,7 @@ protected KapuaTocd translate(KapuaTocd kapuaDefinition) { ad.setRequired(kapuaAd.isRequired()); kapuaAd.getOption().forEach(kuraToption -> { - KapuaToption kapuaToption = new KapuaToption(); + org.eclipse.kapua.model.config.metatype.KapuaToption kapuaToption = new org.eclipse.kapua.model.config.metatype.KapuaToption(); kapuaToption.setLabel(kuraToption.getLabel()); kapuaToption.setValue(kuraToption.getValue()); ad.addOption(kapuaToption); @@ -165,7 +160,7 @@ protected KapuaTocd translate(KapuaTocd kapuaDefinition) { }); kapuaDefinition.getIcon().forEach(kapuaIcon -> { - KapuaTicon icon = new KapuaTicon(); + org.eclipse.kapua.model.config.metatype.KapuaTicon icon = new org.eclipse.kapua.model.config.metatype.KapuaTicon(); icon.setResource(kapuaIcon.getResource()); icon.setSize(kapuaIcon.getSize()); diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/inventory/TranslatorAppInventoryBundleExecKapuaKura.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/inventory/TranslatorAppInventoryBundleExecKapuaKura.java index da1655513d7..b66ce4fda57 100644 --- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/inventory/TranslatorAppInventoryBundleExecKapuaKura.java +++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/inventory/TranslatorAppInventoryBundleExecKapuaKura.java @@ -12,6 +12,8 @@ *******************************************************************************/ package org.eclipse.kapua.translator.kapua.kura.inventory; +import javax.inject.Inject; + import org.eclipse.kapua.KapuaIllegalArgumentException; import org.eclipse.kapua.service.device.call.kura.model.inventory.InventoryMetrics; import org.eclipse.kapua.service.device.call.kura.model.inventory.bundles.KuraInventoryBundle; @@ -20,7 +22,6 @@ import org.eclipse.kapua.service.device.call.message.kura.app.request.KuraRequestPayload; import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSetting; import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSettingKey; -import org.eclipse.kapua.service.device.management.inventory.DeviceInventoryManagementFactory; import org.eclipse.kapua.service.device.management.inventory.internal.message.InventoryBundleExecRequestMessage; import org.eclipse.kapua.service.device.management.inventory.internal.message.InventoryRequestChannel; import org.eclipse.kapua.service.device.management.inventory.internal.message.InventoryRequestPayload; @@ -31,8 +32,6 @@ import org.eclipse.kapua.translator.kapua.kura.AbstractTranslatorKapuaKura; import org.eclipse.kapua.translator.kapua.kura.TranslatorKapuaKuraUtils; -import javax.inject.Inject; - /** * {@link Translator} implementation from {@link InventoryBundleExecRequestMessage} to {@link KuraRequestMessage} * @@ -41,12 +40,9 @@ public class TranslatorAppInventoryBundleExecKapuaKura extends AbstractTranslatorKapuaKura { private final String charEncoding; - private final DeviceInventoryManagementFactory deviceInventoryManagementFactory; @Inject - public TranslatorAppInventoryBundleExecKapuaKura(DeviceManagementSetting deviceManagementSetting, - DeviceInventoryManagementFactory deviceInventoryManagementFactory) { - this.deviceInventoryManagementFactory = deviceInventoryManagementFactory; + public TranslatorAppInventoryBundleExecKapuaKura(DeviceManagementSetting deviceManagementSetting) { charEncoding = deviceManagementSetting.getString(DeviceManagementSettingKey.CHAR_ENCODING); } @@ -56,14 +52,14 @@ protected KuraRequestChannel translateChannel(InventoryRequestChannel inventoryR KuraRequestChannel kuraRequestChannel = TranslatorKapuaKuraUtils.buildBaseRequestChannel(InventoryMetrics.APP_ID, InventoryMetrics.APP_VERSION, inventoryRequestChannel.getMethod()); switch (inventoryRequestChannel.getBundleAction()) { - case START: - kuraRequestChannel.setResources(new String[]{inventoryRequestChannel.getResource(), "_start"}); - break; - case STOP: - kuraRequestChannel.setResources(new String[]{inventoryRequestChannel.getResource(), "_stop"}); - break; - default: - throw new KapuaIllegalArgumentException("inventoryRequestChannel.bundleAction", inventoryRequestChannel.getBundleAction().name()); + case START: + kuraRequestChannel.setResources(new String[] { inventoryRequestChannel.getResource(), "_start" }); + break; + case STOP: + kuraRequestChannel.setResources(new String[] { inventoryRequestChannel.getResource(), "_stop" }); + break; + default: + throw new KapuaIllegalArgumentException("inventoryRequestChannel.bundleAction", inventoryRequestChannel.getBundleAction().name()); } // Return Kura Channel @@ -79,7 +75,7 @@ protected KuraRequestPayload translatePayload(InventoryRequestPayload inventoryR KuraRequestPayload kuraRequestPayload = new KuraRequestPayload(); if (inventoryRequestPayload.hasBody()) { - DeviceInventoryBundle deviceInventoryBundle = inventoryRequestPayload.getDeviceInventoryBundle().orElse(deviceInventoryManagementFactory.newDeviceInventoryBundle()); + DeviceInventoryBundle deviceInventoryBundle = inventoryRequestPayload.getDeviceInventoryBundle().orElse(new DeviceInventoryBundle()); KuraInventoryBundle kuraInventoryBundle = new KuraInventoryBundle(); kuraInventoryBundle.setId(Integer.valueOf(deviceInventoryBundle.getId())); diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/inventory/TranslatorAppInventoryContainerExecKapuaKura.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/inventory/TranslatorAppInventoryContainerExecKapuaKura.java index 55dddfe858b..009ac82ca39 100644 --- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/inventory/TranslatorAppInventoryContainerExecKapuaKura.java +++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/inventory/TranslatorAppInventoryContainerExecKapuaKura.java @@ -12,6 +12,8 @@ *******************************************************************************/ package org.eclipse.kapua.translator.kapua.kura.inventory; +import javax.inject.Inject; + import org.eclipse.kapua.KapuaIllegalArgumentException; import org.eclipse.kapua.service.device.call.kura.model.inventory.InventoryMetrics; import org.eclipse.kapua.service.device.call.kura.model.inventory.containers.KuraInventoryContainer; @@ -20,7 +22,6 @@ import org.eclipse.kapua.service.device.call.message.kura.app.request.KuraRequestPayload; import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSetting; import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSettingKey; -import org.eclipse.kapua.service.device.management.inventory.DeviceInventoryManagementFactory; import org.eclipse.kapua.service.device.management.inventory.internal.message.InventoryContainerExecRequestMessage; import org.eclipse.kapua.service.device.management.inventory.internal.message.InventoryRequestChannel; import org.eclipse.kapua.service.device.management.inventory.internal.message.InventoryRequestPayload; @@ -31,8 +32,6 @@ import org.eclipse.kapua.translator.kapua.kura.AbstractTranslatorKapuaKura; import org.eclipse.kapua.translator.kapua.kura.TranslatorKapuaKuraUtils; -import javax.inject.Inject; - /** * {@link Translator} implementation from {@link InventoryContainerExecRequestMessage} to {@link KuraRequestMessage} * @@ -41,11 +40,9 @@ public class TranslatorAppInventoryContainerExecKapuaKura extends AbstractTranslatorKapuaKura { private final String charEncoding; - private final DeviceInventoryManagementFactory deviceInventoryManagementFactory; @Inject - public TranslatorAppInventoryContainerExecKapuaKura(DeviceManagementSetting deviceManagementSetting, DeviceInventoryManagementFactory deviceInventoryManagementFactory) { - this.deviceInventoryManagementFactory = deviceInventoryManagementFactory; + public TranslatorAppInventoryContainerExecKapuaKura(DeviceManagementSetting deviceManagementSetting) { this.charEncoding = deviceManagementSetting.getString(DeviceManagementSettingKey.CHAR_ENCODING); } @@ -55,14 +52,14 @@ protected KuraRequestChannel translateChannel(InventoryRequestChannel inventoryR KuraRequestChannel kuraRequestChannel = TranslatorKapuaKuraUtils.buildBaseRequestChannel(InventoryMetrics.APP_ID, InventoryMetrics.APP_VERSION, inventoryRequestChannel.getMethod()); switch (inventoryRequestChannel.getContainerAction()) { - case START: - kuraRequestChannel.setResources(new String[]{inventoryRequestChannel.getResource(), "_start"}); - break; - case STOP: - kuraRequestChannel.setResources(new String[]{inventoryRequestChannel.getResource(), "_stop"}); - break; - default: - throw new KapuaIllegalArgumentException("inventoryRequestChannel.containerAction", inventoryRequestChannel.getContainerAction().name()); + case START: + kuraRequestChannel.setResources(new String[] { inventoryRequestChannel.getResource(), "_start" }); + break; + case STOP: + kuraRequestChannel.setResources(new String[] { inventoryRequestChannel.getResource(), "_stop" }); + break; + default: + throw new KapuaIllegalArgumentException("inventoryRequestChannel.containerAction", inventoryRequestChannel.getContainerAction().name()); } // Return Kura Channel @@ -78,7 +75,7 @@ protected KuraRequestPayload translatePayload(InventoryRequestPayload inventoryR KuraRequestPayload kuraRequestPayload = new KuraRequestPayload(); if (inventoryRequestPayload.hasBody()) { - DeviceInventoryContainer deviceInventoryContainer = inventoryRequestPayload.getDeviceInventoryContainer().orElse(deviceInventoryManagementFactory.newDeviceInventoryContainer()); + DeviceInventoryContainer deviceInventoryContainer = inventoryRequestPayload.getDeviceInventoryContainer().orElse(new DeviceInventoryContainer()); KuraInventoryContainer kuraInventoryContainer = new KuraInventoryContainer(); kuraInventoryContainer.setName(deviceInventoryContainer.getName()); diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/keystore/AbstractTranslatorAppKeystoreKapuaKura.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/keystore/AbstractTranslatorAppKeystoreKapuaKura.java index ffcb6cff617..e4b54775a18 100644 --- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/keystore/AbstractTranslatorAppKeystoreKapuaKura.java +++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/keystore/AbstractTranslatorAppKeystoreKapuaKura.java @@ -15,7 +15,6 @@ import org.eclipse.kapua.service.device.call.kura.model.keystore.KeystoreMetrics; import org.eclipse.kapua.service.device.call.message.kura.app.request.KuraRequestChannel; import org.eclipse.kapua.service.device.call.message.kura.app.request.KuraRequestMessage; -import org.eclipse.kapua.service.device.management.keystore.DeviceKeystoreManagementFactory; import org.eclipse.kapua.service.device.management.keystore.internal.message.request.KeystoreRequestChannel; import org.eclipse.kapua.service.device.management.keystore.internal.message.request.KeystoreRequestMessage; import org.eclipse.kapua.service.device.management.keystore.internal.message.request.KeystoreRequestPayload; @@ -30,11 +29,6 @@ * @since 1.5.0 */ public abstract class AbstractTranslatorAppKeystoreKapuaKura> extends AbstractTranslatorKapuaKura { - protected final DeviceKeystoreManagementFactory deviceKeystoreManagementFactory; - - public AbstractTranslatorAppKeystoreKapuaKura(DeviceKeystoreManagementFactory deviceKeystoreManagementFactory) { - this.deviceKeystoreManagementFactory = deviceKeystoreManagementFactory; - } @Override protected KuraRequestChannel translateChannel(KeystoreRequestChannel kapuaChannel) throws InvalidChannelException { @@ -43,18 +37,18 @@ protected KuraRequestChannel translateChannel(KeystoreRequestChannel kapuaChanne if (kapuaChannel.getResource() != null) { if ("items".equals(kapuaChannel.getResource())) { - kuraRequestChannel.setResources(new String[]{"keystores", "entries"}); + kuraRequestChannel.setResources(new String[] { "keystores", "entries" }); } else if ("item".equals(kapuaChannel.getResource())) { - kuraRequestChannel.setResources(new String[]{"keystores", "entries", "entry"}); + kuraRequestChannel.setResources(new String[] { "keystores", "entries", "entry" }); } else if ("certificate".equals(kapuaChannel.getResource())) { - kuraRequestChannel.setResources(new String[]{"keystores", "entries", "certificate"}); + kuraRequestChannel.setResources(new String[] { "keystores", "entries", "certificate" }); } else if ("keypair".equals(kapuaChannel.getResource())) { - kuraRequestChannel.setResources(new String[]{"keystores", "entries", "keypair"}); + kuraRequestChannel.setResources(new String[] { "keystores", "entries", "keypair" }); } else if ("csr".equals(kapuaChannel.getResource())) { - kuraRequestChannel.setResources(new String[]{"keystores", "entries", "csr"}); + kuraRequestChannel.setResources(new String[] { "keystores", "entries", "csr" }); } } else { - kuraRequestChannel.setResources(new String[]{"keystores"}); + kuraRequestChannel.setResources(new String[] { "keystores" }); } // Return Kura Channel diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/keystore/TranslatorAppKeystoreCertificateKapuaKura.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/keystore/TranslatorAppKeystoreCertificateKapuaKura.java index 843e6029c09..caeb41eb327 100644 --- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/keystore/TranslatorAppKeystoreCertificateKapuaKura.java +++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/keystore/TranslatorAppKeystoreCertificateKapuaKura.java @@ -12,20 +12,19 @@ *******************************************************************************/ package org.eclipse.kapua.translator.kapua.kura.keystore; +import javax.inject.Inject; + import org.eclipse.kapua.service.device.call.kura.model.keystore.KuraKeystoreCertificate; import org.eclipse.kapua.service.device.call.message.kura.app.request.KuraRequestMessage; import org.eclipse.kapua.service.device.call.message.kura.app.request.KuraRequestPayload; import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSetting; import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSettingKey; -import org.eclipse.kapua.service.device.management.keystore.DeviceKeystoreManagementFactory; import org.eclipse.kapua.service.device.management.keystore.internal.message.request.KeystoreCertificateRequestMessage; import org.eclipse.kapua.service.device.management.keystore.internal.message.request.KeystoreRequestPayload; import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystoreCertificate; import org.eclipse.kapua.translator.Translator; import org.eclipse.kapua.translator.exception.InvalidPayloadException; -import javax.inject.Inject; - /** * {@link Translator} implementation from {@link KeystoreCertificateRequestMessage} to {@link KuraRequestMessage} * @@ -36,8 +35,7 @@ public class TranslatorAppKeystoreCertificateKapuaKura extends AbstractTranslato private final String charEncoding; @Inject - public TranslatorAppKeystoreCertificateKapuaKura(DeviceManagementSetting deviceManagementSetting, DeviceKeystoreManagementFactory deviceKeystoreManagementFactory) { - super(deviceKeystoreManagementFactory); + public TranslatorAppKeystoreCertificateKapuaKura(DeviceManagementSetting deviceManagementSetting) { charEncoding = deviceManagementSetting.getString(DeviceManagementSettingKey.CHAR_ENCODING); } @@ -47,7 +45,7 @@ protected KuraRequestPayload translatePayload(KeystoreRequestPayload keystoreReq KuraRequestPayload kuraRequestPayload = new KuraRequestPayload(); if (keystoreRequestPayload.hasBody()) { - DeviceKeystoreCertificate keystoreCertificate = keystoreRequestPayload.getCertificate().orElse(deviceKeystoreManagementFactory.newDeviceKeystoreCertificate()); + DeviceKeystoreCertificate keystoreCertificate = keystoreRequestPayload.getCertificate().orElse(new DeviceKeystoreCertificate()); KuraKeystoreCertificate kuraKeystoreCertificate = new KuraKeystoreCertificate(); kuraKeystoreCertificate.setKeystoreServicePid(keystoreCertificate.getKeystoreId()); diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/keystore/TranslatorAppKeystoreCsrKapuaKura.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/keystore/TranslatorAppKeystoreCsrKapuaKura.java index c1b3adae39e..57587c561a9 100644 --- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/keystore/TranslatorAppKeystoreCsrKapuaKura.java +++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/keystore/TranslatorAppKeystoreCsrKapuaKura.java @@ -12,20 +12,19 @@ *******************************************************************************/ package org.eclipse.kapua.translator.kapua.kura.keystore; +import javax.inject.Inject; + import org.eclipse.kapua.service.device.call.kura.model.keystore.KuraKeystoreCSRInfo; import org.eclipse.kapua.service.device.call.message.kura.app.request.KuraRequestMessage; import org.eclipse.kapua.service.device.call.message.kura.app.request.KuraRequestPayload; import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSetting; import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSettingKey; -import org.eclipse.kapua.service.device.management.keystore.DeviceKeystoreManagementFactory; import org.eclipse.kapua.service.device.management.keystore.internal.message.request.KeystoreCsrRequestMessage; import org.eclipse.kapua.service.device.management.keystore.internal.message.request.KeystoreRequestPayload; import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystoreCSRInfo; import org.eclipse.kapua.translator.Translator; import org.eclipse.kapua.translator.exception.InvalidPayloadException; -import javax.inject.Inject; - /** * {@link Translator} implementation from {@link KeystoreCsrRequestMessage} to {@link KuraRequestMessage} * @@ -36,8 +35,7 @@ public class TranslatorAppKeystoreCsrKapuaKura extends AbstractTranslatorAppKeys private final String charEncoding; @Inject - public TranslatorAppKeystoreCsrKapuaKura(DeviceManagementSetting deviceManagementSetting, DeviceKeystoreManagementFactory deviceKeystoreManagementFactory) { - super(deviceKeystoreManagementFactory); + public TranslatorAppKeystoreCsrKapuaKura(DeviceManagementSetting deviceManagementSetting) { charEncoding = deviceManagementSetting.getString(DeviceManagementSettingKey.CHAR_ENCODING); } @@ -47,7 +45,7 @@ protected KuraRequestPayload translatePayload(KeystoreRequestPayload keystoreReq KuraRequestPayload kuraRequestPayload = new KuraRequestPayload(); if (keystoreRequestPayload.hasBody()) { - DeviceKeystoreCSRInfo deviceKeystoreCSRInfo = keystoreRequestPayload.getCSRInfo().orElse(deviceKeystoreManagementFactory.newDeviceKeystoreCSRInfo()); + DeviceKeystoreCSRInfo deviceKeystoreCSRInfo = keystoreRequestPayload.getCSRInfo().orElse(new DeviceKeystoreCSRInfo()); KuraKeystoreCSRInfo kuraKeystoreCSRInfo = new KuraKeystoreCSRInfo(); kuraKeystoreCSRInfo.setKeystoreServicePid(deviceKeystoreCSRInfo.getKeystoreId()); diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/keystore/TranslatorAppKeystoreKeypairKapuaKura.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/keystore/TranslatorAppKeystoreKeypairKapuaKura.java index 71931dbf21e..2a20a9f4ec9 100644 --- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/keystore/TranslatorAppKeystoreKeypairKapuaKura.java +++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/keystore/TranslatorAppKeystoreKeypairKapuaKura.java @@ -12,20 +12,19 @@ *******************************************************************************/ package org.eclipse.kapua.translator.kapua.kura.keystore; +import javax.inject.Inject; + import org.eclipse.kapua.service.device.call.kura.model.keystore.KuraKeystoreKeypair; import org.eclipse.kapua.service.device.call.message.kura.app.request.KuraRequestMessage; import org.eclipse.kapua.service.device.call.message.kura.app.request.KuraRequestPayload; import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSetting; import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSettingKey; -import org.eclipse.kapua.service.device.management.keystore.DeviceKeystoreManagementFactory; import org.eclipse.kapua.service.device.management.keystore.internal.message.request.KeystoreKeypairRequestMessage; import org.eclipse.kapua.service.device.management.keystore.internal.message.request.KeystoreRequestPayload; import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystoreKeypair; import org.eclipse.kapua.translator.Translator; import org.eclipse.kapua.translator.exception.InvalidPayloadException; -import javax.inject.Inject; - /** * {@link Translator} implementation from {@link KeystoreKeypairRequestMessage} to {@link KuraRequestMessage} * @@ -36,8 +35,7 @@ public class TranslatorAppKeystoreKeypairKapuaKura extends AbstractTranslatorApp private final String charEncoding; @Inject - public TranslatorAppKeystoreKeypairKapuaKura(DeviceManagementSetting deviceManagementSetting, DeviceKeystoreManagementFactory deviceKeystoreManagementFactory) { - super(deviceKeystoreManagementFactory); + public TranslatorAppKeystoreKeypairKapuaKura(DeviceManagementSetting deviceManagementSetting) { charEncoding = deviceManagementSetting.getString(DeviceManagementSettingKey.CHAR_ENCODING); } @@ -47,7 +45,7 @@ protected KuraRequestPayload translatePayload(KeystoreRequestPayload keystoreReq KuraRequestPayload kuraRequestPayload = new KuraRequestPayload(); if (keystoreRequestPayload.hasBody()) { - DeviceKeystoreKeypair deviceKeystoreKeypair = keystoreRequestPayload.getKeypair().orElse(deviceKeystoreManagementFactory.newDeviceKeystoreKeypair()); + DeviceKeystoreKeypair deviceKeystoreKeypair = keystoreRequestPayload.getKeypair().orElse(new DeviceKeystoreKeypair()); KuraKeystoreKeypair kuraKeystoreKeypair = new KuraKeystoreKeypair(); kuraKeystoreKeypair.setKeystoreServicePid(deviceKeystoreKeypair.getKeystoreId()); diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/keystore/TranslatorAppKeystoreQueryKapuaKura.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/keystore/TranslatorAppKeystoreQueryKapuaKura.java index f33b50ecbac..d02091fea9e 100644 --- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/keystore/TranslatorAppKeystoreQueryKapuaKura.java +++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kapua/kura/keystore/TranslatorAppKeystoreQueryKapuaKura.java @@ -12,20 +12,19 @@ *******************************************************************************/ package org.eclipse.kapua.translator.kapua.kura.keystore; +import javax.inject.Inject; + import org.eclipse.kapua.service.device.call.kura.model.keystore.KuraKeystoreItemQuery; import org.eclipse.kapua.service.device.call.message.kura.app.request.KuraRequestMessage; import org.eclipse.kapua.service.device.call.message.kura.app.request.KuraRequestPayload; import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSetting; import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSettingKey; -import org.eclipse.kapua.service.device.management.keystore.DeviceKeystoreManagementFactory; import org.eclipse.kapua.service.device.management.keystore.internal.message.request.KeystoreQueryRequestMessage; import org.eclipse.kapua.service.device.management.keystore.internal.message.request.KeystoreRequestPayload; import org.eclipse.kapua.service.device.management.keystore.model.DeviceKeystoreItemQuery; import org.eclipse.kapua.translator.Translator; import org.eclipse.kapua.translator.exception.InvalidPayloadException; -import javax.inject.Inject; - /** * {@link Translator} implementation from {@link KeystoreQueryRequestMessage} to {@link KuraRequestMessage} * @@ -36,8 +35,7 @@ public class TranslatorAppKeystoreQueryKapuaKura extends AbstractTranslatorAppKe private final String charEncoding; @Inject - public TranslatorAppKeystoreQueryKapuaKura(DeviceManagementSetting deviceManagementSetting, DeviceKeystoreManagementFactory deviceKeystoreManagementFactory) { - super(deviceKeystoreManagementFactory); + public TranslatorAppKeystoreQueryKapuaKura(DeviceManagementSetting deviceManagementSetting) { charEncoding = deviceManagementSetting.getString(DeviceManagementSettingKey.CHAR_ENCODING); } @@ -47,7 +45,7 @@ protected KuraRequestPayload translatePayload(KeystoreRequestPayload kapuaPayloa KuraRequestPayload kuraRequestPayload = new KuraRequestPayload(); if (kapuaPayload.hasBody()) { - DeviceKeystoreItemQuery deviceKeystoreItemQuery = kapuaPayload.getItemQuery().orElse(deviceKeystoreManagementFactory.newDeviceKeystoreItemQuery()); + DeviceKeystoreItemQuery deviceKeystoreItemQuery = kapuaPayload.getItemQuery().orElse(new DeviceKeystoreItemQuery()); if (deviceKeystoreItemQuery.hasFilters()) { diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorAppAssetKuraKapua.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorAppAssetKuraKapua.java index 5daa8174bfa..77790620425 100644 --- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorAppAssetKuraKapua.java +++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorAppAssetKuraKapua.java @@ -27,7 +27,6 @@ import org.eclipse.kapua.service.device.management.asset.DeviceAsset; import org.eclipse.kapua.service.device.management.asset.DeviceAssetChannel; import org.eclipse.kapua.service.device.management.asset.DeviceAssetChannelMode; -import org.eclipse.kapua.service.device.management.asset.DeviceAssetFactory; import org.eclipse.kapua.service.device.management.asset.DeviceAssets; import org.eclipse.kapua.service.device.management.asset.message.internal.AssetResponseChannel; import org.eclipse.kapua.service.device.management.asset.message.internal.AssetResponseMessage; @@ -46,13 +45,11 @@ */ public class TranslatorAppAssetKuraKapua extends AbstractSimpleTranslatorResponseKuraKapua { - private final DeviceAssetFactory deviceAssetFactory; private final XmlUtil xmlUtil; @Inject - public TranslatorAppAssetKuraKapua(DeviceManagementSetting deviceManagementSetting, DeviceAssetFactory deviceAssetFactory, XmlUtil xmlUtil) { + public TranslatorAppAssetKuraKapua(DeviceManagementSetting deviceManagementSetting, XmlUtil xmlUtil) { super(deviceManagementSetting, AssetResponseMessage.class, AssetResponsePayload.class); - this.deviceAssetFactory = deviceAssetFactory; this.xmlUtil = xmlUtil; } @@ -76,15 +73,15 @@ protected AssetResponsePayload translatePayload(KuraResponsePayload kuraResponse ObjectMapper mapper = new ObjectMapper(); JsonNode jsonNode = mapper.readTree(kuraResponsePayload.getBody()); - DeviceAssets deviceAssets = deviceAssetFactory.newAssetListResult(); + DeviceAssets deviceAssets = new DeviceAssets(); KuraAssets kuraAssets = KuraAssets.readJsonNode(jsonNode); kuraAssets.getAssets().forEach(kuraAsset -> { - DeviceAsset deviceAsset = deviceAssetFactory.newDeviceAsset(); + DeviceAsset deviceAsset = new DeviceAsset(); deviceAsset.setName(kuraAsset.getName()); kuraAsset.getChannels().forEach(kuraAssetChannel -> { - DeviceAssetChannel deviceAssetChannel = deviceAssetFactory.newDeviceAssetChannel(); + DeviceAssetChannel deviceAssetChannel = new DeviceAssetChannel(); deviceAssetChannel.setName(kuraAssetChannel.getName()); KuraAssetChannelMode kuraChannelMode = kuraAssetChannel.getMode(); if (kuraChannelMode != null) { diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorAppBundleKuraKapua.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorAppBundleKuraKapua.java index 7b7b2664448..7db109bf1a3 100644 --- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorAppBundleKuraKapua.java +++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorAppBundleKuraKapua.java @@ -13,13 +13,17 @@ *******************************************************************************/ package org.eclipse.kapua.translator.kura.kapua; +import java.util.Arrays; +import java.util.List; + +import javax.inject.Inject; + import org.eclipse.kapua.service.device.call.kura.model.bundle.BundleMetrics; import org.eclipse.kapua.service.device.call.kura.model.bundle.KuraBundles; import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponseChannel; import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponseMessage; import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponsePayload; import org.eclipse.kapua.service.device.management.bundle.DeviceBundle; -import org.eclipse.kapua.service.device.management.bundle.DeviceBundleFactory; import org.eclipse.kapua.service.device.management.bundle.DeviceBundles; import org.eclipse.kapua.service.device.management.bundle.message.internal.BundleResponseChannel; import org.eclipse.kapua.service.device.management.bundle.message.internal.BundleResponseMessage; @@ -28,10 +32,6 @@ import org.eclipse.kapua.translator.exception.InvalidChannelException; import org.eclipse.kapua.translator.exception.InvalidPayloadException; -import javax.inject.Inject; -import java.util.Arrays; -import java.util.List; - /** * {@link org.eclipse.kapua.translator.Translator} implementation from {@link KuraResponseMessage} to {@link BundleResponseMessage} * @@ -39,12 +39,9 @@ */ public class TranslatorAppBundleKuraKapua extends AbstractSimpleTranslatorResponseKuraKapua { - private final DeviceBundleFactory deviceBundleFactory; - @Inject - public TranslatorAppBundleKuraKapua(DeviceManagementSetting deviceManagementSetting, DeviceBundleFactory deviceBundleFactory) { + public TranslatorAppBundleKuraKapua(DeviceManagementSetting deviceManagementSetting) { super(deviceManagementSetting, BundleResponseMessage.class, BundleResponsePayload.class); - this.deviceBundleFactory = deviceBundleFactory; } @Override @@ -78,16 +75,17 @@ protected BundleResponsePayload translatePayload(KuraResponsePayload kuraRespons /** * Translates {@link KuraBundles} to {@link DeviceBundles} * - * @param kuraBundles The {@link KuraBundles} to translate. + * @param kuraBundles + * The {@link KuraBundles} to translate. * @return The translated {@link DeviceBundles}. * @since 1.0.0 */ private DeviceBundles translate(KuraBundles kuraBundles) { - DeviceBundles deviceBundles = deviceBundleFactory.newBundleListResult(); + DeviceBundles deviceBundles = new DeviceBundles(); List deviceBundlesList = deviceBundles.getBundles(); Arrays.stream(kuraBundles.getBundles()).forEach(kuraBundle -> { - DeviceBundle deviceBundle = deviceBundleFactory.newDeviceBundle(); + DeviceBundle deviceBundle = new DeviceBundle(); deviceBundle.setId(kuraBundle.getId()); deviceBundle.setName(kuraBundle.getName()); deviceBundle.setVersion(kuraBundle.getVersion()); diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorAppConfigurationKuraKapua.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorAppConfigurationKuraKapua.java index 6dcdc885cfd..4e93bc8eeb3 100644 --- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorAppConfigurationKuraKapua.java +++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorAppConfigurationKuraKapua.java @@ -31,9 +31,8 @@ import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponseMessage; import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponsePayload; import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSetting; +import org.eclipse.kapua.service.device.management.configuration.DeviceComponentConfiguration; import org.eclipse.kapua.service.device.management.configuration.DeviceConfiguration; -import org.eclipse.kapua.service.device.management.configuration.internal.DeviceComponentConfigurationImpl; -import org.eclipse.kapua.service.device.management.configuration.internal.DeviceConfigurationImpl; import org.eclipse.kapua.service.device.management.configuration.message.internal.ConfigurationResponseChannel; import org.eclipse.kapua.service.device.management.configuration.message.internal.ConfigurationResponseMessage; import org.eclipse.kapua.service.device.management.configuration.message.internal.ConfigurationResponsePayload; @@ -82,12 +81,12 @@ protected ConfigurationResponsePayload translatePayload(KuraResponsePayload kura } private DeviceConfiguration translate(KuraDeviceConfiguration kuraDeviceConfiguration) { - DeviceConfigurationImpl deviceConfiguration = new DeviceConfigurationImpl(); + DeviceConfiguration deviceConfiguration = new DeviceConfiguration(); for (KuraDeviceComponentConfiguration kuraDeviceCompConf : kuraDeviceConfiguration.getConfigurations()) { String componentId = kuraDeviceCompConf.getComponentId(); - DeviceComponentConfigurationImpl deviceComponentConfiguration = new DeviceComponentConfigurationImpl(componentId); + DeviceComponentConfiguration deviceComponentConfiguration = new DeviceComponentConfiguration(componentId); deviceComponentConfiguration.setProperties(translate(kuraDeviceCompConf.getProperties())); // Translate also definitions when they are available @@ -123,6 +122,7 @@ private KapuaTocd translate(KapuaTocd kuraDefinition) { kuraAd.getOption().forEach(kuraToption -> { KapuaToption kapuaToption = new KapuaToption(); + kapuaToption.setLabel(kuraToption.getLabel()); kapuaToption.setValue(kuraToption.getValue()); ad.addOption(kapuaToption); diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorAppPackageKuraKapua.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorAppPackageKuraKapua.java index 10d46a278a8..a5e239d2ca4 100644 --- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorAppPackageKuraKapua.java +++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/TranslatorAppPackageKuraKapua.java @@ -13,6 +13,11 @@ *******************************************************************************/ package org.eclipse.kapua.translator.kura.kapua; +import java.math.BigInteger; +import java.util.Map; + +import javax.inject.Inject; + import org.eclipse.kapua.commons.model.id.KapuaEid; import org.eclipse.kapua.service.device.call.kura.model.deploy.KuraBundleInfo; import org.eclipse.kapua.service.device.call.kura.model.deploy.KuraDeploymentPackage; @@ -23,7 +28,6 @@ import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponseMessage; import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponsePayload; import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSetting; -import org.eclipse.kapua.service.device.management.packages.DevicePackageFactory; import org.eclipse.kapua.service.device.management.packages.message.internal.PackageResponseChannel; import org.eclipse.kapua.service.device.management.packages.message.internal.PackageResponseMessage; import org.eclipse.kapua.service.device.management.packages.message.internal.PackageResponsePayload; @@ -37,10 +41,6 @@ import org.eclipse.kapua.translator.exception.TranslatorErrorCodes; import org.eclipse.kapua.translator.exception.TranslatorException; -import javax.inject.Inject; -import java.math.BigInteger; -import java.util.Map; - /** * {@link org.eclipse.kapua.translator.Translator} implementation from {@link KuraResponseMessage} to {@link PackageResponseMessage} * @@ -48,12 +48,9 @@ */ public class TranslatorAppPackageKuraKapua extends AbstractSimpleTranslatorResponseKuraKapua { - private final DevicePackageFactory devicePackageFactory; - @Inject - public TranslatorAppPackageKuraKapua(DeviceManagementSetting deviceManagementSetting, DevicePackageFactory devicePackageFactory) { + public TranslatorAppPackageKuraKapua(DeviceManagementSetting deviceManagementSetting) { super(deviceManagementSetting, PackageResponseMessage.class, PackageResponsePayload.class); - this.devicePackageFactory = devicePackageFactory; } @Override @@ -84,18 +81,18 @@ protected PackageResponsePayload translatePayload(KuraResponsePayload kuraRespon String kuraStatus = (String) metrics.get(PackageMetrics.APP_METRIC_PACKAGE_DOWNLOAD_STATUS.getName()); switch (kuraStatus) { - case "IN_PROGRESS": - status = DevicePackageDownloadStatus.IN_PROGRESS; - break; - case "FAILED": - status = DevicePackageDownloadStatus.FAILED; - break; - case "COMPLETED": - case "ALREADY DONE": - status = DevicePackageDownloadStatus.COMPLETED; - break; - default: - throw new TranslatorException(TranslatorErrorCodes.INVALID_PAYLOAD, null, kuraStatus); + case "IN_PROGRESS": + status = DevicePackageDownloadStatus.IN_PROGRESS; + break; + case "FAILED": + status = DevicePackageDownloadStatus.FAILED; + break; + case "COMPLETED": + case "ALREADY DONE": + status = DevicePackageDownloadStatus.COMPLETED; + break; + default: + throw new TranslatorException(TranslatorErrorCodes.INVALID_PAYLOAD, null, kuraStatus); } responsePayload.setPackageDownloadOperationStatus(status); } @@ -129,18 +126,18 @@ protected PackageResponsePayload translatePayload(KuraResponsePayload kuraRespon } private DevicePackages translate(KuraDeploymentPackages kuraDeploymentPackages) { - DevicePackages deviceDeploymentPackages = devicePackageFactory.newDeviceDeploymentPackages(); + DevicePackages deviceDeploymentPackages = new DevicePackages(); KuraDeploymentPackage[] deploymentPackageArray = kuraDeploymentPackages.getDeploymentPackages(); for (KuraDeploymentPackage deploymentPackage : deploymentPackageArray) { - DevicePackage deviceDeploymentPackage = devicePackageFactory.newDeviceDeploymentPackage(); + DevicePackage deviceDeploymentPackage = new DevicePackage(); deviceDeploymentPackage.setName(deploymentPackage.getName()); deviceDeploymentPackage.setVersion(deploymentPackage.getVersion()); DevicePackageBundleInfos devicePackageBundleInfos = deviceDeploymentPackage.getBundleInfos(); KuraBundleInfo[] bundleInfoArray = deploymentPackage.getBundleInfos(); for (KuraBundleInfo bundleInfo : bundleInfoArray) { - DevicePackageBundleInfo devicePackageBundleInfo = devicePackageFactory.newDevicePackageBundleInfo(); + DevicePackageBundleInfo devicePackageBundleInfo = new DevicePackageBundleInfo(); devicePackageBundleInfo.setName(bundleInfo.getName()); devicePackageBundleInfo.setVersion(bundleInfo.getVersion()); diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/event/TranslatorEventConfigurationKuraKapua.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/event/TranslatorEventConfigurationKuraKapua.java index 83784fed2af..3608a1a188a 100644 --- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/event/TranslatorEventConfigurationKuraKapua.java +++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/event/TranslatorEventConfigurationKuraKapua.java @@ -12,8 +12,15 @@ *******************************************************************************/ package org.eclipse.kapua.translator.kura.kapua.event; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.UnsupportedEncodingException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.inject.Inject; +import javax.validation.constraints.NotNull; + import org.eclipse.kapua.KapuaEntityNotFoundException; import org.eclipse.kapua.service.account.Account; import org.eclipse.kapua.service.account.AccountService; @@ -31,7 +38,6 @@ import org.eclipse.kapua.service.device.management.command.internal.CommandAppProperties; import org.eclipse.kapua.service.device.management.configuration.DeviceComponentConfiguration; import org.eclipse.kapua.service.device.management.configuration.DeviceConfiguration; -import org.eclipse.kapua.service.device.management.configuration.DeviceConfigurationFactory; import org.eclipse.kapua.service.device.management.configuration.internal.DeviceConfigurationAppProperties; import org.eclipse.kapua.service.device.management.configuration.message.event.DeviceConfigurationEventMessage; import org.eclipse.kapua.service.device.management.configuration.message.event.internal.DeviceConfigurationEventChannelImpl; @@ -51,13 +57,8 @@ import org.eclipse.kapua.translator.exception.TranslateException; import org.eclipse.kapua.translator.kura.kapua.TranslatorKuraKapuaUtils; -import javax.inject.Inject; -import javax.validation.constraints.NotNull; -import java.io.UnsupportedEncodingException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; /** * {@link Translator} implementation from {@link KuraConfigurationEventMessage} to {@link DeviceConfigurationEventMessageImpl} @@ -71,8 +72,6 @@ public class TranslatorEventConfigurationKuraKapua extends Translator appNameDictionary; @@ -155,7 +154,7 @@ private DeviceConfigurationEventPayloadImpl translate(KuraConfigurationEventPayl deviceComponentConfigurations.add(translate(kuraDeviceComponentConfiguration)); } - final DeviceConfiguration deviceConfiguration = deviceConfigurationFactory.newConfigurationInstance(); + final DeviceConfiguration deviceConfiguration = new DeviceConfiguration(); deviceConfiguration.setComponentConfigurations(deviceComponentConfigurations); configurationEventPayload.setDeviceComponentConfigurations(deviceConfiguration); } @@ -171,12 +170,13 @@ private DeviceConfigurationEventPayloadImpl translate(KuraConfigurationEventPayl *

        * It currently translates only {@link DeviceComponentConfiguration#getId()} * - * @param kuraDeviceComponentConfiguration The {@link KuraDeviceComponentConfiguration} to translate. + * @param kuraDeviceComponentConfiguration + * The {@link KuraDeviceComponentConfiguration} to translate. * @return The translated {@link DeviceComponentConfiguration}. * @since 2.0.0 */ private DeviceComponentConfiguration translate(KuraDeviceComponentConfiguration kuraDeviceComponentConfiguration) { - return deviceConfigurationFactory.newComponentConfigurationInstance(kuraDeviceComponentConfiguration.getComponentId()); + return new DeviceComponentConfiguration(kuraDeviceComponentConfiguration.getComponentId()); } @Override diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/inventory/AbstractTranslatorAppInventoryKuraKapua.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/inventory/AbstractTranslatorAppInventoryKuraKapua.java index c2e1c2e4af1..66195122e55 100644 --- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/inventory/AbstractTranslatorAppInventoryKuraKapua.java +++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/inventory/AbstractTranslatorAppInventoryKuraKapua.java @@ -12,6 +12,8 @@ *******************************************************************************/ package org.eclipse.kapua.translator.kura.kapua.inventory; +import javax.inject.Inject; + import org.eclipse.kapua.service.device.call.kura.model.inventory.InventoryMetrics; import org.eclipse.kapua.service.device.call.kura.model.inventory.KuraInventoryItems; import org.eclipse.kapua.service.device.call.kura.model.inventory.bundles.KuraInventoryBundles; @@ -21,7 +23,6 @@ import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponseChannel; import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponseMessage; import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSetting; -import org.eclipse.kapua.service.device.management.inventory.DeviceInventoryManagementFactory; import org.eclipse.kapua.service.device.management.inventory.internal.message.InventoryResponseChannel; import org.eclipse.kapua.service.device.management.inventory.internal.message.InventoryResponseMessage; import org.eclipse.kapua.service.device.management.inventory.internal.message.InventoryResponsePayload; @@ -42,8 +43,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.inject.Inject; - /** * {@link Translator} {@code abstract} implementation from {@link KuraResponseMessage} to {@link InventoryResponseMessage} * @@ -52,19 +51,17 @@ public class AbstractTranslatorAppInventoryKuraKapua extends AbstractSimpleTranslatorResponseKuraKapua { private static final Logger LOG = LoggerFactory.getLogger(AbstractTranslatorAppInventoryKuraKapua.class); - private final DeviceInventoryManagementFactory deviceInventoryFactory; /** * Constructor. * - * @param deviceInventoryFactory - * @param responseMessageClass The type of the {@link InventoryResponseMessage}. + * @param responseMessageClass + * The type of the {@link InventoryResponseMessage}. * @since 1.5.0 */ @Inject - public AbstractTranslatorAppInventoryKuraKapua(DeviceManagementSetting deviceManagementSetting, DeviceInventoryManagementFactory deviceInventoryFactory, Class responseMessageClass) { + public AbstractTranslatorAppInventoryKuraKapua(DeviceManagementSetting deviceManagementSetting, Class responseMessageClass) { super(deviceManagementSetting, responseMessageClass, InventoryResponsePayload.class); - this.deviceInventoryFactory = deviceInventoryFactory; } @Override @@ -81,15 +78,16 @@ protected InventoryResponseChannel translateChannel(KuraResponseChannel kuraResp /** * Translates {@link KuraInventoryItems} to {@link DeviceInventory} * - * @param kuraInventoryItems The {@link KuraInventoryItems} to translate. + * @param kuraInventoryItems + * The {@link KuraInventoryItems} to translate. * @return The translated {@link DeviceInventory}. * @since 1.5.0 */ protected DeviceInventory translate(KuraInventoryItems kuraInventoryItems) { - DeviceInventory deviceInventory = deviceInventoryFactory.newDeviceInventory(); + DeviceInventory deviceInventory = new DeviceInventory(); kuraInventoryItems.getInventoryItems().forEach(kuraInventoryItem -> { - DeviceInventoryItem deviceInventoryItem = deviceInventoryFactory.newDeviceInventoryItem(); + DeviceInventoryItem deviceInventoryItem = new DeviceInventoryItem(); deviceInventoryItem.setName(kuraInventoryItem.getName()); deviceInventoryItem.setVersion(kuraInventoryItem.getVersion()); deviceInventoryItem.setItemType(kuraInventoryItem.getType()); @@ -103,15 +101,16 @@ protected DeviceInventory translate(KuraInventoryItems kuraInventoryItems) { /** * Translates {@link KuraInventoryBundles} to {@link DeviceInventoryBundles} * - * @param kuraInventoryBundles The {@link KuraInventoryBundles} to translate. + * @param kuraInventoryBundles + * The {@link KuraInventoryBundles} to translate. * @return The translated {@link DeviceInventoryBundles}. * @since 1.5.0 */ protected DeviceInventoryBundles translate(KuraInventoryBundles kuraInventoryBundles) { - DeviceInventoryBundles deviceInventoryBundles = deviceInventoryFactory.newDeviceInventoryBundles(); + DeviceInventoryBundles deviceInventoryBundles = new DeviceInventoryBundles(); kuraInventoryBundles.getInventoryBundles().forEach(kuraInventoryBundle -> { - DeviceInventoryBundle deviceInventoryBundle = deviceInventoryFactory.newDeviceInventoryBundle(); + DeviceInventoryBundle deviceInventoryBundle = new DeviceInventoryBundle(); deviceInventoryBundle.setId(String.valueOf(kuraInventoryBundle.getId())); deviceInventoryBundle.setName(kuraInventoryBundle.getName()); deviceInventoryBundle.setVersion(kuraInventoryBundle.getVersion()); @@ -127,41 +126,44 @@ protected DeviceInventoryBundles translate(KuraInventoryBundles kuraInventoryBun /** * Translates {@link KuraInventoryContainers} to {@link DeviceInventoryContainers} * - * @param kuraInventoryContainers The {@link KuraInventoryContainers} to translate. + * @param kuraInventoryContainers + * The {@link KuraInventoryContainers} to translate. * @return The translated {@link DeviceInventoryContainers}. * @since 2.0.0 */ protected DeviceInventoryContainers translate(KuraInventoryContainers kuraInventoryContainers) { - DeviceInventoryContainers deviceInventoryContainers = deviceInventoryFactory.newDeviceInventoryContainers(); + DeviceInventoryContainers deviceInventoryContainers = new DeviceInventoryContainers(); kuraInventoryContainers.getInventoryContainers().forEach(kuraInventoryContainer -> { - DeviceInventoryContainer deviceInventoryContainer = deviceInventoryFactory.newDeviceInventoryContainer(); + DeviceInventoryContainer deviceInventoryContainer = new DeviceInventoryContainer(); deviceInventoryContainer.setName(kuraInventoryContainer.getName()); deviceInventoryContainer.setVersion(kuraInventoryContainer.getVersion()); deviceInventoryContainer.setContainerType(kuraInventoryContainer.getType()); if (kuraInventoryContainer.getState() != null) { switch (kuraInventoryContainer.getState()) { - case "active": - deviceInventoryContainer.setState(DeviceInventoryContainerState.ACTIVE); - break; - case "installed": - deviceInventoryContainer.setState(DeviceInventoryContainerState.INSTALLED); - break; - case "uninstalled": - deviceInventoryContainer.setState(DeviceInventoryContainerState.UNINSTALLED); - break; - case "unknown": - deviceInventoryContainer.setState(DeviceInventoryContainerState.UNKNOWN); - break; - default: { - LOG.warn("Unrecognised KuraInventoryContainer.state '{}' received. Defaulting to UNKNOWN state for DeviceInventoryContainer {}", kuraInventoryContainer.getState(), deviceInventoryContainer.getName()); - deviceInventoryContainer.setState(DeviceInventoryContainerState.UNKNOWN); - } + case "active": + deviceInventoryContainer.setState(DeviceInventoryContainerState.ACTIVE); + break; + case "installed": + deviceInventoryContainer.setState(DeviceInventoryContainerState.INSTALLED); + break; + case "uninstalled": + deviceInventoryContainer.setState(DeviceInventoryContainerState.UNINSTALLED); + break; + case "unknown": + deviceInventoryContainer.setState(DeviceInventoryContainerState.UNKNOWN); + break; + default: { + LOG.warn("Unrecognised KuraInventoryContainer.state '{}' received. Defaulting to UNKNOWN state for DeviceInventoryContainer {}", kuraInventoryContainer.getState(), + deviceInventoryContainer.getName()); + deviceInventoryContainer.setState(DeviceInventoryContainerState.UNKNOWN); + } } } else { - LOG.warn("Property KuraInventoryContainer.state '{}' not present. Defaulting to UNKNOWN state for DeviceInventoryContainer {}", kuraInventoryContainer.getState(), deviceInventoryContainer.getName()); + LOG.warn("Property KuraInventoryContainer.state '{}' not present. Defaulting to UNKNOWN state for DeviceInventoryContainer {}", kuraInventoryContainer.getState(), + deviceInventoryContainer.getName()); deviceInventoryContainer.setState(DeviceInventoryContainerState.UNKNOWN); } @@ -174,15 +176,16 @@ protected DeviceInventoryContainers translate(KuraInventoryContainers kuraInvent /** * Translates {@link KuraInventorySystemPackages} to {@link DeviceInventorySystemPackages} * - * @param kuraInventorySystemPackages The {@link KuraInventorySystemPackages} to translate. + * @param kuraInventorySystemPackages + * The {@link KuraInventorySystemPackages} to translate. * @return The translated {@link DeviceInventorySystemPackages}. * @since 1.5.0 */ protected DeviceInventorySystemPackages translate(KuraInventorySystemPackages kuraInventorySystemPackages) { - DeviceInventorySystemPackages deviceInventorySystemPackages = deviceInventoryFactory.newDeviceInventorySystemPackages(); + DeviceInventorySystemPackages deviceInventorySystemPackages = new DeviceInventorySystemPackages(); kuraInventorySystemPackages.getSystemPackages().forEach(kuraInventorySystemPackage -> { - DeviceInventorySystemPackage deviceInventorySystemPackage = deviceInventoryFactory.newDeviceInventorySystemPackage(); + DeviceInventorySystemPackage deviceInventorySystemPackage = new DeviceInventorySystemPackage(); deviceInventorySystemPackage.setName(kuraInventorySystemPackage.getName()); deviceInventorySystemPackage.setVersion(kuraInventorySystemPackage.getVersion()); deviceInventorySystemPackage.setPackageType(kuraInventorySystemPackage.getType()); @@ -196,20 +199,21 @@ protected DeviceInventorySystemPackages translate(KuraInventorySystemPackages ku /** * Translates {@link KuraInventoryPackages} to {@link DeviceInventoryPackages} * - * @param kuraInventoryPackages The {@link KuraInventorySystemPackages} to translate. + * @param kuraInventoryPackages + * The {@link KuraInventorySystemPackages} to translate. * @return The translated {@link DeviceInventorySystemPackages}. * @since 1.5.0 */ protected DeviceInventoryPackages translate(KuraInventoryPackages kuraInventoryPackages) { - DeviceInventoryPackages deviceInventoryPackages = deviceInventoryFactory.newDeviceInventoryPackages(); + DeviceInventoryPackages deviceInventoryPackages = new DeviceInventoryPackages(); kuraInventoryPackages.getPackages().forEach(kuraInventoryPackage -> { - DeviceInventoryPackage deviceInventoryPackage = deviceInventoryFactory.newDeviceInventoryPackage(); + DeviceInventoryPackage deviceInventoryPackage = new DeviceInventoryPackage(); deviceInventoryPackage.setName(kuraInventoryPackage.getName()); deviceInventoryPackage.setVersion(kuraInventoryPackage.getVersion()); kuraInventoryPackage.getPackageBundles().forEach(kuraInventoryBundle -> { - DeviceInventoryBundle deviceInventoryBundle = deviceInventoryFactory.newDeviceInventoryBundle(); + DeviceInventoryBundle deviceInventoryBundle = new DeviceInventoryBundle(); deviceInventoryBundle.setId(String.valueOf(kuraInventoryBundle.getId())); deviceInventoryBundle.setName(kuraInventoryBundle.getName()); deviceInventoryBundle.setVersion(kuraInventoryBundle.getVersion()); diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/inventory/TranslatorAppInventoryBundlesKuraKapua.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/inventory/TranslatorAppInventoryBundlesKuraKapua.java index 4a926af1d2e..fc775d0cce3 100644 --- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/inventory/TranslatorAppInventoryBundlesKuraKapua.java +++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/inventory/TranslatorAppInventoryBundlesKuraKapua.java @@ -12,18 +12,17 @@ *******************************************************************************/ package org.eclipse.kapua.translator.kura.kapua.inventory; +import javax.inject.Inject; + import org.eclipse.kapua.service.device.call.kura.model.inventory.bundles.KuraInventoryBundles; import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponseMessage; import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponsePayload; import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSetting; -import org.eclipse.kapua.service.device.management.inventory.DeviceInventoryManagementFactory; import org.eclipse.kapua.service.device.management.inventory.internal.message.InventoryBundlesResponseMessage; import org.eclipse.kapua.service.device.management.inventory.internal.message.InventoryResponsePayload; import org.eclipse.kapua.translator.Translator; import org.eclipse.kapua.translator.exception.InvalidPayloadException; -import javax.inject.Inject; - /** * {@link Translator} implementation from {@link KuraResponseMessage} to {@link InventoryBundlesResponseMessage} * @@ -37,8 +36,8 @@ public class TranslatorAppInventoryBundlesKuraKapua extends AbstractTranslatorAp * @since 1.5.0 */ @Inject - public TranslatorAppInventoryBundlesKuraKapua(DeviceManagementSetting deviceManagementSetting, DeviceInventoryManagementFactory deviceInventoryManagementFactory) { - super(deviceManagementSetting, deviceInventoryManagementFactory, InventoryBundlesResponseMessage.class); + public TranslatorAppInventoryBundlesKuraKapua(DeviceManagementSetting deviceManagementSetting) { + super(deviceManagementSetting, InventoryBundlesResponseMessage.class); } @Override diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/inventory/TranslatorAppInventoryContainersKuraKapua.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/inventory/TranslatorAppInventoryContainersKuraKapua.java index 8cc60cfc187..3636fc1b0a1 100644 --- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/inventory/TranslatorAppInventoryContainersKuraKapua.java +++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/inventory/TranslatorAppInventoryContainersKuraKapua.java @@ -12,18 +12,17 @@ *******************************************************************************/ package org.eclipse.kapua.translator.kura.kapua.inventory; +import javax.inject.Inject; + import org.eclipse.kapua.service.device.call.kura.model.inventory.containers.KuraInventoryContainers; import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponseMessage; import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponsePayload; import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSetting; -import org.eclipse.kapua.service.device.management.inventory.DeviceInventoryManagementFactory; import org.eclipse.kapua.service.device.management.inventory.internal.message.InventoryContainersResponseMessage; import org.eclipse.kapua.service.device.management.inventory.internal.message.InventoryResponsePayload; import org.eclipse.kapua.translator.Translator; import org.eclipse.kapua.translator.exception.InvalidPayloadException; -import javax.inject.Inject; - /** * {@link Translator} implementation from {@link KuraResponseMessage} to {@link InventoryContainersResponseMessage} * @@ -37,8 +36,8 @@ public class TranslatorAppInventoryContainersKuraKapua extends AbstractTranslato * @since 2.0.0 */ @Inject - public TranslatorAppInventoryContainersKuraKapua(DeviceManagementSetting deviceManagementSetting, DeviceInventoryManagementFactory deviceInventoryManagementFactory) { - super(deviceManagementSetting, deviceInventoryManagementFactory, InventoryContainersResponseMessage.class); + public TranslatorAppInventoryContainersKuraKapua(DeviceManagementSetting deviceManagementSetting) { + super(deviceManagementSetting, InventoryContainersResponseMessage.class); } @Override diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/inventory/TranslatorAppInventoryListKuraKapua.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/inventory/TranslatorAppInventoryListKuraKapua.java index 24e44589340..9fd634e9d39 100644 --- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/inventory/TranslatorAppInventoryListKuraKapua.java +++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/inventory/TranslatorAppInventoryListKuraKapua.java @@ -12,18 +12,17 @@ *******************************************************************************/ package org.eclipse.kapua.translator.kura.kapua.inventory; +import javax.inject.Inject; + import org.eclipse.kapua.service.device.call.kura.model.inventory.KuraInventoryItems; import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponseMessage; import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponsePayload; import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSetting; -import org.eclipse.kapua.service.device.management.inventory.DeviceInventoryManagementFactory; import org.eclipse.kapua.service.device.management.inventory.internal.message.InventoryListResponseMessage; import org.eclipse.kapua.service.device.management.inventory.internal.message.InventoryResponsePayload; import org.eclipse.kapua.translator.Translator; import org.eclipse.kapua.translator.exception.InvalidPayloadException; -import javax.inject.Inject; - /** * {@link Translator} implementation from {@link KuraResponseMessage} to {@link InventoryListResponseMessage} * @@ -37,8 +36,8 @@ public class TranslatorAppInventoryListKuraKapua extends AbstractTranslatorAppIn * @since 1.5.0 */ @Inject - public TranslatorAppInventoryListKuraKapua(DeviceManagementSetting deviceManagementSetting, DeviceInventoryManagementFactory deviceInventoryManagementFactory) { - super(deviceManagementSetting, deviceInventoryManagementFactory, InventoryListResponseMessage.class); + public TranslatorAppInventoryListKuraKapua(DeviceManagementSetting deviceManagementSetting) { + super(deviceManagementSetting, InventoryListResponseMessage.class); } @Override diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/inventory/TranslatorAppInventoryNoContentKuraKapua.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/inventory/TranslatorAppInventoryNoContentKuraKapua.java index e24fb9263d0..06a79658c53 100644 --- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/inventory/TranslatorAppInventoryNoContentKuraKapua.java +++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/inventory/TranslatorAppInventoryNoContentKuraKapua.java @@ -12,14 +12,13 @@ *******************************************************************************/ package org.eclipse.kapua.translator.kura.kapua.inventory; +import javax.inject.Inject; + import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponseMessage; import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSetting; -import org.eclipse.kapua.service.device.management.inventory.DeviceInventoryManagementFactory; import org.eclipse.kapua.service.device.management.inventory.internal.message.InventoryNoContentResponseMessage; import org.eclipse.kapua.translator.Translator; -import javax.inject.Inject; - /** * {@link Translator} implementation from {@link KuraResponseMessage} to {@link InventoryNoContentResponseMessage} * @@ -33,7 +32,7 @@ public class TranslatorAppInventoryNoContentKuraKapua extends AbstractTranslator * @since 1.5.0 */ @Inject - public TranslatorAppInventoryNoContentKuraKapua(DeviceManagementSetting deviceManagementSetting, DeviceInventoryManagementFactory deviceInventoryManagementFactory) { - super(deviceManagementSetting, deviceInventoryManagementFactory, InventoryNoContentResponseMessage.class); + public TranslatorAppInventoryNoContentKuraKapua(DeviceManagementSetting deviceManagementSetting) { + super(deviceManagementSetting, InventoryNoContentResponseMessage.class); } } diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/inventory/TranslatorAppInventoryPackagesKuraKapua.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/inventory/TranslatorAppInventoryPackagesKuraKapua.java index 443b29fa49e..011023dbdff 100644 --- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/inventory/TranslatorAppInventoryPackagesKuraKapua.java +++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/inventory/TranslatorAppInventoryPackagesKuraKapua.java @@ -12,18 +12,17 @@ *******************************************************************************/ package org.eclipse.kapua.translator.kura.kapua.inventory; +import javax.inject.Inject; + import org.eclipse.kapua.service.device.call.kura.model.inventory.packages.KuraInventoryPackages; import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponseMessage; import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponsePayload; import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSetting; -import org.eclipse.kapua.service.device.management.inventory.DeviceInventoryManagementFactory; import org.eclipse.kapua.service.device.management.inventory.internal.message.InventoryPackagesResponseMessage; import org.eclipse.kapua.service.device.management.inventory.internal.message.InventoryResponsePayload; import org.eclipse.kapua.translator.Translator; import org.eclipse.kapua.translator.exception.InvalidPayloadException; -import javax.inject.Inject; - /** * {@link Translator} implementation from {@link KuraResponseMessage} to {@link InventoryPackagesResponseMessage} * @@ -37,8 +36,8 @@ public class TranslatorAppInventoryPackagesKuraKapua extends AbstractTranslatorA * @since 1.5.0 */ @Inject - public TranslatorAppInventoryPackagesKuraKapua(DeviceManagementSetting deviceManagementSetting, DeviceInventoryManagementFactory deviceInventoryManagementFactory) { - super(deviceManagementSetting, deviceInventoryManagementFactory, InventoryPackagesResponseMessage.class); + public TranslatorAppInventoryPackagesKuraKapua(DeviceManagementSetting deviceManagementSetting) { + super(deviceManagementSetting, InventoryPackagesResponseMessage.class); } @Override diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/inventory/TranslatorAppInventorySystemPackagesKuraKapua.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/inventory/TranslatorAppInventorySystemPackagesKuraKapua.java index 9f52c5be199..daf6ab7c973 100644 --- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/inventory/TranslatorAppInventorySystemPackagesKuraKapua.java +++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/inventory/TranslatorAppInventorySystemPackagesKuraKapua.java @@ -12,18 +12,17 @@ *******************************************************************************/ package org.eclipse.kapua.translator.kura.kapua.inventory; +import javax.inject.Inject; + import org.eclipse.kapua.service.device.call.kura.model.inventory.system.KuraInventorySystemPackages; import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponseMessage; import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponsePayload; import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSetting; -import org.eclipse.kapua.service.device.management.inventory.DeviceInventoryManagementFactory; import org.eclipse.kapua.service.device.management.inventory.internal.message.InventoryResponsePayload; import org.eclipse.kapua.service.device.management.inventory.internal.message.InventorySystemPackagesResponseMessage; import org.eclipse.kapua.translator.Translator; import org.eclipse.kapua.translator.exception.InvalidPayloadException; -import javax.inject.Inject; - /** * {@link Translator} implementation from {@link KuraResponseMessage} to {@link InventorySystemPackagesResponseMessage} * @@ -37,8 +36,8 @@ public class TranslatorAppInventorySystemPackagesKuraKapua extends AbstractTrans * @since 1.5.0 */ @Inject - public TranslatorAppInventorySystemPackagesKuraKapua(DeviceManagementSetting deviceManagementSetting, DeviceInventoryManagementFactory deviceInventoryManagementFactory) { - super(deviceManagementSetting, deviceInventoryManagementFactory, InventorySystemPackagesResponseMessage.class); + public TranslatorAppInventorySystemPackagesKuraKapua(DeviceManagementSetting deviceManagementSetting) { + super(deviceManagementSetting, InventorySystemPackagesResponseMessage.class); } @Override diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/keystore/AbstractTranslatorAppKeystoreKuraKapua.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/keystore/AbstractTranslatorAppKeystoreKuraKapua.java index f7c956b4a1e..2e08ea3f4b3 100644 --- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/keystore/AbstractTranslatorAppKeystoreKuraKapua.java +++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/keystore/AbstractTranslatorAppKeystoreKuraKapua.java @@ -12,6 +12,12 @@ *******************************************************************************/ package org.eclipse.kapua.translator.kura.kapua.keystore; +import java.util.Arrays; +import java.util.Date; +import java.util.stream.Collectors; + +import javax.inject.Inject; + import org.eclipse.kapua.service.device.call.kura.model.keystore.KeystoreMetrics; import org.eclipse.kapua.service.device.call.kura.model.keystore.KuraKeystore; import org.eclipse.kapua.service.device.call.kura.model.keystore.KuraKeystoreCSR; @@ -19,7 +25,6 @@ import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponseChannel; import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponseMessage; import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSetting; -import org.eclipse.kapua.service.device.management.keystore.DeviceKeystoreManagementFactory; import org.eclipse.kapua.service.device.management.keystore.internal.message.response.KeystoreResponseChannel; import org.eclipse.kapua.service.device.management.keystore.internal.message.response.KeystoreResponseMessage; import org.eclipse.kapua.service.device.management.keystore.internal.message.response.KeystoreResponsePayload; @@ -35,11 +40,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.inject.Inject; -import java.util.Arrays; -import java.util.Date; -import java.util.stream.Collectors; - /** * {@link Translator} {@code abstract} implementation from {@link KuraResponseMessage} to {@link KeystoreResponseMessage} * @@ -49,19 +49,16 @@ public abstract class AbstractTranslatorAppKeystoreKuraKapua responseMessageClass) { + public AbstractTranslatorAppKeystoreKuraKapua(DeviceManagementSetting deviceManagementSetting, Class responseMessageClass) { super(deviceManagementSetting, responseMessageClass, KeystoreResponsePayload.class); - this.deviceKeystoreManagementFactory = deviceKeystoreManagementFactory; } @Override @@ -78,17 +75,18 @@ protected KeystoreResponseChannel translateChannel(KuraResponseChannel kuraRespo /** * Translates a {@link KuraKeystore}[] to {@link DeviceKeystores}. * - * @param kuraKeystoreArray The {@link KuraKeystore}[] to translate. + * @param kuraKeystoreArray + * The {@link KuraKeystore}[] to translate. * @return The translated {@link DeviceKeystores}. * @since 1.5.0 */ protected DeviceKeystores translate(KuraKeystore[] kuraKeystoreArray) { - DeviceKeystores deviceKeystores = deviceKeystoreManagementFactory.newDeviceKeystores(); + DeviceKeystores deviceKeystores = new DeviceKeystores(); deviceKeystores.setKeystores( Arrays.stream(kuraKeystoreArray).map(kuraKeystore -> { - DeviceKeystore deviceKeystore = deviceKeystoreManagementFactory.newDeviceKeystore(); + DeviceKeystore deviceKeystore = new DeviceKeystore(); deviceKeystore.setId(kuraKeystore.getKeystoreServicePid()); deviceKeystore.setKeystoreType(kuraKeystore.getType()); @@ -104,13 +102,14 @@ protected DeviceKeystores translate(KuraKeystore[] kuraKeystoreArray) { /** * Translates a {@link KuraKeystoreItem}[] to {@link DeviceKeystoreItems}. * - * @param kuraKeystoreItemArray The {@link KuraKeystoreItem}[] to translate. + * @param kuraKeystoreItemArray + * The {@link KuraKeystoreItem}[] to translate. * @return The translated {@link DeviceKeystoreItems}. * @since 1.5.0 */ protected DeviceKeystoreItems translate(KuraKeystoreItem[] kuraKeystoreItemArray) { - DeviceKeystoreItems deviceKeystoreItems = deviceKeystoreManagementFactory.newDeviceKeystoreItems(); + DeviceKeystoreItems deviceKeystoreItems = new DeviceKeystoreItems(); deviceKeystoreItems.setKeystoreItems( Arrays.stream(kuraKeystoreItemArray) @@ -124,13 +123,14 @@ protected DeviceKeystoreItems translate(KuraKeystoreItem[] kuraKeystoreItemArray /** * Translates a {@link KuraKeystoreItem}to {@link DeviceKeystoreItems}. * - * @param kuraKeystoreItem The {@link KuraKeystoreItem} to translate. + * @param kuraKeystoreItem + * The {@link KuraKeystoreItem} to translate. * @return The translated {@link DeviceKeystoreItems}. * @since 1.5.0 */ protected DeviceKeystoreItem translate(KuraKeystoreItem kuraKeystoreItem) { - DeviceKeystoreItem deviceKeystore = deviceKeystoreManagementFactory.newDeviceKeystoreItem(); + DeviceKeystoreItem deviceKeystore = new DeviceKeystoreItem(); deviceKeystore.setKeystoreId(kuraKeystoreItem.getKeystoreServicePid()); deviceKeystore.setItemType(kuraKeystoreItem.getType()); @@ -143,7 +143,7 @@ protected DeviceKeystoreItem translate(KuraKeystoreItem kuraKeystoreItem) { deviceKeystore.setCertificateChain(kuraKeystoreItem.getCertificateChain()); for (String[] kuraSubjectAN : kuraKeystoreItem.getSubjectAN()) { - DeviceKeystoreSubjectAN deviceSubjectAN = deviceKeystoreManagementFactory.newDeviceKeystoreSubjectAN(); + DeviceKeystoreSubjectAN deviceSubjectAN = new DeviceKeystoreSubjectAN(); if (kuraSubjectAN == null || kuraSubjectAN.length != 2) { LOG.warn("Invalid Subject Alternative Names provided from the device: {}", (Object) kuraSubjectAN); @@ -170,12 +170,13 @@ protected DeviceKeystoreItem translate(KuraKeystoreItem kuraKeystoreItem) { /** * Translates a {@link KuraKeystoreCSR} to {@link DeviceKeystoreCSR}. * - * @param kuraKeystoreCSR The {@link KuraKeystoreCSR} to translate. + * @param kuraKeystoreCSR + * The {@link KuraKeystoreCSR} to translate. * @return The translated {@link DeviceKeystoreCSR}. * @since 1.5.0 */ protected DeviceKeystoreCSR translate(KuraKeystoreCSR kuraKeystoreCSR) { - DeviceKeystoreCSR deviceKeystoreCSR = deviceKeystoreManagementFactory.newDeviceKeystoreCSR(); + DeviceKeystoreCSR deviceKeystoreCSR = new DeviceKeystoreCSR(); deviceKeystoreCSR.setSigningRequest(kuraKeystoreCSR.getSigningRequest()); diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/keystore/TranslatorAppKeystoreCsrKuraKapua.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/keystore/TranslatorAppKeystoreCsrKuraKapua.java index efee19b7fd4..77838967a7f 100644 --- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/keystore/TranslatorAppKeystoreCsrKuraKapua.java +++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/keystore/TranslatorAppKeystoreCsrKuraKapua.java @@ -12,10 +12,11 @@ *******************************************************************************/ package org.eclipse.kapua.translator.kura.kapua.keystore; +import javax.inject.Inject; + import org.eclipse.kapua.service.device.call.kura.model.keystore.KuraKeystoreCSR; import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponsePayload; import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSetting; -import org.eclipse.kapua.service.device.management.keystore.DeviceKeystoreManagementFactory; import org.eclipse.kapua.service.device.management.keystore.internal.message.response.KeystoreCsrResponseMessage; import org.eclipse.kapua.service.device.management.keystore.internal.message.response.KeystoreResponsePayload; import org.eclipse.kapua.translator.Translator; @@ -23,8 +24,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.inject.Inject; - /** * {@link Translator} implementation from {@link KeystoreCsrResponseMessage} to {@link KeystoreCsrResponseMessage} * @@ -40,8 +39,8 @@ public class TranslatorAppKeystoreCsrKuraKapua extends AbstractTranslatorAppKeys * @since 1.5.0 */ @Inject - public TranslatorAppKeystoreCsrKuraKapua(DeviceManagementSetting deviceManagementSetting, DeviceKeystoreManagementFactory deviceKeystoreManagementFactory) { - super(deviceManagementSetting, deviceKeystoreManagementFactory, KeystoreCsrResponseMessage.class); + public TranslatorAppKeystoreCsrKuraKapua(DeviceManagementSetting deviceManagementSetting) { + super(deviceManagementSetting, KeystoreCsrResponseMessage.class); } @Override @@ -71,7 +70,8 @@ protected KeystoreResponsePayload translatePayload(KuraResponsePayload kuraRespo *

        * See https://github.com/eclipse/kura/issues/3387 for more info. * - * @param kuraResponsePayload The {@link KuraKeystoreCSR} that cannot be {@link #readJsonBodyAs(byte[], Class)} {@link KuraKeystoreCSR}. + * @param kuraResponsePayload + * The {@link KuraKeystoreCSR} that cannot be {@link #readJsonBodyAs(byte[], Class)} {@link KuraKeystoreCSR}. * @return The {@link KuraKeystoreCSR} parsed with the alternative format. * @since 1.5.0 */ diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/keystore/TranslatorAppKeystoreItemKuraKapua.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/keystore/TranslatorAppKeystoreItemKuraKapua.java index 8cf230b7fc2..093f9b4b78f 100644 --- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/keystore/TranslatorAppKeystoreItemKuraKapua.java +++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/keystore/TranslatorAppKeystoreItemKuraKapua.java @@ -12,18 +12,17 @@ *******************************************************************************/ package org.eclipse.kapua.translator.kura.kapua.keystore; +import javax.inject.Inject; + import org.eclipse.kapua.service.device.call.kura.model.keystore.KuraKeystoreItem; import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponseMessage; import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponsePayload; import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSetting; -import org.eclipse.kapua.service.device.management.keystore.DeviceKeystoreManagementFactory; import org.eclipse.kapua.service.device.management.keystore.internal.message.response.KeystoreItemResponseMessage; import org.eclipse.kapua.service.device.management.keystore.internal.message.response.KeystoreResponsePayload; import org.eclipse.kapua.translator.Translator; import org.eclipse.kapua.translator.exception.InvalidPayloadException; -import javax.inject.Inject; - /** * {@link Translator} implementation from {@link KuraResponseMessage} to {@link KeystoreItemResponseMessage} * @@ -37,8 +36,8 @@ public class TranslatorAppKeystoreItemKuraKapua extends AbstractTranslatorAppKey * @since 1.5.0 */ @Inject - public TranslatorAppKeystoreItemKuraKapua(DeviceManagementSetting deviceManagementSetting, DeviceKeystoreManagementFactory deviceKeystoreManagementFactory) { - super(deviceManagementSetting, deviceKeystoreManagementFactory, KeystoreItemResponseMessage.class); + public TranslatorAppKeystoreItemKuraKapua(DeviceManagementSetting deviceManagementSetting) { + super(deviceManagementSetting, KeystoreItemResponseMessage.class); } @Override diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/keystore/TranslatorAppKeystoreItemsKuraKapua.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/keystore/TranslatorAppKeystoreItemsKuraKapua.java index 16c31625c12..1276b8f3e5a 100644 --- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/keystore/TranslatorAppKeystoreItemsKuraKapua.java +++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/keystore/TranslatorAppKeystoreItemsKuraKapua.java @@ -12,18 +12,17 @@ *******************************************************************************/ package org.eclipse.kapua.translator.kura.kapua.keystore; +import javax.inject.Inject; + import org.eclipse.kapua.service.device.call.kura.model.keystore.KuraKeystoreItem; import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponseMessage; import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponsePayload; import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSetting; -import org.eclipse.kapua.service.device.management.keystore.DeviceKeystoreManagementFactory; import org.eclipse.kapua.service.device.management.keystore.internal.message.response.KeystoreItemsResponseMessage; import org.eclipse.kapua.service.device.management.keystore.internal.message.response.KeystoreResponsePayload; import org.eclipse.kapua.translator.Translator; import org.eclipse.kapua.translator.exception.InvalidPayloadException; -import javax.inject.Inject; - /** * {@link Translator} implementation from {@link KuraResponseMessage} to {@link KeystoreItemsResponseMessage} * @@ -37,8 +36,8 @@ public class TranslatorAppKeystoreItemsKuraKapua extends AbstractTranslatorAppKe * @since 1.5.0 */ @Inject - public TranslatorAppKeystoreItemsKuraKapua(DeviceManagementSetting deviceManagementSetting, DeviceKeystoreManagementFactory deviceKeystoreManagementFactory) { - super(deviceManagementSetting, deviceKeystoreManagementFactory, KeystoreItemsResponseMessage.class); + public TranslatorAppKeystoreItemsKuraKapua(DeviceManagementSetting deviceManagementSetting) { + super(deviceManagementSetting, KeystoreItemsResponseMessage.class); } @Override diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/keystore/TranslatorAppKeystoreNoContentKuraKapua.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/keystore/TranslatorAppKeystoreNoContentKuraKapua.java index 4f72434d751..36a380e8c5e 100644 --- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/keystore/TranslatorAppKeystoreNoContentKuraKapua.java +++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/keystore/TranslatorAppKeystoreNoContentKuraKapua.java @@ -12,14 +12,13 @@ *******************************************************************************/ package org.eclipse.kapua.translator.kura.kapua.keystore; +import javax.inject.Inject; + import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponseMessage; import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSetting; -import org.eclipse.kapua.service.device.management.keystore.DeviceKeystoreManagementFactory; import org.eclipse.kapua.service.device.management.keystore.internal.message.response.KeystoreNoContentResponseMessage; import org.eclipse.kapua.translator.Translator; -import javax.inject.Inject; - /** * {@link Translator} implementation from {@link KuraResponseMessage} to {@link KeystoreNoContentResponseMessage} * @@ -33,7 +32,7 @@ public class TranslatorAppKeystoreNoContentKuraKapua extends AbstractTranslatorA * @since 1.5.0 */ @Inject - public TranslatorAppKeystoreNoContentKuraKapua(DeviceManagementSetting deviceManagementSetting, DeviceKeystoreManagementFactory deviceKeystoreManagementFactory) { - super(deviceManagementSetting, deviceKeystoreManagementFactory, KeystoreNoContentResponseMessage.class); + public TranslatorAppKeystoreNoContentKuraKapua(DeviceManagementSetting deviceManagementSetting) { + super(deviceManagementSetting, KeystoreNoContentResponseMessage.class); } } diff --git a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/keystore/TranslatorAppKeystoresKuraKapua.java b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/keystore/TranslatorAppKeystoresKuraKapua.java index d4dd476772a..565a00c162e 100644 --- a/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/keystore/TranslatorAppKeystoresKuraKapua.java +++ b/translator/kapua/kura/src/main/java/org/eclipse/kapua/translator/kura/kapua/keystore/TranslatorAppKeystoresKuraKapua.java @@ -12,18 +12,17 @@ *******************************************************************************/ package org.eclipse.kapua.translator.kura.kapua.keystore; +import javax.inject.Inject; + import org.eclipse.kapua.service.device.call.kura.model.keystore.KuraKeystore; import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponseMessage; import org.eclipse.kapua.service.device.call.message.kura.app.response.KuraResponsePayload; import org.eclipse.kapua.service.device.management.commons.setting.DeviceManagementSetting; -import org.eclipse.kapua.service.device.management.keystore.DeviceKeystoreManagementFactory; import org.eclipse.kapua.service.device.management.keystore.internal.message.response.KeystoreResponsePayload; import org.eclipse.kapua.service.device.management.keystore.internal.message.response.KeystoresResponseMessage; import org.eclipse.kapua.translator.Translator; import org.eclipse.kapua.translator.exception.InvalidPayloadException; -import javax.inject.Inject; - /** * {@link Translator} implementation from {@link KuraResponseMessage} to {@link KeystoresResponseMessage} * @@ -37,8 +36,8 @@ public class TranslatorAppKeystoresKuraKapua extends AbstractTranslatorAppKeysto * @since 1.5.0 */ @Inject - public TranslatorAppKeystoresKuraKapua(DeviceManagementSetting deviceManagementSetting, DeviceKeystoreManagementFactory deviceKeystoreManagementFactory) { - super(deviceManagementSetting, deviceKeystoreManagementFactory, KeystoresResponseMessage.class); + public TranslatorAppKeystoresKuraKapua(DeviceManagementSetting deviceManagementSetting) { + super(deviceManagementSetting, KeystoresResponseMessage.class); } @Override diff --git a/translator/kapua/pom.xml b/translator/kapua/pom.xml index 2d275de630c..9f61e08cbf2 100644 --- a/translator/kapua/pom.xml +++ b/translator/kapua/pom.xml @@ -19,7 +19,7 @@ org.eclipse.kapua kapua-translator - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-translator-kapua diff --git a/translator/kura/jms/pom.xml b/translator/kura/jms/pom.xml index 196f4f7b73b..0cb9917dd77 100644 --- a/translator/kura/jms/pom.xml +++ b/translator/kura/jms/pom.xml @@ -19,7 +19,7 @@ org.eclipse.kapua kapua-translator-kura - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-translator-kura-jms diff --git a/translator/kura/mqtt/pom.xml b/translator/kura/mqtt/pom.xml index f3d5031a6d5..66e64a02b70 100644 --- a/translator/kura/mqtt/pom.xml +++ b/translator/kura/mqtt/pom.xml @@ -19,7 +19,7 @@ org.eclipse.kapua kapua-translator-kura - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-translator-kura-mqtt diff --git a/translator/kura/pom.xml b/translator/kura/pom.xml index d8a2c605eb3..36b7503052e 100644 --- a/translator/kura/pom.xml +++ b/translator/kura/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-translator - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-translator-kura diff --git a/translator/pom.xml b/translator/pom.xml index 765b845c112..82b9c444747 100644 --- a/translator/pom.xml +++ b/translator/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-translator diff --git a/translator/test-steps/pom.xml b/translator/test-steps/pom.xml index c6717dc0306..4f9ce480dcb 100644 --- a/translator/test-steps/pom.xml +++ b/translator/test-steps/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-translator - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-translator-test-steps diff --git a/translator/test/pom.xml b/translator/test/pom.xml index 866085ee6b5..874813fc01a 100644 --- a/translator/test/pom.xml +++ b/translator/test/pom.xml @@ -18,7 +18,7 @@ org.eclipse.kapua kapua-translator - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-translator-test diff --git a/translator/test/src/test/java/org/eclipse/kapua/translator/test/TranslatorLocatorConfiguration.java b/translator/test/src/test/java/org/eclipse/kapua/translator/test/TranslatorLocatorConfiguration.java index 8b84694b410..274e7b5b117 100644 --- a/translator/test/src/test/java/org/eclipse/kapua/translator/test/TranslatorLocatorConfiguration.java +++ b/translator/test/src/test/java/org/eclipse/kapua/translator/test/TranslatorLocatorConfiguration.java @@ -37,13 +37,6 @@ import org.eclipse.kapua.service.authorization.AuthorizationService; import org.eclipse.kapua.service.authorization.domain.DomainRegistryService; import org.eclipse.kapua.service.authorization.permission.Permission; -import org.eclipse.kapua.service.authorization.permission.PermissionFactory; -import org.eclipse.kapua.service.device.management.asset.DeviceAssetFactory; -import org.eclipse.kapua.service.device.management.bundle.DeviceBundleFactory; -import org.eclipse.kapua.service.device.management.configuration.DeviceConfigurationFactory; -import org.eclipse.kapua.service.device.management.inventory.DeviceInventoryManagementFactory; -import org.eclipse.kapua.service.device.management.keystore.DeviceKeystoreManagementFactory; -import org.eclipse.kapua.service.device.management.packages.DevicePackageFactory; import org.eclipse.kapua.service.device.management.request.GenericRequestFactory; import org.eclipse.kapua.service.device.management.snapshot.DeviceSnapshotFactory; import org.eclipse.kapua.service.device.registry.DeviceRegistryService; @@ -100,20 +93,12 @@ protected void configure() { // skip } bind(AuthorizationService.class).toInstance(mockedAuthorization); - // Inject mocked Permission Factory - bind(PermissionFactory.class).toInstance(Mockito.mock(PermissionFactory.class)); bind(AccountService.class).toInstance(Mockito.mock(AccountService.class)); bind(DeviceRegistryService.class).toInstance(Mockito.mock(DeviceRegistryService.class)); bind(GenericRequestFactory.class).toInstance(Mockito.mock(GenericRequestFactory.class)); - bind(DeviceAssetFactory.class).toInstance(Mockito.mock(DeviceAssetFactory.class)); - bind(DeviceBundleFactory.class).toInstance(Mockito.mock(DeviceBundleFactory.class)); bind(KapuaIdFactory.class).toInstance(Mockito.mock(KapuaIdFactory.class)); - bind(DevicePackageFactory.class).toInstance(Mockito.mock(DevicePackageFactory.class)); bind(DeviceSnapshotFactory.class).toInstance(Mockito.mock(DeviceSnapshotFactory.class)); bind(KapuaDataMessageFactory.class).toInstance(Mockito.mock(KapuaDataMessageFactory.class)); - bind(DeviceConfigurationFactory.class).toInstance(Mockito.mock(DeviceConfigurationFactory.class)); - bind(DeviceInventoryManagementFactory.class).toInstance(Mockito.mock(DeviceInventoryManagementFactory.class)); - bind(DeviceKeystoreManagementFactory.class).toInstance(Mockito.mock(DeviceKeystoreManagementFactory.class)); } }; diff --git a/transport/api/pom.xml b/transport/api/pom.xml index ac5fe343ceb..aa0d99981ed 100644 --- a/transport/api/pom.xml +++ b/transport/api/pom.xml @@ -19,7 +19,7 @@ org.eclipse.kapua kapua-transport - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-transport-api diff --git a/transport/jms/pom.xml b/transport/jms/pom.xml index 3a302442bd4..149ceecbff1 100644 --- a/transport/jms/pom.xml +++ b/transport/jms/pom.xml @@ -19,7 +19,7 @@ org.eclipse.kapua kapua-transport - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-transport-jms diff --git a/transport/mqtt/pom.xml b/transport/mqtt/pom.xml index 3e07ac625a3..56faef2b443 100644 --- a/transport/mqtt/pom.xml +++ b/transport/mqtt/pom.xml @@ -19,7 +19,7 @@ org.eclipse.kapua kapua-transport - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT kapua-transport-mqtt diff --git a/transport/mqtt/src/main/java/org/eclipse/kapua/transport/mqtt/MqttFacade.java b/transport/mqtt/src/main/java/org/eclipse/kapua/transport/mqtt/MqttFacade.java index a0c8780d408..595bd88a37c 100644 --- a/transport/mqtt/src/main/java/org/eclipse/kapua/transport/mqtt/MqttFacade.java +++ b/transport/mqtt/src/main/java/org/eclipse/kapua/transport/mqtt/MqttFacade.java @@ -12,6 +12,11 @@ *******************************************************************************/ package org.eclipse.kapua.transport.mqtt; +import java.util.ArrayList; +import java.util.List; + +import javax.validation.constraints.NotNull; + import org.checkerframework.checker.nullness.qual.Nullable; import org.eclipse.kapua.transport.TransportFacade; import org.eclipse.kapua.transport.exception.TransportClientGetException; @@ -27,10 +32,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.validation.constraints.NotNull; -import java.util.ArrayList; -import java.util.List; - /** * Implementation of {@link TransportFacade} API for MQTT transport facade. * @@ -55,7 +56,8 @@ public class MqttFacade implements TransportFacade * - * @param mqttMessage The request to send. - * @param responses The container in which load responses received from the device - * @param timeout The timeout of waiting the response from the device. - * If {@code null} request will be fired without waiting for the response. - * If mqttMessage has no response message set, timeout will be ignore even if set. - * @throws TransportSendException if sending the request produces any error. + * @param mqttMessage + * The request to send. + * @param responses + * The container in which load responses received from the device + * @param timeout + * The timeout of waiting the response from the device. If {@code null} request will be fired without waiting for the response. If mqttMessage has no response message set, timeout will be + * ignore even if set. + * @throws TransportSendException + * if sending the request produces any error. * @see MqttMessage#getResponseTopic() * @since 1.0.0 */ @@ -162,8 +167,10 @@ public void close() { /** * Publish the given {@link MqttMessage} using the {@link MqttClient}. * - * @param mqttMessage The {@link MqttMessage} to publish. - * @throws TransportSendException if error occurs while publishing the given {@link MqttMessage} + * @param mqttMessage + * The {@link MqttMessage} to publish. + * @throws TransportSendException + * if error occurs while publishing the given {@link MqttMessage} * @since 1.1.0 */ private void publishMessage(@NotNull MqttMessage mqttMessage) throws TransportSendException { @@ -177,11 +184,15 @@ private void publishMessage(@NotNull MqttMessage mqttMessage) throws TransportSe /** * Subscribe to response topic and adds the response messages to the given {@code responses} container. * - * @param responseTopic The {@link MqttTopic} to subscribe to receive the response. - * @param responses The container of the received responses + * @param responseTopic + * The {@link MqttTopic} to subscribe to receive the response. + * @param responses + * The container of the received responses * @return The {@link MqttResponseCallback} which handles the received responses. - * @throws MqttClientCallbackSetException if {@link MqttClient#setCallback(MqttResponseCallback)} fails. - * @throws MqttClientSubscribeException if the {@link MqttClient#subscribe(MqttTopic)} fails. + * @throws MqttClientCallbackSetException + * if {@link MqttClient#setCallback(MqttResponseCallback)} fails. + * @throws MqttClientSubscribeException + * if the {@link MqttClient#subscribe(MqttTopic)} fails. * @since 1.1.0 */ private MqttResponseCallback subscribeToResponse(MqttTopic responseTopic, List responses) throws MqttClientCallbackSetException, MqttClientSubscribeException { @@ -195,8 +206,10 @@ private MqttResponseCallback subscribeToResponse(MqttTopic responseTopic, List org.eclipse.kapua kapua - 2.1.0-SNAPSHOT + 2.1.0-FALSE_EXTENSIONS-SNAPSHOT pom