From 7ba13a27da06948634426ba2fbc0a9ac5f34ac49 Mon Sep 17 00:00:00 2001 From: achour94 Date: Thu, 26 Sep 2024 16:41:25 +0200 Subject: [PATCH 1/9] Implement basic operations --- .github/workflows/maven.yml | 61 +++ .gitignore | 12 + LICENSE | 373 ++++++++++++++++++ lombok.config | 1 + pom.xml | 157 ++++++++ .../server/RestTemplateConfig.java | 58 +++ .../server/SpreadsheetConfigApi.java | 18 + .../server/SpreadsheetConfigApplication.java | 22 ++ .../server/SwaggerConfig.java | 28 ++ .../server/constants/SheetType.java | 29 ++ .../SpreadsheetConfigController.java | 106 +++++ .../server/dto/CustomColumnDto.java | 37 ++ .../server/dto/SpreadsheetConfigDto.java | 37 ++ .../server/entities/CustomColumnEntity.java | 40 ++ .../entities/SpreadsheetConfigEntity.java | 42 ++ .../mapper/SpreadsheetConfigMapper.java | 62 +++ .../repositories/CustomColumnRepository.java | 20 + .../SpreadsheetConfigRepository.java | 20 + .../service/SpreadsheetConfigService.java | 98 +++++ src/main/resources/application-local.yml | 6 + src/main/resources/config/application.yaml | 7 + .../create-spreadsheet-config-table.xml | 31 ++ .../db/changelog/db.changelog-master.yaml | 4 + .../SpreadsheetConfigControllerTest.java | 246 ++++++++++++ src/test/resources/application-default.yml | 20 + src/test/resources/logback-test.xml | 42 ++ 26 files changed, 1577 insertions(+) create mode 100644 .github/workflows/maven.yml create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 lombok.config create mode 100644 pom.xml create mode 100644 src/main/java/org/gridsuite/spreadsheetconfig/server/RestTemplateConfig.java create mode 100644 src/main/java/org/gridsuite/spreadsheetconfig/server/SpreadsheetConfigApi.java create mode 100644 src/main/java/org/gridsuite/spreadsheetconfig/server/SpreadsheetConfigApplication.java create mode 100644 src/main/java/org/gridsuite/spreadsheetconfig/server/SwaggerConfig.java create mode 100644 src/main/java/org/gridsuite/spreadsheetconfig/server/constants/SheetType.java create mode 100644 src/main/java/org/gridsuite/spreadsheetconfig/server/controller/SpreadsheetConfigController.java create mode 100644 src/main/java/org/gridsuite/spreadsheetconfig/server/dto/CustomColumnDto.java create mode 100644 src/main/java/org/gridsuite/spreadsheetconfig/server/dto/SpreadsheetConfigDto.java create mode 100644 src/main/java/org/gridsuite/spreadsheetconfig/server/entities/CustomColumnEntity.java create mode 100644 src/main/java/org/gridsuite/spreadsheetconfig/server/entities/SpreadsheetConfigEntity.java create mode 100644 src/main/java/org/gridsuite/spreadsheetconfig/server/mapper/SpreadsheetConfigMapper.java create mode 100644 src/main/java/org/gridsuite/spreadsheetconfig/server/repositories/CustomColumnRepository.java create mode 100644 src/main/java/org/gridsuite/spreadsheetconfig/server/repositories/SpreadsheetConfigRepository.java create mode 100644 src/main/java/org/gridsuite/spreadsheetconfig/server/service/SpreadsheetConfigService.java create mode 100644 src/main/resources/application-local.yml create mode 100644 src/main/resources/config/application.yaml create mode 100644 src/main/resources/db/changelog/changesets/create-spreadsheet-config-table.xml create mode 100644 src/main/resources/db/changelog/db.changelog-master.yaml create mode 100644 src/test/java/org/gridsuite/spreadsheetconfig/server/SpreadsheetConfigControllerTest.java create mode 100644 src/test/resources/application-default.yml create mode 100644 src/test/resources/logback-test.xml diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml new file mode 100644 index 0000000..af7f67e --- /dev/null +++ b/.github/workflows/maven.yml @@ -0,0 +1,61 @@ +name: CI + +on: + push: + branches: + - 'main' + tags: + - 'v[0-9]*' + pull_request: + +jobs: + build: + + runs-on: ubuntu-latest + + steps: + - name: Set up JDK 17 + uses: actions/setup-java@v1 + with: + java-version: 17 + + - name: Checkout sources + uses: actions/checkout@v1 + + - name: Build with Maven + run: mvn --batch-mode -P jacoco verify + + - name: Run SonarCloud analysis + run: > + mvn --batch-mode -DskipTests sonar:sonar + -Dsonar.host.url=https://sonarcloud.io + -Dsonar.organization=gridsuite + -Dsonar.projectKey=org.gridsuite:gridsuite_spreadsheet-config-server + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} + + - name: Build Docker image - Main + if: github.ref == 'refs/heads/main' + run: > + mvn --batch-mode deploy -DskipTests -Dmaven.install.skip -Dmaven.deploy.skip -Dpowsybl.docker.deploy + -Djib.httpTimeout=60000 + -Djib.to.image=docker.io/gridsuite/spreadsheet-config-server + -Djib.to.auth.username=gridsuiteci + -Djib.to.auth.password=${{ secrets.DOCKERHUB_TOKEN }} + + - name: Build Docker image - Tag + if: startsWith(github.ref, 'refs/tags/') + run: > + mvn --batch-mode deploy -DskipTests -Dmaven.install.skip -Dmaven.deploy.skip -Dpowsybl.docker.deploy + -Djib.httpTimeout=60000 + -Djib.to.image=docker.io/gridsuite/spreadsheet-config-server:${GITHUB_REF_NAME#v} + -Djib.to.auth.username=gridsuiteci + -Djib.to.auth.password=${{ secrets.DOCKERHUB_TOKEN }} + + - name: Broadcast update event + if: github.ref == 'refs/heads/main' + uses: gridsuite/broadcast-event@main + with: + token: ${{ secrets.REPO_ACCESS_TOKEN }} + event-type: spreadsheet_config_server_updated diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..41e2fab --- /dev/null +++ b/.gitignore @@ -0,0 +1,12 @@ +# VSCode +/.vscode +/.settings +.classpath +.factorypath +.project + +target/ + +# IntelliJ +/.idea +*.iml diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..a612ad9 --- /dev/null +++ b/LICENSE @@ -0,0 +1,373 @@ +Mozilla Public License Version 2.0 +================================== + +1. Definitions +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + +5. Termination +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ + +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. diff --git a/lombok.config b/lombok.config new file mode 100644 index 0000000..4fa8250 --- /dev/null +++ b/lombok.config @@ -0,0 +1 @@ +import target/configs/powsybl-build-tools.jar!powsybl-build-tools/lombok.config diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..d0e1fa4 --- /dev/null +++ b/pom.xml @@ -0,0 +1,157 @@ + + + + 4.0.0 + + + com.powsybl + powsybl-parent-ws + 20 + + + + org.gridsuite + gridsuite-spreadsheet-config-server + 1.0.0-SNAPSHOT + + jar + Spreadsheet config server + Spreadsheet config server + http://www.gridsuite.org/ + + + scm:git:https://github.com/gridsuite/spreadsheet-config-server.git + scm:git:https://github.com/gridsuite/spreadsheet-config-server.git + https://github.com/gridsuite/spreadsheet-config-server + + + + + Achour BERRAHMA + achour.berrahma_externe@rte-france.com + RTE + http://www.rte-france.com + + + + + 33 + org.gridsuite.spreadsheetconfig.server + + + + + + com.google.cloud.tools + jib-maven-plugin + + + org.springframework.boot + spring-boot-maven-plugin + + + io.github.git-commit-id + git-commit-id-maven-plugin + + + + + + + + + + + org.gridsuite + gridsuite-dependencies + ${gridsuite-dependencies.version} + pom + import + + + + + + + + + org.springframework.bootspring-boot-starter-validation + + com.fasterxml.jackson.core + jackson-databind + + + com.powsybl + powsybl-ws-commons + + + org.projectlombok + lombok + provided + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-web + + + org.springdoc + springdoc-openapi-starter-webmvc-ui + + + + org.springframework.boot + spring-boot-starter-validation + + + + + org.liquibase + liquibase-core + runtime + + + org.postgresql + postgresql + runtime + + + org.springframework.boot + spring-boot-starter-actuator + runtime + + + io.micrometer + micrometer-registry-prometheus + runtime + + + + + com.h2database + h2 + test + + + org.mockito + mockito-core + test + + + org.springframework.boot + spring-boot-starter-test + test + + + diff --git a/src/main/java/org/gridsuite/spreadsheetconfig/server/RestTemplateConfig.java b/src/main/java/org/gridsuite/spreadsheetconfig/server/RestTemplateConfig.java new file mode 100644 index 0000000..e87f3a9 --- /dev/null +++ b/src/main/java/org/gridsuite/spreadsheetconfig/server/RestTemplateConfig.java @@ -0,0 +1,58 @@ +/** + * Copyright (c) 2024, RTE (http://www.rte-france.com) + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ +package org.gridsuite.spreadsheetconfig.server; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import org.springframework.boot.jackson.JsonComponentModule; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; +import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; +import org.springframework.web.client.RestTemplate; + +/** + * @author Achour BERRAHMA + */ +@Configuration +public class RestTemplateConfig { + + @Bean + public RestTemplate restTemplate() { + final RestTemplate restTemplate = new RestTemplate(); + + //find and replace Jackson message converter with our own + for (int i = 0; i < restTemplate.getMessageConverters().size(); i++) { + final HttpMessageConverter httpMessageConverter = restTemplate.getMessageConverters().get(i); + if (httpMessageConverter instanceof MappingJackson2HttpMessageConverter) { + restTemplate.getMessageConverters().set(i, mappingJackson2HttpMessageConverter()); + } + } + + return restTemplate; + } + + public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() { + MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); + converter.setObjectMapper(objectMapper()); + return converter; + } + + private ObjectMapper createObjectMapper() { + var objectMapper = Jackson2ObjectMapperBuilder.json().build(); + objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); + objectMapper.registerModule(new JsonComponentModule()); + return objectMapper; + } + + @Bean + public ObjectMapper objectMapper() { + return createObjectMapper(); + } +} + diff --git a/src/main/java/org/gridsuite/spreadsheetconfig/server/SpreadsheetConfigApi.java b/src/main/java/org/gridsuite/spreadsheetconfig/server/SpreadsheetConfigApi.java new file mode 100644 index 0000000..ed66f6c --- /dev/null +++ b/src/main/java/org/gridsuite/spreadsheetconfig/server/SpreadsheetConfigApi.java @@ -0,0 +1,18 @@ +/** + * Copyright (c) 2024, RTE (http://www.rte-france.com) + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ +package org.gridsuite.spreadsheetconfig.server; + +/** + * @author Achour BERRAHMA + */ +public final class SpreadsheetConfigApi { + + private SpreadsheetConfigApi() { + } + + public static final String API_VERSION = "v1"; +} diff --git a/src/main/java/org/gridsuite/spreadsheetconfig/server/SpreadsheetConfigApplication.java b/src/main/java/org/gridsuite/spreadsheetconfig/server/SpreadsheetConfigApplication.java new file mode 100644 index 0000000..d75e64e --- /dev/null +++ b/src/main/java/org/gridsuite/spreadsheetconfig/server/SpreadsheetConfigApplication.java @@ -0,0 +1,22 @@ +/** + * Copyright (c) 2024, RTE (http://www.rte-france.com) + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ +package org.gridsuite.spreadsheetconfig.server; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +/** + * @author Achour BERRAHMA + */ +@SuppressWarnings("checkstyle:HideUtilityClassConstructor") +@SpringBootApplication +public class SpreadsheetConfigApplication { + + public static void main(String[] args) { + SpringApplication.run(SpreadsheetConfigApplication.class, args); + } +} diff --git a/src/main/java/org/gridsuite/spreadsheetconfig/server/SwaggerConfig.java b/src/main/java/org/gridsuite/spreadsheetconfig/server/SwaggerConfig.java new file mode 100644 index 0000000..2f7c164 --- /dev/null +++ b/src/main/java/org/gridsuite/spreadsheetconfig/server/SwaggerConfig.java @@ -0,0 +1,28 @@ +/** + * Copyright (c) 2024, RTE (http://www.rte-france.com) + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ +package org.gridsuite.spreadsheetconfig.server; + +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.info.Info; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * @author Achour BERRAHMA + */ +@Configuration +public class SwaggerConfig { + + @Bean + public OpenAPI openAPI() { + return new OpenAPI() + .info(new Info() + .title("Spreadsheet Config API") + .description("This is the documentation of the spreadsheet config REST API") + .version(SpreadsheetConfigApi.API_VERSION)); + } +} diff --git a/src/main/java/org/gridsuite/spreadsheetconfig/server/constants/SheetType.java b/src/main/java/org/gridsuite/spreadsheetconfig/server/constants/SheetType.java new file mode 100644 index 0000000..c583d26 --- /dev/null +++ b/src/main/java/org/gridsuite/spreadsheetconfig/server/constants/SheetType.java @@ -0,0 +1,29 @@ +/** + * Copyright (c) 2024, RTE (http://www.rte-france.com) + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ +package org.gridsuite.spreadsheetconfig.server.constants; + +/** + * @author Achour BERRAHMA + */ +public enum SheetType { + SUBSTATIONS, + VOLTAGE_LEVELS, + LINES, + TWO_WINDINGS_TRANSFORMERS, + THREE_WINDINGS_TRANSFORMERS, + GENERATORS, + LOADS, + SHUNT_COMPENSATORS, + STATIC_VAR_COMPENSATORS, + BATTERIES, + HVDC_LINES, + LCC_CONVERTER_STATIONS, + VSC_CONVERTER_STATIONS, + DANGLING_LINES, + BUSES, + TIE_LINES +} diff --git a/src/main/java/org/gridsuite/spreadsheetconfig/server/controller/SpreadsheetConfigController.java b/src/main/java/org/gridsuite/spreadsheetconfig/server/controller/SpreadsheetConfigController.java new file mode 100644 index 0000000..fa41bd0 --- /dev/null +++ b/src/main/java/org/gridsuite/spreadsheetconfig/server/controller/SpreadsheetConfigController.java @@ -0,0 +1,106 @@ +/** + * Copyright (c) 2024, RTE (http://www.rte-france.com) + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ +package org.gridsuite.spreadsheetconfig.server.controller; + +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.gridsuite.spreadsheetconfig.server.SpreadsheetConfigApi; +import org.gridsuite.spreadsheetconfig.server.dto.SpreadsheetConfigDto; +import org.gridsuite.spreadsheetconfig.server.service.SpreadsheetConfigService; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.util.List; +import java.util.UUID; + +import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; + +/** + * @author Achour BERRAHMA + */ +@RestController +@RequestMapping(value = "/" + SpreadsheetConfigApi.API_VERSION + "/spreadsheet-configs") +@RequiredArgsConstructor +@Tag(name = "Spreadsheet Config", description = "Spreadsheet Configuration API") +public class SpreadsheetConfigController { + + private final SpreadsheetConfigService spreadsheetConfigService; + + public static final String DUPLICATE_FROM = "duplicateFrom"; + + @PostMapping(consumes = APPLICATION_JSON_VALUE) + @Operation(summary = "Create a new spreadsheet configuration", + description = "Creates a new spreadsheet configuration and returns its ID") + @ApiResponse(responseCode = "201", description = "Configuration created", + content = @Content(schema = @Schema(implementation = UUID.class))) + public ResponseEntity createSpreadsheetConfig(@Parameter(description = "Configuration to save") @Valid @RequestBody SpreadsheetConfigDto dto) { + UUID id = spreadsheetConfigService.createSpreadsheetConfig(dto); + return ResponseEntity.status(HttpStatus.CREATED).body(id); + } + + @PostMapping(value = "/duplicate", params = { DUPLICATE_FROM }) + @Operation(summary = "Duplicate a spreadsheet configuration", + description = "Creates a copy of an existing spreadsheet configuration") + @ApiResponse(responseCode = "201", description = "Configuration duplicated", + content = @Content(schema = @Schema(implementation = UUID.class))) + @ApiResponse(responseCode = "404", description = "Configuration not found") + public ResponseEntity duplicateSpreadsheetConfig(@Parameter(description = "UUID of the configuration to duplicate") @RequestParam(name = DUPLICATE_FROM) UUID id) { + return spreadsheetConfigService.duplicateSpreadsheetConfig(id) + .map(newId -> ResponseEntity.status(HttpStatus.CREATED).body(newId)) + .orElse(ResponseEntity.notFound().build()); + } + + @GetMapping("/{id}") + @Operation(summary = "Get a spreadsheet configuration", + description = "Retrieves a spreadsheet configuration by its ID") + @ApiResponse(responseCode = "200", description = "Configuration found", + content = @Content(schema = @Schema(implementation = SpreadsheetConfigDto.class))) + @ApiResponse(responseCode = "404", description = "Configuration not found") + public ResponseEntity getSpreadsheetConfig( + @Parameter(description = "ID of the configuration to retrieve") @PathVariable UUID id) { + return ResponseEntity.of(spreadsheetConfigService.getSpreadsheetConfig(id)); + } + + @GetMapping + @Operation(summary = "Get all spreadsheet configurations", + description = "Retrieves all spreadsheet configurations") + @ApiResponse(responseCode = "200", description = "List of configurations", + content = @Content(schema = @Schema(implementation = SpreadsheetConfigDto.class))) + public ResponseEntity> getAllSpreadsheetConfigs() { + return ResponseEntity.ok(spreadsheetConfigService.getAllSpreadsheetConfigs()); + } + + @PutMapping("/{id}") + @Operation(summary = "Update a spreadsheet configuration", + description = "Updates an existing spreadsheet configuration") + @ApiResponse(responseCode = "204", description = "Configuration updated") + @ApiResponse(responseCode = "404", description = "Configuration not found") + public ResponseEntity updateSpreadsheetConfig( + @Parameter(description = "ID of the configuration to update") @PathVariable UUID id, + @Valid @RequestBody SpreadsheetConfigDto dto) { + spreadsheetConfigService.updateSpreadsheetConfig(id, dto); + return ResponseEntity.noContent().build(); + } + + @DeleteMapping("/{id}") + @Operation(summary = "Delete a spreadsheet configuration", + description = "Deletes an existing spreadsheet configuration") + @ApiResponse(responseCode = "204", description = "Configuration deleted") + @ApiResponse(responseCode = "404", description = "Configuration not found") + public ResponseEntity deleteSpreadsheetConfig( + @Parameter(description = "ID of the configuration to delete") @PathVariable UUID id) { + spreadsheetConfigService.deleteSpreadsheetConfig(id); + return ResponseEntity.noContent().build(); + } +} diff --git a/src/main/java/org/gridsuite/spreadsheetconfig/server/dto/CustomColumnDto.java b/src/main/java/org/gridsuite/spreadsheetconfig/server/dto/CustomColumnDto.java new file mode 100644 index 0000000..944361e --- /dev/null +++ b/src/main/java/org/gridsuite/spreadsheetconfig/server/dto/CustomColumnDto.java @@ -0,0 +1,37 @@ +/** + * Copyright (c) 2024, RTE (http://www.rte-france.com) + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ +package org.gridsuite.spreadsheetconfig.server.dto; + +import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.validation.constraints.NotNull; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.extern.jackson.Jacksonized; + +import java.util.UUID; + +/** + * @author Achour BERRAHMA + */ +@Data +@AllArgsConstructor +@Builder +@Jacksonized +@Schema(name = "CustomColumnDto", description = "Custom column configuration") +public class CustomColumnDto { + + @Schema(description = "Custom column ID") + UUID id; + + @NotNull(message = "Column name is mandatory") + @Schema(description = "Column name") + String name; + + @Schema(description = "Column formula") + String formula; +} diff --git a/src/main/java/org/gridsuite/spreadsheetconfig/server/dto/SpreadsheetConfigDto.java b/src/main/java/org/gridsuite/spreadsheetconfig/server/dto/SpreadsheetConfigDto.java new file mode 100644 index 0000000..caee7cf --- /dev/null +++ b/src/main/java/org/gridsuite/spreadsheetconfig/server/dto/SpreadsheetConfigDto.java @@ -0,0 +1,37 @@ +/** + * Copyright (c) 2024, RTE (http://www.rte-france.com) + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ +package org.gridsuite.spreadsheetconfig.server.dto; + +import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.validation.constraints.NotNull; +import lombok.Builder; +import lombok.Value; +import lombok.extern.jackson.Jacksonized; +import org.gridsuite.spreadsheetconfig.server.constants.SheetType; + +import java.util.List; +import java.util.UUID; + +/** + * @author Achour BERRAHMA + */ +@Value +@Builder +@Jacksonized +@Schema(name = "SpreadsheetConfigDto", description = "Spreadsheet configuration") +public class SpreadsheetConfigDto { + + @Schema(description = "Spreadsheet configuration ID") + UUID id; + + @NotNull(message = "Sheet type is mandatory") + @Schema(description = "Spreadsheet type") + SheetType sheetType; + + @Schema(description = "Custom columns") + List customColumns; +} diff --git a/src/main/java/org/gridsuite/spreadsheetconfig/server/entities/CustomColumnEntity.java b/src/main/java/org/gridsuite/spreadsheetconfig/server/entities/CustomColumnEntity.java new file mode 100644 index 0000000..8d944b8 --- /dev/null +++ b/src/main/java/org/gridsuite/spreadsheetconfig/server/entities/CustomColumnEntity.java @@ -0,0 +1,40 @@ +/** + * Copyright (c) 2024, RTE (http://www.rte-france.com) + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ +package org.gridsuite.spreadsheetconfig.server.entities; + +import jakarta.persistence.*; +import lombok.*; + +import java.util.UUID; + +/** + * @author Achour BERRAHMA + */ +@Entity +@Table(name = "spreadsheet_custom_column") +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor +@Builder +public class CustomColumnEntity { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "id") + private UUID id; + + @Column(name = "name", nullable = false, columnDefinition = "varchar(255)") + private String name; + + @Column(name = "formula", columnDefinition = "varchar(255)") + private String formula; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "spreadsheet_config_id", nullable = false, foreignKey = @ForeignKey(name = "spreadsheet_config_id_fk_constraint")) + private SpreadsheetConfigEntity spreadsheetConfig; +} diff --git a/src/main/java/org/gridsuite/spreadsheetconfig/server/entities/SpreadsheetConfigEntity.java b/src/main/java/org/gridsuite/spreadsheetconfig/server/entities/SpreadsheetConfigEntity.java new file mode 100644 index 0000000..ee07fc6 --- /dev/null +++ b/src/main/java/org/gridsuite/spreadsheetconfig/server/entities/SpreadsheetConfigEntity.java @@ -0,0 +1,42 @@ +/** + * Copyright (c) 2024, RTE (http://www.rte-france.com) + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ +package org.gridsuite.spreadsheetconfig.server.entities; + +import jakarta.persistence.*; +import lombok.*; +import org.gridsuite.spreadsheetconfig.server.constants.SheetType; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +/** + * @author Achour BERRAHMA + */ +@Builder +@NoArgsConstructor +@AllArgsConstructor +@Getter +@Setter +@Entity +@Table(name = "spreadsheet_config") +public class SpreadsheetConfigEntity { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "id") + private UUID id; + + @Column(name = "sheet_type", nullable = false) + @Enumerated(EnumType.STRING) + private SheetType sheetType; + + @OneToMany(mappedBy = "spreadsheetConfig", cascade = CascadeType.ALL, orphanRemoval = true) + @Builder.Default + private List customColumns = new ArrayList<>(); + +} diff --git a/src/main/java/org/gridsuite/spreadsheetconfig/server/mapper/SpreadsheetConfigMapper.java b/src/main/java/org/gridsuite/spreadsheetconfig/server/mapper/SpreadsheetConfigMapper.java new file mode 100644 index 0000000..05f6007 --- /dev/null +++ b/src/main/java/org/gridsuite/spreadsheetconfig/server/mapper/SpreadsheetConfigMapper.java @@ -0,0 +1,62 @@ +/** + * Copyright (c) 2024, RTE (http://www.rte-france.com) + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ +package org.gridsuite.spreadsheetconfig.server.mapper; + +import org.gridsuite.spreadsheetconfig.server.dto.SpreadsheetConfigDto; +import org.gridsuite.spreadsheetconfig.server.dto.CustomColumnDto; +import org.gridsuite.spreadsheetconfig.server.entities.SpreadsheetConfigEntity; +import org.gridsuite.spreadsheetconfig.server.entities.CustomColumnEntity; +import org.springframework.stereotype.Component; + +/** + * @author Achour BERRAHMA + */ +@Component +public class SpreadsheetConfigMapper { + + public SpreadsheetConfigDto toDto(SpreadsheetConfigEntity entity) { + return SpreadsheetConfigDto.builder() + .id(entity.getId()) + .sheetType(entity.getSheetType()) + .customColumns(entity.getCustomColumns().stream() + .map(this::toCustomColumnDto) + .toList()) + .build(); + } + + public SpreadsheetConfigEntity toEntity(SpreadsheetConfigDto dto) { + SpreadsheetConfigEntity entity = SpreadsheetConfigEntity.builder() + .id(dto.getId()) + .sheetType(dto.getSheetType()) + .build(); + + if (dto.getCustomColumns() != null) { + entity.setCustomColumns(dto.getCustomColumns().stream() + .map(columnDto -> toCustomColumnEntity(columnDto, entity)) + .toList()); + } + + return entity; + } + + public CustomColumnDto toCustomColumnDto(CustomColumnEntity entity) { + return CustomColumnDto.builder() + .id(entity.getId()) + .name(entity.getName()) + .formula(entity.getFormula()) + .build(); + } + + public CustomColumnEntity toCustomColumnEntity(CustomColumnDto dto, SpreadsheetConfigEntity spreadsheetConfig) { + return CustomColumnEntity.builder() + .id(dto.getId()) + .name(dto.getName()) + .formula(dto.getFormula()) + .spreadsheetConfig(spreadsheetConfig) + .build(); + } +} diff --git a/src/main/java/org/gridsuite/spreadsheetconfig/server/repositories/CustomColumnRepository.java b/src/main/java/org/gridsuite/spreadsheetconfig/server/repositories/CustomColumnRepository.java new file mode 100644 index 0000000..caf27b4 --- /dev/null +++ b/src/main/java/org/gridsuite/spreadsheetconfig/server/repositories/CustomColumnRepository.java @@ -0,0 +1,20 @@ +/** + * Copyright (c) 2024, RTE (http://www.rte-france.com) + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ +package org.gridsuite.spreadsheetconfig.server.repositories; + +import org.gridsuite.spreadsheetconfig.server.entities.CustomColumnEntity; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.UUID; + +/** + * @author Achour BERRAHMA + */ +@Repository +public interface CustomColumnRepository extends JpaRepository { +} diff --git a/src/main/java/org/gridsuite/spreadsheetconfig/server/repositories/SpreadsheetConfigRepository.java b/src/main/java/org/gridsuite/spreadsheetconfig/server/repositories/SpreadsheetConfigRepository.java new file mode 100644 index 0000000..eaf0935 --- /dev/null +++ b/src/main/java/org/gridsuite/spreadsheetconfig/server/repositories/SpreadsheetConfigRepository.java @@ -0,0 +1,20 @@ +/** + * Copyright (c) 2024, RTE (http://www.rte-france.com) + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ +package org.gridsuite.spreadsheetconfig.server.repositories; + +import org.gridsuite.spreadsheetconfig.server.entities.SpreadsheetConfigEntity; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.UUID; + +/** + * @author Achour BERRAHMA + */ +@Repository +public interface SpreadsheetConfigRepository extends JpaRepository { +} diff --git a/src/main/java/org/gridsuite/spreadsheetconfig/server/service/SpreadsheetConfigService.java b/src/main/java/org/gridsuite/spreadsheetconfig/server/service/SpreadsheetConfigService.java new file mode 100644 index 0000000..3dcbfcb --- /dev/null +++ b/src/main/java/org/gridsuite/spreadsheetconfig/server/service/SpreadsheetConfigService.java @@ -0,0 +1,98 @@ +/** + * Copyright (c) 2024, RTE (http://www.rte-france.com) + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ +package org.gridsuite.spreadsheetconfig.server.service; + +import jakarta.persistence.EntityNotFoundException; +import lombok.RequiredArgsConstructor; +import org.gridsuite.spreadsheetconfig.server.dto.SpreadsheetConfigDto; +import org.gridsuite.spreadsheetconfig.server.entities.CustomColumnEntity; +import org.gridsuite.spreadsheetconfig.server.entities.SpreadsheetConfigEntity; +import org.gridsuite.spreadsheetconfig.server.mapper.SpreadsheetConfigMapper; +import org.gridsuite.spreadsheetconfig.server.repositories.SpreadsheetConfigRepository; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +/** + * @author Achour BERRAHMA + */ +@Service +@RequiredArgsConstructor +public class SpreadsheetConfigService { + + private final SpreadsheetConfigRepository spreadsheetConfigRepository; + + private final SpreadsheetConfigMapper spreadsheetConfigMapper; + + @Transactional + public UUID createSpreadsheetConfig(SpreadsheetConfigDto dto) { + SpreadsheetConfigEntity entity = spreadsheetConfigMapper.toEntity(dto); + return spreadsheetConfigRepository.save(entity).getId(); + } + + @Transactional + public Optional duplicateSpreadsheetConfig(UUID id) { + return spreadsheetConfigRepository.findById(id) + .map(entity -> { + SpreadsheetConfigEntity duplicate = SpreadsheetConfigEntity.builder() + .sheetType(entity.getSheetType()) + .build(); + + List customColumns = entity.getCustomColumns().stream() + .map(column -> CustomColumnEntity.builder() + .name(column.getName()) + .formula(column.getFormula()) + .spreadsheetConfig(duplicate) + .build()) + .toList(); + + duplicate.setCustomColumns(customColumns); + + return spreadsheetConfigRepository.save(duplicate).getId(); + }); + } + + @Transactional(readOnly = true) + public Optional getSpreadsheetConfig(UUID id) { + return spreadsheetConfigRepository.findById(id) + .map(spreadsheetConfigMapper::toDto); + } + + @Transactional(readOnly = true) + public List getAllSpreadsheetConfigs() { + return spreadsheetConfigRepository.findAll() + .stream() + .map(spreadsheetConfigMapper::toDto) + .toList(); + } + + @Transactional + public void updateSpreadsheetConfig(UUID id, SpreadsheetConfigDto dto) { + SpreadsheetConfigEntity entity = spreadsheetConfigRepository.findById(id) + .orElseThrow(() -> new EntityNotFoundException("SpreadsheetConfig not found with id: " + id)); + + entity.setSheetType(dto.getSheetType()); + entity.getCustomColumns().clear(); + if (dto.getCustomColumns() != null) { + entity.getCustomColumns().addAll(dto.getCustomColumns().stream() + .map(columnDto -> spreadsheetConfigMapper.toCustomColumnEntity(columnDto, entity)) + .toList()); + } + } + + @Transactional + public void deleteSpreadsheetConfig(UUID id) { + if (!spreadsheetConfigRepository.existsById(id)) { + throw new EntityNotFoundException("SpreadsheetConfig not found with id: " + id); + } + spreadsheetConfigRepository.deleteById(id); + } + +} diff --git a/src/main/resources/application-local.yml b/src/main/resources/application-local.yml new file mode 100644 index 0000000..5e85bd0 --- /dev/null +++ b/src/main/resources/application-local.yml @@ -0,0 +1,6 @@ +server: + port: 5035 + +powsybl-ws: + database: + host: localhost \ No newline at end of file diff --git a/src/main/resources/config/application.yaml b/src/main/resources/config/application.yaml new file mode 100644 index 0000000..b197d3b --- /dev/null +++ b/src/main/resources/config/application.yaml @@ -0,0 +1,7 @@ +spring: + application: + name: spreadsheet-config + +powsybl-ws: + database: + name: spreadsheetconfig \ No newline at end of file diff --git a/src/main/resources/db/changelog/changesets/create-spreadsheet-config-table.xml b/src/main/resources/db/changelog/changesets/create-spreadsheet-config-table.xml new file mode 100644 index 0000000..4a6ec14 --- /dev/null +++ b/src/main/resources/db/changelog/changesets/create-spreadsheet-config-table.xml @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/resources/db/changelog/db.changelog-master.yaml b/src/main/resources/db/changelog/db.changelog-master.yaml new file mode 100644 index 0000000..8c7162f --- /dev/null +++ b/src/main/resources/db/changelog/db.changelog-master.yaml @@ -0,0 +1,4 @@ +databaseChangeLog: + - include: + file: changesets/create-spreadsheet-config-table.xml + relativeToChangelogFile: true \ No newline at end of file diff --git a/src/test/java/org/gridsuite/spreadsheetconfig/server/SpreadsheetConfigControllerTest.java b/src/test/java/org/gridsuite/spreadsheetconfig/server/SpreadsheetConfigControllerTest.java new file mode 100644 index 0000000..afb756b --- /dev/null +++ b/src/test/java/org/gridsuite/spreadsheetconfig/server/SpreadsheetConfigControllerTest.java @@ -0,0 +1,246 @@ +/** + * Copyright (c) 2024, RTE (http://www.rte-france.com) + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ +package org.gridsuite.spreadsheetconfig.server; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.gridsuite.spreadsheetconfig.server.constants.SheetType; +import org.gridsuite.spreadsheetconfig.server.dto.CustomColumnDto; +import org.gridsuite.spreadsheetconfig.server.dto.SpreadsheetConfigDto; +import org.gridsuite.spreadsheetconfig.server.repositories.SpreadsheetConfigRepository; +import org.gridsuite.spreadsheetconfig.server.service.SpreadsheetConfigService; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; + +import java.util.Arrays; +import java.util.List; +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +/** + * @author Achour BERRAHMA + */ +@SpringBootTest +@AutoConfigureMockMvc +class SpreadsheetConfigControllerTest { + + private static final String URI_SPREADSHEET_CONFIG_BASE = "/v1/spreadsheet-configs"; + private static final String URI_SPREADSHEET_CONFIG_GET_PUT = URI_SPREADSHEET_CONFIG_BASE + "/"; + + @Autowired + private MockMvc mockMvc; + + @Autowired + private ObjectMapper mapper; + + @Autowired + private SpreadsheetConfigService spreadsheetConfigService; + + @Autowired + private SpreadsheetConfigRepository spreadsheetConfigRepository; + + @AfterEach + public void tearDown() { + spreadsheetConfigRepository.deleteAll(); + } + + @Test + void testCreate() throws Exception { + SpreadsheetConfigDto configToCreate = SpreadsheetConfigDto.builder() + .sheetType(SheetType.BATTERIES) + .customColumns(createCustomColumns()) + .build(); + + UUID configUuid = postSpreadsheetConfig(configToCreate); + SpreadsheetConfigDto createdConfig = getSpreadsheetConfig(configUuid); + + assertThat(createdConfig) + .usingRecursiveComparison() + .ignoringFields("id", "customColumns.id") + .isEqualTo(configToCreate); + assertThat(createdConfig.getId()).isNotNull(); + assertThat(createdConfig.getCustomColumns()).allMatch(column -> column.getId() != null); + } + + @Test + void testRead() throws Exception { + SpreadsheetConfigDto configToRead = SpreadsheetConfigDto.builder() + .sheetType(SheetType.BUSES) + .customColumns(createCustomColumns()) + .build(); + + UUID configUuid = saveAndReturnId(configToRead); + + SpreadsheetConfigDto receivedConfig = getSpreadsheetConfig(configUuid); + + assertThat(receivedConfig) + .usingRecursiveComparison() + .ignoringFields("id", "customColumns.id") + .isEqualTo(configToRead); + assertThat(receivedConfig.getId()).isEqualTo(configUuid); + assertThat(receivedConfig.getCustomColumns()).allMatch(column -> column.getId() != null); + } + + @Test + void testUpdate() throws Exception { + SpreadsheetConfigDto configToUpdate = SpreadsheetConfigDto.builder() + .sheetType(SheetType.BATTERIES) + .customColumns(createCustomColumns()) + .build(); + + UUID configUuid = saveAndReturnId(configToUpdate); + + SpreadsheetConfigDto updatedConfig = SpreadsheetConfigDto.builder() + .id(configUuid) + .sheetType(SheetType.BUSES) + .customColumns(createUpdatedCustomColumns()) + .build(); + + String updatedConfigJson = mapper.writeValueAsString(updatedConfig); + + mockMvc.perform(put(URI_SPREADSHEET_CONFIG_GET_PUT + configUuid) + .content(updatedConfigJson) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isNoContent()); + + SpreadsheetConfigDto retrievedConfig = getSpreadsheetConfig(configUuid); + + assertThat(retrievedConfig) + .usingRecursiveComparison() + .ignoringFields("customColumns.id") + .isEqualTo(updatedConfig); + } + + @Test + void testDelete() throws Exception { + SpreadsheetConfigDto configToDelete = SpreadsheetConfigDto.builder() + .sheetType(SheetType.BATTERIES) + .customColumns(createCustomColumns()) + .build(); + + UUID configUuid = saveAndReturnId(configToDelete); + + mockMvc.perform(delete(URI_SPREADSHEET_CONFIG_GET_PUT + configUuid)) + .andExpect(status().isNoContent()); + + List storedConfigs = getAllSpreadsheetConfigs(); + + assertThat(storedConfigs).isEmpty(); + } + + @Test + void testGetAll() throws Exception { + SpreadsheetConfigDto config1 = SpreadsheetConfigDto.builder() + .sheetType(SheetType.BATTERIES) + .customColumns(createCustomColumns()) + .build(); + SpreadsheetConfigDto config2 = SpreadsheetConfigDto.builder() + .sheetType(SheetType.BUSES) + .customColumns(createUpdatedCustomColumns()) + .build(); + + saveAndReturnId(config1); + saveAndReturnId(config2); + + List receivedConfigs = getAllSpreadsheetConfigs(); + + assertThat(receivedConfigs).hasSize(2); + } + + @Test + void testDuplicate() throws Exception { + SpreadsheetConfigDto configToCreate = SpreadsheetConfigDto.builder() + .sheetType(SheetType.BATTERIES) + .customColumns(createCustomColumns()) + .build(); + UUID configUuid = postSpreadsheetConfig(configToCreate); + + mockMvc.perform(post(URI_SPREADSHEET_CONFIG_BASE + "/duplicate") + .queryParam("duplicateFrom", UUID.randomUUID().toString())) + .andExpect(status().isNotFound()); + + UUID duplicatedConfigUuid = duplicateSpreadsheetConfig(configUuid); + + SpreadsheetConfigDto duplicatedConfig = getSpreadsheetConfig(duplicatedConfigUuid); + assertThat(duplicatedConfig) + .usingRecursiveComparison() + .ignoringFields("id", "customColumns.id") + .isEqualTo(configToCreate); + assertThat(duplicatedConfig.getId()).isNotEqualTo(configUuid); + } + + private List createCustomColumns() { + return Arrays.asList( + new CustomColumnDto(null, "cust_a", "cust_b + cust_c"), + new CustomColumnDto(null, "cust_b", "var_minP + 1"), + new CustomColumnDto(null, "cust_c", "cust_b + 1"), + new CustomColumnDto(null, "cust_d", "5 + 2") + ); + } + + private List createUpdatedCustomColumns() { + return Arrays.asList( + new CustomColumnDto(null, "cust_x", "cust_y * 2"), + new CustomColumnDto(null, "cust_y", "var_maxP - 1"), + new CustomColumnDto(null, "cust_z", "cust_x / 2") + ); + } + + private SpreadsheetConfigDto getSpreadsheetConfig(UUID configUuid) throws Exception { + MvcResult mvcGetResult = mockMvc.perform(get(URI_SPREADSHEET_CONFIG_GET_PUT + configUuid)) + .andExpect(status().isOk()) + .andReturn(); + + return mapper.readValue( + mvcGetResult.getResponse().getContentAsString(), + SpreadsheetConfigDto.class); + } + + private UUID postSpreadsheetConfig(SpreadsheetConfigDto configToCreate) throws Exception { + String configToCreateJson = mapper.writeValueAsString(configToCreate); + + MvcResult mvcPostResult = mockMvc.perform(post(URI_SPREADSHEET_CONFIG_BASE) + .content(configToCreateJson) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isCreated()) + .andReturn(); + + return mapper.readValue(mvcPostResult.getResponse().getContentAsString(), UUID.class); + } + + private UUID duplicateSpreadsheetConfig(UUID configUuid) throws Exception { + MvcResult mvcPostResult = mockMvc.perform(post(URI_SPREADSHEET_CONFIG_BASE + "/duplicate") + .queryParam("duplicateFrom", configUuid.toString())) + .andExpect(status().isCreated()) + .andReturn(); + + return mapper.readValue(mvcPostResult.getResponse().getContentAsString(), UUID.class); + } + + private List getAllSpreadsheetConfigs() throws Exception { + MvcResult mvcResult = mockMvc.perform(get(URI_SPREADSHEET_CONFIG_BASE)) + .andExpect(status().isOk()) + .andReturn(); + + return mapper.readValue( + mvcResult.getResponse().getContentAsString(), + new TypeReference>() { }); + } + + private UUID saveAndReturnId(SpreadsheetConfigDto config) { + return spreadsheetConfigService.createSpreadsheetConfig(config); + } +} diff --git a/src/test/resources/application-default.yml b/src/test/resources/application-default.yml new file mode 100644 index 0000000..4feacb9 --- /dev/null +++ b/src/test/resources/application-default.yml @@ -0,0 +1,20 @@ +spring: + jpa: + database: H2 + properties: + dialect: org.hibernate.dialect.H2Dialect + hibernate.format_sql: true + hibernate.generate_statistics: true + +logging: + level: + org.springframework.orm.jpa: INFO + org.springframework.transaction: INFO + org.hibernate.SQL: INFO + org.hibernate.type.descriptor.sql.BasicBinder: INFO + +powsybl-ws: + database: + vendor: h2:mem + query: ;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE + hostPort: ":" diff --git a/src/test/resources/logback-test.xml b/src/test/resources/logback-test.xml new file mode 100644 index 0000000..c531f97 --- /dev/null +++ b/src/test/resources/logback-test.xml @@ -0,0 +1,42 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger - %msg%n + + + + + + + + + + From a570fb994764abc277eae375d8709012a1ca92fa Mon Sep 17 00:00:00 2001 From: achour94 Date: Fri, 27 Sep 2024 11:23:12 +0200 Subject: [PATCH 2/9] fix sonar project Signed-off-by: achour94 --- .github/workflows/maven.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml index af7f67e..9b60eb4 100644 --- a/.github/workflows/maven.yml +++ b/.github/workflows/maven.yml @@ -30,7 +30,7 @@ jobs: mvn --batch-mode -DskipTests sonar:sonar -Dsonar.host.url=https://sonarcloud.io -Dsonar.organization=gridsuite - -Dsonar.projectKey=org.gridsuite:gridsuite_spreadsheet-config-server + -Dsonar.projectKey=gridsuite_spreadsheet-config-server env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} From a0f8ad5633fe52d03264e112b32e716877ded52a Mon Sep 17 00:00:00 2001 From: achour94 Date: Fri, 27 Sep 2024 11:46:08 +0200 Subject: [PATCH 3/9] add tests Signed-off-by: achour94 --- .../RestResponseEntityExceptionHandler.java | 28 +++++++++ .../SpreadsheetConfigControllerTest.java | 63 +++++++++++++++++++ 2 files changed, 91 insertions(+) create mode 100644 src/main/java/org/gridsuite/spreadsheetconfig/server/RestResponseEntityExceptionHandler.java diff --git a/src/main/java/org/gridsuite/spreadsheetconfig/server/RestResponseEntityExceptionHandler.java b/src/main/java/org/gridsuite/spreadsheetconfig/server/RestResponseEntityExceptionHandler.java new file mode 100644 index 0000000..7044a3e --- /dev/null +++ b/src/main/java/org/gridsuite/spreadsheetconfig/server/RestResponseEntityExceptionHandler.java @@ -0,0 +1,28 @@ +/** + * Copyright (c) 2024, RTE (http://www.rte-france.com) + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ +package org.gridsuite.spreadsheetconfig.server; + +import jakarta.persistence.EntityNotFoundException; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.context.request.WebRequest; + +/** + * @author Achour BERRAHMA + */ +@ControllerAdvice +public class RestResponseEntityExceptionHandler { + + @ExceptionHandler(EntityNotFoundException.class) + protected ResponseEntity handleEntityNotFound( + EntityNotFoundException ex, WebRequest request) { + String bodyOfResponse = ex.getMessage(); + return new ResponseEntity<>(bodyOfResponse, HttpStatus.NOT_FOUND); + } +} diff --git a/src/test/java/org/gridsuite/spreadsheetconfig/server/SpreadsheetConfigControllerTest.java b/src/test/java/org/gridsuite/spreadsheetconfig/server/SpreadsheetConfigControllerTest.java index afb756b..6f39d9b 100644 --- a/src/test/java/org/gridsuite/spreadsheetconfig/server/SpreadsheetConfigControllerTest.java +++ b/src/test/java/org/gridsuite/spreadsheetconfig/server/SpreadsheetConfigControllerTest.java @@ -75,6 +75,21 @@ void testCreate() throws Exception { assertThat(createdConfig.getCustomColumns()).allMatch(column -> column.getId() != null); } + @Test + void testCreateWithInvalidData() throws Exception { + SpreadsheetConfigDto invalidConfig = SpreadsheetConfigDto.builder() + .sheetType(null) // SheetType is required + .customColumns(createCustomColumns()) + .build(); + + String invalidConfigJson = mapper.writeValueAsString(invalidConfig); + + mockMvc.perform(post(URI_SPREADSHEET_CONFIG_BASE) + .content(invalidConfigJson) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isBadRequest()); + } + @Test void testRead() throws Exception { SpreadsheetConfigDto configToRead = SpreadsheetConfigDto.builder() @@ -94,6 +109,37 @@ void testRead() throws Exception { assertThat(receivedConfig.getCustomColumns()).allMatch(column -> column.getId() != null); } + @Test + void testReadNonExistent() throws Exception { + UUID nonExistentUuid = UUID.randomUUID(); + + mockMvc.perform(get(URI_SPREADSHEET_CONFIG_GET_PUT + nonExistentUuid)) + .andExpect(status().isNotFound()); + } + + @Test + void testUpdateWithInvalidData() throws Exception { + SpreadsheetConfigDto configToUpdate = SpreadsheetConfigDto.builder() + .sheetType(SheetType.BATTERIES) + .customColumns(createCustomColumns()) + .build(); + + UUID configUuid = saveAndReturnId(configToUpdate); + + SpreadsheetConfigDto invalidUpdate = SpreadsheetConfigDto.builder() + .id(configUuid) + .sheetType(null) // SheetType is required + .customColumns(createUpdatedCustomColumns()) + .build(); + + String invalidUpdateJson = mapper.writeValueAsString(invalidUpdate); + + mockMvc.perform(put(URI_SPREADSHEET_CONFIG_GET_PUT + configUuid) + .content(invalidUpdateJson) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isBadRequest()); + } + @Test void testUpdate() throws Exception { SpreadsheetConfigDto configToUpdate = SpreadsheetConfigDto.builder() @@ -141,6 +187,14 @@ void testDelete() throws Exception { assertThat(storedConfigs).isEmpty(); } + @Test + void testDeleteNonExistent() throws Exception { + UUID nonExistentUuid = UUID.randomUUID(); + + mockMvc.perform(delete(URI_SPREADSHEET_CONFIG_GET_PUT + nonExistentUuid)) + .andExpect(status().isNotFound()); + } + @Test void testGetAll() throws Exception { SpreadsheetConfigDto config1 = SpreadsheetConfigDto.builder() @@ -182,6 +236,15 @@ void testDuplicate() throws Exception { assertThat(duplicatedConfig.getId()).isNotEqualTo(configUuid); } + @Test + void testDuplicateNonExistent() throws Exception { + UUID nonExistentUuid = UUID.randomUUID(); + + mockMvc.perform(post(URI_SPREADSHEET_CONFIG_BASE + "/duplicate") + .queryParam("duplicateFrom", nonExistentUuid.toString())) + .andExpect(status().isNotFound()); + } + private List createCustomColumns() { return Arrays.asList( new CustomColumnDto(null, "cust_a", "cust_b + cust_c"), From 593dd0b80b013554f4d6c7c166ffd820844fe810 Mon Sep 17 00:00:00 2001 From: achour94 Date: Fri, 27 Sep 2024 13:29:53 +0200 Subject: [PATCH 4/9] add tests Signed-off-by: achour94 --- .../server/DtoConverterTest.java | 131 ++++++++++++++++++ 1 file changed, 131 insertions(+) create mode 100644 src/test/java/org/gridsuite/spreadsheetconfig/server/DtoConverterTest.java diff --git a/src/test/java/org/gridsuite/spreadsheetconfig/server/DtoConverterTest.java b/src/test/java/org/gridsuite/spreadsheetconfig/server/DtoConverterTest.java new file mode 100644 index 0000000..a0239b3 --- /dev/null +++ b/src/test/java/org/gridsuite/spreadsheetconfig/server/DtoConverterTest.java @@ -0,0 +1,131 @@ +/** + * Copyright (c) 2024, RTE (http://www.rte-france.com) + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ +package org.gridsuite.spreadsheetconfig.server; + +import org.assertj.core.api.WithAssertions; +import org.gridsuite.spreadsheetconfig.server.constants.SheetType; +import org.gridsuite.spreadsheetconfig.server.dto.CustomColumnDto; +import org.gridsuite.spreadsheetconfig.server.dto.SpreadsheetConfigDto; +import org.gridsuite.spreadsheetconfig.server.entities.CustomColumnEntity; +import org.gridsuite.spreadsheetconfig.server.entities.SpreadsheetConfigEntity; +import org.gridsuite.spreadsheetconfig.server.mapper.SpreadsheetConfigMapper; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.UUID; + +/** + * @author Achour BERRAHMA + */ +public class DtoConverterTest implements WithAssertions { + + private final SpreadsheetConfigMapper mapper = new SpreadsheetConfigMapper(); + + @Nested + class SpreadsheetConfigConverterTest { + + @Test + void testConversionToDtoOfSpreadsheetConfig() { + UUID id = UUID.randomUUID(); + SpreadsheetConfigEntity entity = SpreadsheetConfigEntity.builder() + .id(id) + .sheetType(SheetType.BATTERIES) + .customColumns(Arrays.asList( + CustomColumnEntity.builder().id(UUID.randomUUID()).name("Column1").formula("A+B").build(), + CustomColumnEntity.builder().id(UUID.randomUUID()).name("Column2").formula("C*D").build() + )) + .build(); + + SpreadsheetConfigDto dto = mapper.toDto(entity); + + assertThat(dto) + .as("DTO conversion result") + .satisfies(d -> { + assertThat(d.getId()).isEqualTo(id); + assertThat(d.getSheetType()).isEqualTo(SheetType.BATTERIES); + assertThat(d.getCustomColumns()).hasSize(2); + assertThat(d.getCustomColumns().get(0).getName()).isEqualTo("Column1"); + assertThat(d.getCustomColumns().get(0).getFormula()).isEqualTo("A+B"); + assertThat(d.getCustomColumns().get(1).getName()).isEqualTo("Column2"); + assertThat(d.getCustomColumns().get(1).getFormula()).isEqualTo("C*D"); + }); + } + + @Test + void testConversionToEntityOfSpreadsheetConfig() { + UUID id = UUID.randomUUID(); + SpreadsheetConfigDto dto = SpreadsheetConfigDto.builder() + .id(id) + .sheetType(SheetType.BUSES) + .customColumns(Arrays.asList( + CustomColumnDto.builder().id(UUID.randomUUID()).name("Column1").formula("X+Y").build(), + CustomColumnDto.builder().id(UUID.randomUUID()).name("Column2").formula("Z*W").build() + )) + .build(); + + SpreadsheetConfigEntity entity = mapper.toEntity(dto); + + assertThat(entity) + .as("Entity conversion result") + .satisfies(e -> { + assertThat(e.getId()).isEqualTo(id); + assertThat(e.getSheetType()).isEqualTo(SheetType.BUSES); + assertThat(e.getCustomColumns()).hasSize(2); + assertThat(e.getCustomColumns().get(0).getName()).isEqualTo("Column1"); + assertThat(e.getCustomColumns().get(0).getFormula()).isEqualTo("X+Y"); + assertThat(e.getCustomColumns().get(1).getName()).isEqualTo("Column2"); + assertThat(e.getCustomColumns().get(1).getFormula()).isEqualTo("Z*W"); + }); + } + } + + @Nested + class CustomColumnConverterTest { + @Test + void testConversionToDtoOfCustomColumn() { + UUID id = UUID.randomUUID(); + CustomColumnEntity entity = CustomColumnEntity.builder() + .id(id) + .name("TestColumn") + .formula("A+B+C") + .build(); + + CustomColumnDto dto = mapper.toCustomColumnDto(entity); + + assertThat(dto) + .as("DTO conversion result") + .satisfies(d -> { + assertThat(d.getId()).isEqualTo(id); + assertThat(d.getName()).isEqualTo("TestColumn"); + assertThat(d.getFormula()).isEqualTo("A+B+C"); + }); + } + + @Test + void testConversionToEntityOfCustomColumn() { + UUID id = UUID.randomUUID(); + CustomColumnDto dto = CustomColumnDto.builder() + .id(id) + .name("TestColumn") + .formula("X*Y*Z") + .build(); + + SpreadsheetConfigEntity spreadsheetConfig = new SpreadsheetConfigEntity(); + CustomColumnEntity entity = mapper.toCustomColumnEntity(dto, spreadsheetConfig); + + assertThat(entity) + .as("Entity conversion result") + .satisfies(e -> { + assertThat(e.getId()).isEqualTo(id); + assertThat(e.getName()).isEqualTo("TestColumn"); + assertThat(e.getFormula()).isEqualTo("X*Y*Z"); + assertThat(e.getSpreadsheetConfig()).isEqualTo(spreadsheetConfig); + }); + } + } +} From f4e86194e0c1e93b6a74176e15984c6b5ab42204 Mon Sep 17 00:00:00 2001 From: achour94 Date: Fri, 27 Sep 2024 13:45:53 +0200 Subject: [PATCH 5/9] add tests Signed-off-by: achour94 --- .mvn/lombok-config-copy.marker | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 .mvn/lombok-config-copy.marker diff --git a/.mvn/lombok-config-copy.marker b/.mvn/lombok-config-copy.marker new file mode 100644 index 0000000..e69de29 From 4026ce8f9aea4a4600b439c7ccb70e6695cb51e3 Mon Sep 17 00:00:00 2001 From: achour94 Date: Mon, 30 Sep 2024 15:07:10 +0200 Subject: [PATCH 6/9] Resolve comments, add metadata endpoint Signed-off-by: achour94 --- pom.xml | 8 +- .../RestResponseEntityExceptionHandler.java | 3 +- .../server/RestTemplateConfig.java | 39 +---- .../server/SwaggerConfig.java | 6 +- .../SpreadsheetConfigController.java | 31 ++-- ...mColumnDto.java => CustomColumnInfos.java} | 21 +-- .../server/dto/MetadataInfos.java | 26 ++++ ...igDto.java => SpreadsheetConfigInfos.java} | 16 +-- ...ntity.java => CustomColumnEmbeddable.java} | 17 +-- .../entities/SpreadsheetConfigEntity.java | 8 +- .../mapper/SpreadsheetConfigMapper.java | 65 ++++----- .../repositories/CustomColumnRepository.java | 20 --- .../service/SpreadsheetConfigService.java | 78 +++++----- .../create-spreadsheet-config-table.xml | 17 ++- .../server/DtoConverterTest.java | 73 ++++------ .../SpreadsheetConfigControllerTest.java | 133 ++++++++---------- src/test/resources/logback-test.xml | 2 +- 17 files changed, 246 insertions(+), 317 deletions(-) rename src/main/java/org/gridsuite/spreadsheetconfig/server/dto/{CustomColumnDto.java => CustomColumnInfos.java} (68%) create mode 100644 src/main/java/org/gridsuite/spreadsheetconfig/server/dto/MetadataInfos.java rename src/main/java/org/gridsuite/spreadsheetconfig/server/dto/{SpreadsheetConfigDto.java => SpreadsheetConfigInfos.java} (79%) rename src/main/java/org/gridsuite/spreadsheetconfig/server/entities/{CustomColumnEntity.java => CustomColumnEmbeddable.java} (55%) delete mode 100644 src/main/java/org/gridsuite/spreadsheetconfig/server/repositories/CustomColumnRepository.java diff --git a/pom.xml b/pom.xml index d0e1fa4..44f94d5 100644 --- a/pom.xml +++ b/pom.xml @@ -42,7 +42,7 @@ - 33 + 34 org.gridsuite.spreadsheetconfig.server @@ -82,7 +82,6 @@ - org.springframework.bootspring-boot-starter-validation com.fasterxml.jackson.core jackson-databind @@ -131,11 +130,6 @@ spring-boot-starter-actuator runtime - - io.micrometer - micrometer-registry-prometheus - runtime - diff --git a/src/main/java/org/gridsuite/spreadsheetconfig/server/RestResponseEntityExceptionHandler.java b/src/main/java/org/gridsuite/spreadsheetconfig/server/RestResponseEntityExceptionHandler.java index 7044a3e..197ec6b 100644 --- a/src/main/java/org/gridsuite/spreadsheetconfig/server/RestResponseEntityExceptionHandler.java +++ b/src/main/java/org/gridsuite/spreadsheetconfig/server/RestResponseEntityExceptionHandler.java @@ -20,8 +20,7 @@ public class RestResponseEntityExceptionHandler { @ExceptionHandler(EntityNotFoundException.class) - protected ResponseEntity handleEntityNotFound( - EntityNotFoundException ex, WebRequest request) { + protected ResponseEntity handleEntityNotFound(EntityNotFoundException ex, WebRequest request) { String bodyOfResponse = ex.getMessage(); return new ResponseEntity<>(bodyOfResponse, HttpStatus.NOT_FOUND); } diff --git a/src/main/java/org/gridsuite/spreadsheetconfig/server/RestTemplateConfig.java b/src/main/java/org/gridsuite/spreadsheetconfig/server/RestTemplateConfig.java index e87f3a9..054ee4a 100644 --- a/src/main/java/org/gridsuite/spreadsheetconfig/server/RestTemplateConfig.java +++ b/src/main/java/org/gridsuite/spreadsheetconfig/server/RestTemplateConfig.java @@ -6,14 +6,9 @@ */ package org.gridsuite.spreadsheetconfig.server; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationFeature; -import org.springframework.boot.jackson.JsonComponentModule; +import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.http.converter.HttpMessageConverter; -import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; -import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.web.client.RestTemplate; /** @@ -23,36 +18,8 @@ public class RestTemplateConfig { @Bean - public RestTemplate restTemplate() { - final RestTemplate restTemplate = new RestTemplate(); - - //find and replace Jackson message converter with our own - for (int i = 0; i < restTemplate.getMessageConverters().size(); i++) { - final HttpMessageConverter httpMessageConverter = restTemplate.getMessageConverters().get(i); - if (httpMessageConverter instanceof MappingJackson2HttpMessageConverter) { - restTemplate.getMessageConverters().set(i, mappingJackson2HttpMessageConverter()); - } - } - - return restTemplate; - } - - public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() { - MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); - converter.setObjectMapper(objectMapper()); - return converter; - } - - private ObjectMapper createObjectMapper() { - var objectMapper = Jackson2ObjectMapperBuilder.json().build(); - objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); - objectMapper.registerModule(new JsonComponentModule()); - return objectMapper; - } - - @Bean - public ObjectMapper objectMapper() { - return createObjectMapper(); + public RestTemplate restTemplate(RestTemplateBuilder builder) { + return builder.build(); } } diff --git a/src/main/java/org/gridsuite/spreadsheetconfig/server/SwaggerConfig.java b/src/main/java/org/gridsuite/spreadsheetconfig/server/SwaggerConfig.java index 2f7c164..adf3cd1 100644 --- a/src/main/java/org/gridsuite/spreadsheetconfig/server/SwaggerConfig.java +++ b/src/main/java/org/gridsuite/spreadsheetconfig/server/SwaggerConfig.java @@ -21,8 +21,8 @@ public class SwaggerConfig { public OpenAPI openAPI() { return new OpenAPI() .info(new Info() - .title("Spreadsheet Config API") - .description("This is the documentation of the spreadsheet config REST API") - .version(SpreadsheetConfigApi.API_VERSION)); + .title("Spreadsheet Config API") + .description("This is the documentation of the spreadsheet config REST API") + .version(SpreadsheetConfigApi.API_VERSION)); } } diff --git a/src/main/java/org/gridsuite/spreadsheetconfig/server/controller/SpreadsheetConfigController.java b/src/main/java/org/gridsuite/spreadsheetconfig/server/controller/SpreadsheetConfigController.java index fa41bd0..75a6a52 100644 --- a/src/main/java/org/gridsuite/spreadsheetconfig/server/controller/SpreadsheetConfigController.java +++ b/src/main/java/org/gridsuite/spreadsheetconfig/server/controller/SpreadsheetConfigController.java @@ -15,7 +15,8 @@ import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; import org.gridsuite.spreadsheetconfig.server.SpreadsheetConfigApi; -import org.gridsuite.spreadsheetconfig.server.dto.SpreadsheetConfigDto; +import org.gridsuite.spreadsheetconfig.server.dto.MetadataInfos; +import org.gridsuite.spreadsheetconfig.server.dto.SpreadsheetConfigInfos; import org.gridsuite.spreadsheetconfig.server.service.SpreadsheetConfigService; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -44,7 +45,7 @@ public class SpreadsheetConfigController { description = "Creates a new spreadsheet configuration and returns its ID") @ApiResponse(responseCode = "201", description = "Configuration created", content = @Content(schema = @Schema(implementation = UUID.class))) - public ResponseEntity createSpreadsheetConfig(@Parameter(description = "Configuration to save") @Valid @RequestBody SpreadsheetConfigDto dto) { + public ResponseEntity createSpreadsheetConfig(@Parameter(description = "Configuration to save") @Valid @RequestBody SpreadsheetConfigInfos dto) { UUID id = spreadsheetConfigService.createSpreadsheetConfig(dto); return ResponseEntity.status(HttpStatus.CREATED).body(id); } @@ -56,28 +57,36 @@ public ResponseEntity createSpreadsheetConfig(@Parameter(description = "Co content = @Content(schema = @Schema(implementation = UUID.class))) @ApiResponse(responseCode = "404", description = "Configuration not found") public ResponseEntity duplicateSpreadsheetConfig(@Parameter(description = "UUID of the configuration to duplicate") @RequestParam(name = DUPLICATE_FROM) UUID id) { - return spreadsheetConfigService.duplicateSpreadsheetConfig(id) - .map(newId -> ResponseEntity.status(HttpStatus.CREATED).body(newId)) - .orElse(ResponseEntity.notFound().build()); + UUID newId = spreadsheetConfigService.duplicateSpreadsheetConfig(id); + return ResponseEntity.status(HttpStatus.CREATED).body(newId); } @GetMapping("/{id}") @Operation(summary = "Get a spreadsheet configuration", description = "Retrieves a spreadsheet configuration by its ID") @ApiResponse(responseCode = "200", description = "Configuration found", - content = @Content(schema = @Schema(implementation = SpreadsheetConfigDto.class))) + content = @Content(schema = @Schema(implementation = SpreadsheetConfigInfos.class))) @ApiResponse(responseCode = "404", description = "Configuration not found") - public ResponseEntity getSpreadsheetConfig( + public ResponseEntity getSpreadsheetConfig( @Parameter(description = "ID of the configuration to retrieve") @PathVariable UUID id) { - return ResponseEntity.of(spreadsheetConfigService.getSpreadsheetConfig(id)); + return ResponseEntity.ok(spreadsheetConfigService.getSpreadsheetConfig(id)); + } + + @GetMapping("/metadata") + @Operation(summary = "Get spreadsheet configurations metadata", + description = "Retrieves metadata of spreadsheet configurations by their IDs") + @ApiResponse(responseCode = "200", description = "Metadata found", + content = @Content(schema = @Schema(implementation = MetadataInfos.class))) + public ResponseEntity> getSpreadsheetConfigsMetadata(@RequestParam List ids) { + return ResponseEntity.ok(spreadsheetConfigService.getSpreadsheetConfigsMetadata(ids)); } @GetMapping @Operation(summary = "Get all spreadsheet configurations", description = "Retrieves all spreadsheet configurations") @ApiResponse(responseCode = "200", description = "List of configurations", - content = @Content(schema = @Schema(implementation = SpreadsheetConfigDto.class))) - public ResponseEntity> getAllSpreadsheetConfigs() { + content = @Content(schema = @Schema(implementation = SpreadsheetConfigInfos.class))) + public ResponseEntity> getAllSpreadsheetConfigs() { return ResponseEntity.ok(spreadsheetConfigService.getAllSpreadsheetConfigs()); } @@ -88,7 +97,7 @@ public ResponseEntity> getAllSpreadsheetConfigs() { @ApiResponse(responseCode = "404", description = "Configuration not found") public ResponseEntity updateSpreadsheetConfig( @Parameter(description = "ID of the configuration to update") @PathVariable UUID id, - @Valid @RequestBody SpreadsheetConfigDto dto) { + @Valid @RequestBody SpreadsheetConfigInfos dto) { spreadsheetConfigService.updateSpreadsheetConfig(id, dto); return ResponseEntity.noContent().build(); } diff --git a/src/main/java/org/gridsuite/spreadsheetconfig/server/dto/CustomColumnDto.java b/src/main/java/org/gridsuite/spreadsheetconfig/server/dto/CustomColumnInfos.java similarity index 68% rename from src/main/java/org/gridsuite/spreadsheetconfig/server/dto/CustomColumnDto.java rename to src/main/java/org/gridsuite/spreadsheetconfig/server/dto/CustomColumnInfos.java index 944361e..86f2ca0 100644 --- a/src/main/java/org/gridsuite/spreadsheetconfig/server/dto/CustomColumnDto.java +++ b/src/main/java/org/gridsuite/spreadsheetconfig/server/dto/CustomColumnInfos.java @@ -8,30 +8,17 @@ import io.swagger.v3.oas.annotations.media.Schema; import jakarta.validation.constraints.NotNull; -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; -import lombok.extern.jackson.Jacksonized; - -import java.util.UUID; /** * @author Achour BERRAHMA */ -@Data -@AllArgsConstructor -@Builder -@Jacksonized @Schema(name = "CustomColumnDto", description = "Custom column configuration") -public class CustomColumnDto { - - @Schema(description = "Custom column ID") - UUID id; +public record CustomColumnInfos( @NotNull(message = "Column name is mandatory") @Schema(description = "Column name") - String name; + String name, @Schema(description = "Column formula") - String formula; -} + String formula +) { } diff --git a/src/main/java/org/gridsuite/spreadsheetconfig/server/dto/MetadataInfos.java b/src/main/java/org/gridsuite/spreadsheetconfig/server/dto/MetadataInfos.java new file mode 100644 index 0000000..ee7e6c3 --- /dev/null +++ b/src/main/java/org/gridsuite/spreadsheetconfig/server/dto/MetadataInfos.java @@ -0,0 +1,26 @@ +/** + * Copyright (c) 2024, RTE (http://www.rte-france.com) + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ +package org.gridsuite.spreadsheetconfig.server.dto; + +import io.swagger.v3.oas.annotations.media.Schema; +import org.gridsuite.spreadsheetconfig.server.constants.SheetType; + +import java.util.UUID; + +/** + * @author Achour BERRAHMA + */ +@Schema(name = "MetadataDto", description = "Spreadsheet configuration metadata") +public record MetadataInfos( + + @Schema(description = "Spreadsheet configuration ID") + UUID id, + + @Schema(description = "Spreadsheet type") + SheetType sheetType + +) { } diff --git a/src/main/java/org/gridsuite/spreadsheetconfig/server/dto/SpreadsheetConfigDto.java b/src/main/java/org/gridsuite/spreadsheetconfig/server/dto/SpreadsheetConfigInfos.java similarity index 79% rename from src/main/java/org/gridsuite/spreadsheetconfig/server/dto/SpreadsheetConfigDto.java rename to src/main/java/org/gridsuite/spreadsheetconfig/server/dto/SpreadsheetConfigInfos.java index caee7cf..2712407 100644 --- a/src/main/java/org/gridsuite/spreadsheetconfig/server/dto/SpreadsheetConfigDto.java +++ b/src/main/java/org/gridsuite/spreadsheetconfig/server/dto/SpreadsheetConfigInfos.java @@ -8,9 +8,6 @@ import io.swagger.v3.oas.annotations.media.Schema; import jakarta.validation.constraints.NotNull; -import lombok.Builder; -import lombok.Value; -import lombok.extern.jackson.Jacksonized; import org.gridsuite.spreadsheetconfig.server.constants.SheetType; import java.util.List; @@ -19,19 +16,16 @@ /** * @author Achour BERRAHMA */ -@Value -@Builder -@Jacksonized @Schema(name = "SpreadsheetConfigDto", description = "Spreadsheet configuration") -public class SpreadsheetConfigDto { +public record SpreadsheetConfigInfos( @Schema(description = "Spreadsheet configuration ID") - UUID id; + UUID id, @NotNull(message = "Sheet type is mandatory") @Schema(description = "Spreadsheet type") - SheetType sheetType; + SheetType sheetType, @Schema(description = "Custom columns") - List customColumns; -} + List customColumns +) { } diff --git a/src/main/java/org/gridsuite/spreadsheetconfig/server/entities/CustomColumnEntity.java b/src/main/java/org/gridsuite/spreadsheetconfig/server/entities/CustomColumnEmbeddable.java similarity index 55% rename from src/main/java/org/gridsuite/spreadsheetconfig/server/entities/CustomColumnEntity.java rename to src/main/java/org/gridsuite/spreadsheetconfig/server/entities/CustomColumnEmbeddable.java index 8d944b8..dca6d28 100644 --- a/src/main/java/org/gridsuite/spreadsheetconfig/server/entities/CustomColumnEntity.java +++ b/src/main/java/org/gridsuite/spreadsheetconfig/server/entities/CustomColumnEmbeddable.java @@ -9,32 +9,21 @@ import jakarta.persistence.*; import lombok.*; -import java.util.UUID; - /** * @author Achour BERRAHMA */ -@Entity -@Table(name = "spreadsheet_custom_column") +@Embeddable @Getter @Setter @NoArgsConstructor @AllArgsConstructor @Builder -public class CustomColumnEntity { - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name = "id") - private UUID id; +public class CustomColumnEmbeddable { @Column(name = "name", nullable = false, columnDefinition = "varchar(255)") private String name; - @Column(name = "formula", columnDefinition = "varchar(255)") + @Column(name = "formula", columnDefinition = "CLOB") private String formula; - @ManyToOne(fetch = FetchType.LAZY) - @JoinColumn(name = "spreadsheet_config_id", nullable = false, foreignKey = @ForeignKey(name = "spreadsheet_config_id_fk_constraint")) - private SpreadsheetConfigEntity spreadsheetConfig; } diff --git a/src/main/java/org/gridsuite/spreadsheetconfig/server/entities/SpreadsheetConfigEntity.java b/src/main/java/org/gridsuite/spreadsheetconfig/server/entities/SpreadsheetConfigEntity.java index ee07fc6..882a09b 100644 --- a/src/main/java/org/gridsuite/spreadsheetconfig/server/entities/SpreadsheetConfigEntity.java +++ b/src/main/java/org/gridsuite/spreadsheetconfig/server/entities/SpreadsheetConfigEntity.java @@ -35,8 +35,12 @@ public class SpreadsheetConfigEntity { @Enumerated(EnumType.STRING) private SheetType sheetType; - @OneToMany(mappedBy = "spreadsheetConfig", cascade = CascadeType.ALL, orphanRemoval = true) + @ElementCollection + @CollectionTable( + name = "spreadsheet_custom_column", + joinColumns = @JoinColumn(name = "spreadsheet_config_id") + ) @Builder.Default - private List customColumns = new ArrayList<>(); + private List customColumns = new ArrayList<>(); } diff --git a/src/main/java/org/gridsuite/spreadsheetconfig/server/mapper/SpreadsheetConfigMapper.java b/src/main/java/org/gridsuite/spreadsheetconfig/server/mapper/SpreadsheetConfigMapper.java index 05f6007..6544d3c 100644 --- a/src/main/java/org/gridsuite/spreadsheetconfig/server/mapper/SpreadsheetConfigMapper.java +++ b/src/main/java/org/gridsuite/spreadsheetconfig/server/mapper/SpreadsheetConfigMapper.java @@ -6,57 +6,54 @@ */ package org.gridsuite.spreadsheetconfig.server.mapper; -import org.gridsuite.spreadsheetconfig.server.dto.SpreadsheetConfigDto; -import org.gridsuite.spreadsheetconfig.server.dto.CustomColumnDto; +import org.gridsuite.spreadsheetconfig.server.dto.MetadataInfos; +import org.gridsuite.spreadsheetconfig.server.dto.SpreadsheetConfigInfos; +import org.gridsuite.spreadsheetconfig.server.dto.CustomColumnInfos; +import org.gridsuite.spreadsheetconfig.server.entities.CustomColumnEmbeddable; import org.gridsuite.spreadsheetconfig.server.entities.SpreadsheetConfigEntity; -import org.gridsuite.spreadsheetconfig.server.entities.CustomColumnEntity; -import org.springframework.stereotype.Component; /** * @author Achour BERRAHMA */ -@Component -public class SpreadsheetConfigMapper { - - public SpreadsheetConfigDto toDto(SpreadsheetConfigEntity entity) { - return SpreadsheetConfigDto.builder() - .id(entity.getId()) - .sheetType(entity.getSheetType()) - .customColumns(entity.getCustomColumns().stream() - .map(this::toCustomColumnDto) - .toList()) - .build(); +public final class SpreadsheetConfigMapper { + + private SpreadsheetConfigMapper() { + } + + public static SpreadsheetConfigInfos toDto(SpreadsheetConfigEntity entity) { + return new SpreadsheetConfigInfos( + entity.getId(), + entity.getSheetType(), + entity.getCustomColumns().stream() + .map(SpreadsheetConfigMapper::toCustomColumnDto) + .toList() + ); } - public SpreadsheetConfigEntity toEntity(SpreadsheetConfigDto dto) { + public static MetadataInfos toMetadataDto(SpreadsheetConfigEntity entity) { + return new MetadataInfos(entity.getId(), entity.getSheetType()); + } + + public static SpreadsheetConfigEntity toEntity(SpreadsheetConfigInfos dto) { SpreadsheetConfigEntity entity = SpreadsheetConfigEntity.builder() - .id(dto.getId()) - .sheetType(dto.getSheetType()) + .id(dto.id()) + .sheetType(dto.sheetType()) .build(); - if (dto.getCustomColumns() != null) { - entity.setCustomColumns(dto.getCustomColumns().stream() - .map(columnDto -> toCustomColumnEntity(columnDto, entity)) + if (dto.customColumns() != null) { + entity.setCustomColumns(dto.customColumns().stream() + .map(SpreadsheetConfigMapper::toCustomColumnEmbeddable) .toList()); } return entity; } - public CustomColumnDto toCustomColumnDto(CustomColumnEntity entity) { - return CustomColumnDto.builder() - .id(entity.getId()) - .name(entity.getName()) - .formula(entity.getFormula()) - .build(); + public static CustomColumnInfos toCustomColumnDto(CustomColumnEmbeddable entity) { + return new CustomColumnInfos(entity.getName(), entity.getFormula()); } - public CustomColumnEntity toCustomColumnEntity(CustomColumnDto dto, SpreadsheetConfigEntity spreadsheetConfig) { - return CustomColumnEntity.builder() - .id(dto.getId()) - .name(dto.getName()) - .formula(dto.getFormula()) - .spreadsheetConfig(spreadsheetConfig) - .build(); + public static CustomColumnEmbeddable toCustomColumnEmbeddable(CustomColumnInfos dto) { + return new CustomColumnEmbeddable(dto.name(), dto.formula()); } } diff --git a/src/main/java/org/gridsuite/spreadsheetconfig/server/repositories/CustomColumnRepository.java b/src/main/java/org/gridsuite/spreadsheetconfig/server/repositories/CustomColumnRepository.java deleted file mode 100644 index caf27b4..0000000 --- a/src/main/java/org/gridsuite/spreadsheetconfig/server/repositories/CustomColumnRepository.java +++ /dev/null @@ -1,20 +0,0 @@ -/** - * Copyright (c) 2024, RTE (http://www.rte-france.com) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - */ -package org.gridsuite.spreadsheetconfig.server.repositories; - -import org.gridsuite.spreadsheetconfig.server.entities.CustomColumnEntity; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; - -import java.util.UUID; - -/** - * @author Achour BERRAHMA - */ -@Repository -public interface CustomColumnRepository extends JpaRepository { -} diff --git a/src/main/java/org/gridsuite/spreadsheetconfig/server/service/SpreadsheetConfigService.java b/src/main/java/org/gridsuite/spreadsheetconfig/server/service/SpreadsheetConfigService.java index 3dcbfcb..56803c8 100644 --- a/src/main/java/org/gridsuite/spreadsheetconfig/server/service/SpreadsheetConfigService.java +++ b/src/main/java/org/gridsuite/spreadsheetconfig/server/service/SpreadsheetConfigService.java @@ -8,8 +8,9 @@ import jakarta.persistence.EntityNotFoundException; import lombok.RequiredArgsConstructor; -import org.gridsuite.spreadsheetconfig.server.dto.SpreadsheetConfigDto; -import org.gridsuite.spreadsheetconfig.server.entities.CustomColumnEntity; +import org.gridsuite.spreadsheetconfig.server.dto.MetadataInfos; +import org.gridsuite.spreadsheetconfig.server.dto.SpreadsheetConfigInfos; +import org.gridsuite.spreadsheetconfig.server.entities.CustomColumnEmbeddable; import org.gridsuite.spreadsheetconfig.server.entities.SpreadsheetConfigEntity; import org.gridsuite.spreadsheetconfig.server.mapper.SpreadsheetConfigMapper; import org.gridsuite.spreadsheetconfig.server.repositories.SpreadsheetConfigRepository; @@ -17,7 +18,7 @@ import org.springframework.transaction.annotation.Transactional; import java.util.List; -import java.util.Optional; +import java.util.Objects; import java.util.UUID; /** @@ -29,60 +30,67 @@ public class SpreadsheetConfigService { private final SpreadsheetConfigRepository spreadsheetConfigRepository; - private final SpreadsheetConfigMapper spreadsheetConfigMapper; - @Transactional - public UUID createSpreadsheetConfig(SpreadsheetConfigDto dto) { - SpreadsheetConfigEntity entity = spreadsheetConfigMapper.toEntity(dto); + public UUID createSpreadsheetConfig(SpreadsheetConfigInfos dto) { + SpreadsheetConfigEntity entity = SpreadsheetConfigMapper.toEntity(dto); return spreadsheetConfigRepository.save(entity).getId(); } @Transactional - public Optional duplicateSpreadsheetConfig(UUID id) { - return spreadsheetConfigRepository.findById(id) - .map(entity -> { - SpreadsheetConfigEntity duplicate = SpreadsheetConfigEntity.builder() - .sheetType(entity.getSheetType()) - .build(); - - List customColumns = entity.getCustomColumns().stream() - .map(column -> CustomColumnEntity.builder() - .name(column.getName()) - .formula(column.getFormula()) - .spreadsheetConfig(duplicate) - .build()) - .toList(); - - duplicate.setCustomColumns(customColumns); - - return spreadsheetConfigRepository.save(duplicate).getId(); - }); + public UUID duplicateSpreadsheetConfig(UUID id) { + SpreadsheetConfigEntity entity = spreadsheetConfigRepository.findById(id) + .orElseThrow(() -> new EntityNotFoundException("SpreadsheetConfig not found with id: " + id)); + + SpreadsheetConfigEntity duplicate = SpreadsheetConfigEntity.builder() + .sheetType(entity.getSheetType()) + .build(); + + List customColumns = entity.getCustomColumns().stream() + .map(column -> CustomColumnEmbeddable.builder() + .name(column.getName()) + .formula(column.getFormula()) + .build()) + .toList(); + + duplicate.setCustomColumns(customColumns); + + return spreadsheetConfigRepository.save(duplicate).getId(); } @Transactional(readOnly = true) - public Optional getSpreadsheetConfig(UUID id) { + public SpreadsheetConfigInfos getSpreadsheetConfig(UUID id) { return spreadsheetConfigRepository.findById(id) - .map(spreadsheetConfigMapper::toDto); + .map(SpreadsheetConfigMapper::toDto) + .orElseThrow(() -> new EntityNotFoundException("SpreadsheetConfig not found with id: " + id)); } @Transactional(readOnly = true) - public List getAllSpreadsheetConfigs() { + public List getAllSpreadsheetConfigs() { return spreadsheetConfigRepository.findAll() .stream() - .map(spreadsheetConfigMapper::toDto) + .map(SpreadsheetConfigMapper::toDto) + .toList(); + } + + @Transactional(readOnly = true) + public List getSpreadsheetConfigsMetadata(List ids) { + Objects.requireNonNull(ids); + return spreadsheetConfigRepository.findAllById(ids) + .stream() + .map(SpreadsheetConfigMapper::toMetadataDto) .toList(); } @Transactional - public void updateSpreadsheetConfig(UUID id, SpreadsheetConfigDto dto) { + public void updateSpreadsheetConfig(UUID id, SpreadsheetConfigInfos dto) { SpreadsheetConfigEntity entity = spreadsheetConfigRepository.findById(id) .orElseThrow(() -> new EntityNotFoundException("SpreadsheetConfig not found with id: " + id)); - entity.setSheetType(dto.getSheetType()); + entity.setSheetType(dto.sheetType()); entity.getCustomColumns().clear(); - if (dto.getCustomColumns() != null) { - entity.getCustomColumns().addAll(dto.getCustomColumns().stream() - .map(columnDto -> spreadsheetConfigMapper.toCustomColumnEntity(columnDto, entity)) + if (dto.customColumns() != null) { + entity.getCustomColumns().addAll(dto.customColumns().stream() + .map(SpreadsheetConfigMapper::toCustomColumnEmbeddable) .toList()); } } diff --git a/src/main/resources/db/changelog/changesets/create-spreadsheet-config-table.xml b/src/main/resources/db/changelog/changesets/create-spreadsheet-config-table.xml index 4a6ec14..74586d7 100644 --- a/src/main/resources/db/changelog/changesets/create-spreadsheet-config-table.xml +++ b/src/main/resources/db/changelog/changesets/create-spreadsheet-config-table.xml @@ -13,19 +13,22 @@ - - - - - - - + + + + + + + + diff --git a/src/test/java/org/gridsuite/spreadsheetconfig/server/DtoConverterTest.java b/src/test/java/org/gridsuite/spreadsheetconfig/server/DtoConverterTest.java index a0239b3..d68c619 100644 --- a/src/test/java/org/gridsuite/spreadsheetconfig/server/DtoConverterTest.java +++ b/src/test/java/org/gridsuite/spreadsheetconfig/server/DtoConverterTest.java @@ -8,9 +8,9 @@ import org.assertj.core.api.WithAssertions; import org.gridsuite.spreadsheetconfig.server.constants.SheetType; -import org.gridsuite.spreadsheetconfig.server.dto.CustomColumnDto; -import org.gridsuite.spreadsheetconfig.server.dto.SpreadsheetConfigDto; -import org.gridsuite.spreadsheetconfig.server.entities.CustomColumnEntity; +import org.gridsuite.spreadsheetconfig.server.dto.CustomColumnInfos; +import org.gridsuite.spreadsheetconfig.server.dto.SpreadsheetConfigInfos; +import org.gridsuite.spreadsheetconfig.server.entities.CustomColumnEmbeddable; import org.gridsuite.spreadsheetconfig.server.entities.SpreadsheetConfigEntity; import org.gridsuite.spreadsheetconfig.server.mapper.SpreadsheetConfigMapper; import org.junit.jupiter.api.Nested; @@ -24,8 +24,6 @@ */ public class DtoConverterTest implements WithAssertions { - private final SpreadsheetConfigMapper mapper = new SpreadsheetConfigMapper(); - @Nested class SpreadsheetConfigConverterTest { @@ -36,39 +34,39 @@ void testConversionToDtoOfSpreadsheetConfig() { .id(id) .sheetType(SheetType.BATTERIES) .customColumns(Arrays.asList( - CustomColumnEntity.builder().id(UUID.randomUUID()).name("Column1").formula("A+B").build(), - CustomColumnEntity.builder().id(UUID.randomUUID()).name("Column2").formula("C*D").build() + CustomColumnEmbeddable.builder().name("Column1").formula("A+B").build(), + CustomColumnEmbeddable.builder().name("Column2").formula("C*D").build() )) .build(); - SpreadsheetConfigDto dto = mapper.toDto(entity); + SpreadsheetConfigInfos dto = SpreadsheetConfigMapper.toDto(entity); assertThat(dto) .as("DTO conversion result") .satisfies(d -> { - assertThat(d.getId()).isEqualTo(id); - assertThat(d.getSheetType()).isEqualTo(SheetType.BATTERIES); - assertThat(d.getCustomColumns()).hasSize(2); - assertThat(d.getCustomColumns().get(0).getName()).isEqualTo("Column1"); - assertThat(d.getCustomColumns().get(0).getFormula()).isEqualTo("A+B"); - assertThat(d.getCustomColumns().get(1).getName()).isEqualTo("Column2"); - assertThat(d.getCustomColumns().get(1).getFormula()).isEqualTo("C*D"); + assertThat(d.id()).isEqualTo(id); + assertThat(d.sheetType()).isEqualTo(SheetType.BATTERIES); + assertThat(d.customColumns()).hasSize(2); + assertThat(d.customColumns().get(0).name()).isEqualTo("Column1"); + assertThat(d.customColumns().get(0).formula()).isEqualTo("A+B"); + assertThat(d.customColumns().get(1).name()).isEqualTo("Column2"); + assertThat(d.customColumns().get(1).formula()).isEqualTo("C*D"); }); } @Test void testConversionToEntityOfSpreadsheetConfig() { UUID id = UUID.randomUUID(); - SpreadsheetConfigDto dto = SpreadsheetConfigDto.builder() - .id(id) - .sheetType(SheetType.BUSES) - .customColumns(Arrays.asList( - CustomColumnDto.builder().id(UUID.randomUUID()).name("Column1").formula("X+Y").build(), - CustomColumnDto.builder().id(UUID.randomUUID()).name("Column2").formula("Z*W").build() - )) - .build(); + SpreadsheetConfigInfos dto = new SpreadsheetConfigInfos( + id, + SheetType.BUSES, + Arrays.asList( + new CustomColumnInfos("Column1", "X+Y"), + new CustomColumnInfos("Column2", "Z*W") + ) + ); - SpreadsheetConfigEntity entity = mapper.toEntity(dto); + SpreadsheetConfigEntity entity = SpreadsheetConfigMapper.toEntity(dto); assertThat(entity) .as("Entity conversion result") @@ -88,43 +86,32 @@ void testConversionToEntityOfSpreadsheetConfig() { class CustomColumnConverterTest { @Test void testConversionToDtoOfCustomColumn() { - UUID id = UUID.randomUUID(); - CustomColumnEntity entity = CustomColumnEntity.builder() - .id(id) + CustomColumnEmbeddable entity = CustomColumnEmbeddable.builder() .name("TestColumn") .formula("A+B+C") .build(); - CustomColumnDto dto = mapper.toCustomColumnDto(entity); + CustomColumnInfos dto = SpreadsheetConfigMapper.toCustomColumnDto(entity); assertThat(dto) .as("DTO conversion result") .satisfies(d -> { - assertThat(d.getId()).isEqualTo(id); - assertThat(d.getName()).isEqualTo("TestColumn"); - assertThat(d.getFormula()).isEqualTo("A+B+C"); + assertThat(d.name()).isEqualTo("TestColumn"); + assertThat(d.formula()).isEqualTo("A+B+C"); }); } @Test - void testConversionToEntityOfCustomColumn() { - UUID id = UUID.randomUUID(); - CustomColumnDto dto = CustomColumnDto.builder() - .id(id) - .name("TestColumn") - .formula("X*Y*Z") - .build(); + void testConversionToEmbeddableOfCustomColumn() { + CustomColumnInfos dto = new CustomColumnInfos("TestColumn", "X*Y*Z"); - SpreadsheetConfigEntity spreadsheetConfig = new SpreadsheetConfigEntity(); - CustomColumnEntity entity = mapper.toCustomColumnEntity(dto, spreadsheetConfig); + CustomColumnEmbeddable customColumnEmbeddable = SpreadsheetConfigMapper.toCustomColumnEmbeddable(dto); - assertThat(entity) + assertThat(customColumnEmbeddable) .as("Entity conversion result") .satisfies(e -> { - assertThat(e.getId()).isEqualTo(id); assertThat(e.getName()).isEqualTo("TestColumn"); assertThat(e.getFormula()).isEqualTo("X*Y*Z"); - assertThat(e.getSpreadsheetConfig()).isEqualTo(spreadsheetConfig); }); } } diff --git a/src/test/java/org/gridsuite/spreadsheetconfig/server/SpreadsheetConfigControllerTest.java b/src/test/java/org/gridsuite/spreadsheetconfig/server/SpreadsheetConfigControllerTest.java index 6f39d9b..5179c49 100644 --- a/src/test/java/org/gridsuite/spreadsheetconfig/server/SpreadsheetConfigControllerTest.java +++ b/src/test/java/org/gridsuite/spreadsheetconfig/server/SpreadsheetConfigControllerTest.java @@ -9,8 +9,9 @@ import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import org.gridsuite.spreadsheetconfig.server.constants.SheetType; -import org.gridsuite.spreadsheetconfig.server.dto.CustomColumnDto; -import org.gridsuite.spreadsheetconfig.server.dto.SpreadsheetConfigDto; +import org.gridsuite.spreadsheetconfig.server.dto.CustomColumnInfos; +import org.gridsuite.spreadsheetconfig.server.dto.MetadataInfos; +import org.gridsuite.spreadsheetconfig.server.dto.SpreadsheetConfigInfos; import org.gridsuite.spreadsheetconfig.server.repositories.SpreadsheetConfigRepository; import org.gridsuite.spreadsheetconfig.server.service.SpreadsheetConfigService; import org.junit.jupiter.api.AfterEach; @@ -59,28 +60,21 @@ public void tearDown() { @Test void testCreate() throws Exception { - SpreadsheetConfigDto configToCreate = SpreadsheetConfigDto.builder() - .sheetType(SheetType.BATTERIES) - .customColumns(createCustomColumns()) - .build(); + SpreadsheetConfigInfos configToCreate = new SpreadsheetConfigInfos(null, SheetType.BATTERIES, createCustomColumns()); UUID configUuid = postSpreadsheetConfig(configToCreate); - SpreadsheetConfigDto createdConfig = getSpreadsheetConfig(configUuid); + SpreadsheetConfigInfos createdConfig = getSpreadsheetConfig(configUuid); assertThat(createdConfig) .usingRecursiveComparison() .ignoringFields("id", "customColumns.id") .isEqualTo(configToCreate); - assertThat(createdConfig.getId()).isNotNull(); - assertThat(createdConfig.getCustomColumns()).allMatch(column -> column.getId() != null); + assertThat(createdConfig.id()).isNotNull(); } @Test void testCreateWithInvalidData() throws Exception { - SpreadsheetConfigDto invalidConfig = SpreadsheetConfigDto.builder() - .sheetType(null) // SheetType is required - .customColumns(createCustomColumns()) - .build(); + SpreadsheetConfigInfos invalidConfig = new SpreadsheetConfigInfos(null, null, createCustomColumns()); String invalidConfigJson = mapper.writeValueAsString(invalidConfig); @@ -92,21 +86,38 @@ void testCreateWithInvalidData() throws Exception { @Test void testRead() throws Exception { - SpreadsheetConfigDto configToRead = SpreadsheetConfigDto.builder() - .sheetType(SheetType.BUSES) - .customColumns(createCustomColumns()) - .build(); + SpreadsheetConfigInfos configToRead = new SpreadsheetConfigInfos(null, SheetType.BUSES, createCustomColumns()); UUID configUuid = saveAndReturnId(configToRead); - SpreadsheetConfigDto receivedConfig = getSpreadsheetConfig(configUuid); + SpreadsheetConfigInfos receivedConfig = getSpreadsheetConfig(configUuid); assertThat(receivedConfig) .usingRecursiveComparison() .ignoringFields("id", "customColumns.id") .isEqualTo(configToRead); - assertThat(receivedConfig.getId()).isEqualTo(configUuid); - assertThat(receivedConfig.getCustomColumns()).allMatch(column -> column.getId() != null); + assertThat(receivedConfig.id()).isEqualTo(configUuid); + } + + @Test + void testGetMetadata() throws Exception { + SpreadsheetConfigInfos configToRead = new SpreadsheetConfigInfos(null, SheetType.BUSES, createCustomColumns()); + + UUID configUuid = saveAndReturnId(configToRead); + + MvcResult receivedMetadata = mockMvc.perform(get(URI_SPREADSHEET_CONFIG_BASE + "/metadata") + .queryParam("ids", configUuid.toString())) + .andExpect(status().isOk()) + .andReturn(); + + List metadata = mapper.readValue( + receivedMetadata.getResponse().getContentAsString(), + new TypeReference>() { }); + + assertThat(metadata).hasSize(1); + assertThat(metadata.get(0).id()).isEqualTo(configUuid); + assertThat(metadata.get(0).sheetType()).isEqualTo(SheetType.BUSES); + } @Test @@ -119,18 +130,11 @@ void testReadNonExistent() throws Exception { @Test void testUpdateWithInvalidData() throws Exception { - SpreadsheetConfigDto configToUpdate = SpreadsheetConfigDto.builder() - .sheetType(SheetType.BATTERIES) - .customColumns(createCustomColumns()) - .build(); + SpreadsheetConfigInfos configToUpdate = new SpreadsheetConfigInfos(null, SheetType.BATTERIES, createCustomColumns()); UUID configUuid = saveAndReturnId(configToUpdate); - SpreadsheetConfigDto invalidUpdate = SpreadsheetConfigDto.builder() - .id(configUuid) - .sheetType(null) // SheetType is required - .customColumns(createUpdatedCustomColumns()) - .build(); + SpreadsheetConfigInfos invalidUpdate = new SpreadsheetConfigInfos(configUuid, null, createUpdatedCustomColumns()); String invalidUpdateJson = mapper.writeValueAsString(invalidUpdate); @@ -142,18 +146,11 @@ void testUpdateWithInvalidData() throws Exception { @Test void testUpdate() throws Exception { - SpreadsheetConfigDto configToUpdate = SpreadsheetConfigDto.builder() - .sheetType(SheetType.BATTERIES) - .customColumns(createCustomColumns()) - .build(); + SpreadsheetConfigInfos configToUpdate = new SpreadsheetConfigInfos(null, SheetType.BATTERIES, createCustomColumns()); UUID configUuid = saveAndReturnId(configToUpdate); - SpreadsheetConfigDto updatedConfig = SpreadsheetConfigDto.builder() - .id(configUuid) - .sheetType(SheetType.BUSES) - .customColumns(createUpdatedCustomColumns()) - .build(); + SpreadsheetConfigInfos updatedConfig = new SpreadsheetConfigInfos(configUuid, SheetType.BUSES, createUpdatedCustomColumns()); String updatedConfigJson = mapper.writeValueAsString(updatedConfig); @@ -162,7 +159,7 @@ void testUpdate() throws Exception { .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isNoContent()); - SpreadsheetConfigDto retrievedConfig = getSpreadsheetConfig(configUuid); + SpreadsheetConfigInfos retrievedConfig = getSpreadsheetConfig(configUuid); assertThat(retrievedConfig) .usingRecursiveComparison() @@ -172,17 +169,14 @@ void testUpdate() throws Exception { @Test void testDelete() throws Exception { - SpreadsheetConfigDto configToDelete = SpreadsheetConfigDto.builder() - .sheetType(SheetType.BATTERIES) - .customColumns(createCustomColumns()) - .build(); + SpreadsheetConfigInfos configToDelete = new SpreadsheetConfigInfos(null, SheetType.BATTERIES, createCustomColumns()); UUID configUuid = saveAndReturnId(configToDelete); mockMvc.perform(delete(URI_SPREADSHEET_CONFIG_GET_PUT + configUuid)) .andExpect(status().isNoContent()); - List storedConfigs = getAllSpreadsheetConfigs(); + List storedConfigs = getAllSpreadsheetConfigs(); assertThat(storedConfigs).isEmpty(); } @@ -197,29 +191,20 @@ void testDeleteNonExistent() throws Exception { @Test void testGetAll() throws Exception { - SpreadsheetConfigDto config1 = SpreadsheetConfigDto.builder() - .sheetType(SheetType.BATTERIES) - .customColumns(createCustomColumns()) - .build(); - SpreadsheetConfigDto config2 = SpreadsheetConfigDto.builder() - .sheetType(SheetType.BUSES) - .customColumns(createUpdatedCustomColumns()) - .build(); + SpreadsheetConfigInfos config1 = new SpreadsheetConfigInfos(null, SheetType.BATTERIES, createCustomColumns()); + SpreadsheetConfigInfos config2 = new SpreadsheetConfigInfos(null, SheetType.BUSES, createUpdatedCustomColumns()); saveAndReturnId(config1); saveAndReturnId(config2); - List receivedConfigs = getAllSpreadsheetConfigs(); + List receivedConfigs = getAllSpreadsheetConfigs(); assertThat(receivedConfigs).hasSize(2); } @Test void testDuplicate() throws Exception { - SpreadsheetConfigDto configToCreate = SpreadsheetConfigDto.builder() - .sheetType(SheetType.BATTERIES) - .customColumns(createCustomColumns()) - .build(); + SpreadsheetConfigInfos configToCreate = new SpreadsheetConfigInfos(null, SheetType.BATTERIES, createCustomColumns()); UUID configUuid = postSpreadsheetConfig(configToCreate); mockMvc.perform(post(URI_SPREADSHEET_CONFIG_BASE + "/duplicate") @@ -228,12 +213,12 @@ void testDuplicate() throws Exception { UUID duplicatedConfigUuid = duplicateSpreadsheetConfig(configUuid); - SpreadsheetConfigDto duplicatedConfig = getSpreadsheetConfig(duplicatedConfigUuid); + SpreadsheetConfigInfos duplicatedConfig = getSpreadsheetConfig(duplicatedConfigUuid); assertThat(duplicatedConfig) .usingRecursiveComparison() .ignoringFields("id", "customColumns.id") .isEqualTo(configToCreate); - assertThat(duplicatedConfig.getId()).isNotEqualTo(configUuid); + assertThat(duplicatedConfig.id()).isNotEqualTo(configUuid); } @Test @@ -245,34 +230,34 @@ void testDuplicateNonExistent() throws Exception { .andExpect(status().isNotFound()); } - private List createCustomColumns() { + private List createCustomColumns() { return Arrays.asList( - new CustomColumnDto(null, "cust_a", "cust_b + cust_c"), - new CustomColumnDto(null, "cust_b", "var_minP + 1"), - new CustomColumnDto(null, "cust_c", "cust_b + 1"), - new CustomColumnDto(null, "cust_d", "5 + 2") + new CustomColumnInfos("cust_a", "cust_b + cust_c"), + new CustomColumnInfos( "cust_b", "var_minP + 1"), + new CustomColumnInfos("cust_c", "cust_b + 1"), + new CustomColumnInfos("cust_d", "5 + 2") ); } - private List createUpdatedCustomColumns() { + private List createUpdatedCustomColumns() { return Arrays.asList( - new CustomColumnDto(null, "cust_x", "cust_y * 2"), - new CustomColumnDto(null, "cust_y", "var_maxP - 1"), - new CustomColumnDto(null, "cust_z", "cust_x / 2") + new CustomColumnInfos("cust_x", "cust_y * 2"), + new CustomColumnInfos("cust_y", "var_maxP - 1"), + new CustomColumnInfos("cust_z", "cust_x / 2") ); } - private SpreadsheetConfigDto getSpreadsheetConfig(UUID configUuid) throws Exception { + private SpreadsheetConfigInfos getSpreadsheetConfig(UUID configUuid) throws Exception { MvcResult mvcGetResult = mockMvc.perform(get(URI_SPREADSHEET_CONFIG_GET_PUT + configUuid)) .andExpect(status().isOk()) .andReturn(); return mapper.readValue( mvcGetResult.getResponse().getContentAsString(), - SpreadsheetConfigDto.class); + SpreadsheetConfigInfos.class); } - private UUID postSpreadsheetConfig(SpreadsheetConfigDto configToCreate) throws Exception { + private UUID postSpreadsheetConfig(SpreadsheetConfigInfos configToCreate) throws Exception { String configToCreateJson = mapper.writeValueAsString(configToCreate); MvcResult mvcPostResult = mockMvc.perform(post(URI_SPREADSHEET_CONFIG_BASE) @@ -293,17 +278,17 @@ private UUID duplicateSpreadsheetConfig(UUID configUuid) throws Exception { return mapper.readValue(mvcPostResult.getResponse().getContentAsString(), UUID.class); } - private List getAllSpreadsheetConfigs() throws Exception { + private List getAllSpreadsheetConfigs() throws Exception { MvcResult mvcResult = mockMvc.perform(get(URI_SPREADSHEET_CONFIG_BASE)) .andExpect(status().isOk()) .andReturn(); return mapper.readValue( mvcResult.getResponse().getContentAsString(), - new TypeReference>() { }); + new TypeReference>() { }); } - private UUID saveAndReturnId(SpreadsheetConfigDto config) { + private UUID saveAndReturnId(SpreadsheetConfigInfos config) { return spreadsheetConfigService.createSpreadsheetConfig(config); } } diff --git a/src/test/resources/logback-test.xml b/src/test/resources/logback-test.xml index c531f97..b65a9a0 100644 --- a/src/test/resources/logback-test.xml +++ b/src/test/resources/logback-test.xml @@ -37,6 +37,6 @@ - + From 1d1a758bce8683fcb6bd9ff03129336110aa1d66 Mon Sep 17 00:00:00 2001 From: achour94 Date: Mon, 30 Sep 2024 15:07:53 +0200 Subject: [PATCH 7/9] fix style Signed-off-by: achour94 --- .../server/SpreadsheetConfigControllerTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/org/gridsuite/spreadsheetconfig/server/SpreadsheetConfigControllerTest.java b/src/test/java/org/gridsuite/spreadsheetconfig/server/SpreadsheetConfigControllerTest.java index 5179c49..68158cd 100644 --- a/src/test/java/org/gridsuite/spreadsheetconfig/server/SpreadsheetConfigControllerTest.java +++ b/src/test/java/org/gridsuite/spreadsheetconfig/server/SpreadsheetConfigControllerTest.java @@ -233,7 +233,7 @@ void testDuplicateNonExistent() throws Exception { private List createCustomColumns() { return Arrays.asList( new CustomColumnInfos("cust_a", "cust_b + cust_c"), - new CustomColumnInfos( "cust_b", "var_minP + 1"), + new CustomColumnInfos("cust_b", "var_minP + 1"), new CustomColumnInfos("cust_c", "cust_b + 1"), new CustomColumnInfos("cust_d", "5 + 2") ); From ff5c4e9d5c7a405835931541f2f0815e119345e4 Mon Sep 17 00:00:00 2001 From: achour94 Date: Mon, 30 Sep 2024 17:16:43 +0200 Subject: [PATCH 8/9] clean code Signed-off-by: achour94 --- .../service/SpreadsheetConfigService.java | 21 ++++++++++++------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/src/main/java/org/gridsuite/spreadsheetconfig/server/service/SpreadsheetConfigService.java b/src/main/java/org/gridsuite/spreadsheetconfig/server/service/SpreadsheetConfigService.java index 56803c8..e7369c6 100644 --- a/src/main/java/org/gridsuite/spreadsheetconfig/server/service/SpreadsheetConfigService.java +++ b/src/main/java/org/gridsuite/spreadsheetconfig/server/service/SpreadsheetConfigService.java @@ -38,8 +38,7 @@ public UUID createSpreadsheetConfig(SpreadsheetConfigInfos dto) { @Transactional public UUID duplicateSpreadsheetConfig(UUID id) { - SpreadsheetConfigEntity entity = spreadsheetConfigRepository.findById(id) - .orElseThrow(() -> new EntityNotFoundException("SpreadsheetConfig not found with id: " + id)); + SpreadsheetConfigEntity entity = findEntityById(id); SpreadsheetConfigEntity duplicate = SpreadsheetConfigEntity.builder() .sheetType(entity.getSheetType()) @@ -59,9 +58,7 @@ public UUID duplicateSpreadsheetConfig(UUID id) { @Transactional(readOnly = true) public SpreadsheetConfigInfos getSpreadsheetConfig(UUID id) { - return spreadsheetConfigRepository.findById(id) - .map(SpreadsheetConfigMapper::toDto) - .orElseThrow(() -> new EntityNotFoundException("SpreadsheetConfig not found with id: " + id)); + return SpreadsheetConfigMapper.toDto(findEntityById(id)); } @Transactional(readOnly = true) @@ -83,8 +80,7 @@ public List getSpreadsheetConfigsMetadata(List ids) { @Transactional public void updateSpreadsheetConfig(UUID id, SpreadsheetConfigInfos dto) { - SpreadsheetConfigEntity entity = spreadsheetConfigRepository.findById(id) - .orElseThrow(() -> new EntityNotFoundException("SpreadsheetConfig not found with id: " + id)); + SpreadsheetConfigEntity entity = findEntityById(id); entity.setSheetType(dto.sheetType()); entity.getCustomColumns().clear(); @@ -98,9 +94,18 @@ public void updateSpreadsheetConfig(UUID id, SpreadsheetConfigInfos dto) { @Transactional public void deleteSpreadsheetConfig(UUID id) { if (!spreadsheetConfigRepository.existsById(id)) { - throw new EntityNotFoundException("SpreadsheetConfig not found with id: " + id); + throw entityNotFoundException(id); } spreadsheetConfigRepository.deleteById(id); } + private SpreadsheetConfigEntity findEntityById(UUID id) { + return spreadsheetConfigRepository.findById(id) + .orElseThrow(() -> entityNotFoundException(id)); + } + + private EntityNotFoundException entityNotFoundException(UUID id) { + return new EntityNotFoundException("SpreadsheetConfig not found with id: " + id); + } + } From 35ef35ea9d7a31ec174651c0f759cfe4c8b1d215 Mon Sep 17 00:00:00 2001 From: achour94 Date: Tue, 1 Oct 2024 14:08:53 +0200 Subject: [PATCH 9/9] clean test Signed-off-by: achour94 --- ... => SpreadsheetConfigIntegrationTest.java} | 22 +++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) rename src/test/java/org/gridsuite/spreadsheetconfig/server/{SpreadsheetConfigControllerTest.java => SpreadsheetConfigIntegrationTest.java} (97%) diff --git a/src/test/java/org/gridsuite/spreadsheetconfig/server/SpreadsheetConfigControllerTest.java b/src/test/java/org/gridsuite/spreadsheetconfig/server/SpreadsheetConfigIntegrationTest.java similarity index 97% rename from src/test/java/org/gridsuite/spreadsheetconfig/server/SpreadsheetConfigControllerTest.java rename to src/test/java/org/gridsuite/spreadsheetconfig/server/SpreadsheetConfigIntegrationTest.java index 68158cd..fdf4e34 100644 --- a/src/test/java/org/gridsuite/spreadsheetconfig/server/SpreadsheetConfigControllerTest.java +++ b/src/test/java/org/gridsuite/spreadsheetconfig/server/SpreadsheetConfigIntegrationTest.java @@ -36,7 +36,7 @@ */ @SpringBootTest @AutoConfigureMockMvc -class SpreadsheetConfigControllerTest { +class SpreadsheetConfigIntegrationTest { private static final String URI_SPREADSHEET_CONFIG_BASE = "/v1/spreadsheet-configs"; private static final String URI_SPREADSHEET_CONFIG_GET_PUT = URI_SPREADSHEET_CONFIG_BASE + "/"; @@ -105,19 +105,23 @@ void testGetMetadata() throws Exception { UUID configUuid = saveAndReturnId(configToRead); + List metadata = getMetadataInfos(configUuid); + + assertThat(metadata).hasSize(1); + assertThat(metadata.get(0).id()).isEqualTo(configUuid); + assertThat(metadata.get(0).sheetType()).isEqualTo(SheetType.BUSES); + + } + + private List getMetadataInfos(UUID configUuid) throws Exception { MvcResult receivedMetadata = mockMvc.perform(get(URI_SPREADSHEET_CONFIG_BASE + "/metadata") .queryParam("ids", configUuid.toString())) .andExpect(status().isOk()) .andReturn(); - List metadata = mapper.readValue( + return mapper.readValue( receivedMetadata.getResponse().getContentAsString(), new TypeReference>() { }); - - assertThat(metadata).hasSize(1); - assertThat(metadata.get(0).id()).isEqualTo(configUuid); - assertThat(metadata.get(0).sheetType()).isEqualTo(SheetType.BUSES); - } @Test @@ -207,10 +211,6 @@ void testDuplicate() throws Exception { SpreadsheetConfigInfos configToCreate = new SpreadsheetConfigInfos(null, SheetType.BATTERIES, createCustomColumns()); UUID configUuid = postSpreadsheetConfig(configToCreate); - mockMvc.perform(post(URI_SPREADSHEET_CONFIG_BASE + "/duplicate") - .queryParam("duplicateFrom", UUID.randomUUID().toString())) - .andExpect(status().isNotFound()); - UUID duplicatedConfigUuid = duplicateSpreadsheetConfig(configUuid); SpreadsheetConfigInfos duplicatedConfig = getSpreadsheetConfig(duplicatedConfigUuid);