From 9a7b68d8f202471eae1c24263ed1039385228756 Mon Sep 17 00:00:00 2001 From: Sudharaka Palamakumbura Date: Wed, 14 Oct 2020 23:11:00 -0700 Subject: [PATCH] feat: add prettier-java to the project for formatting (#249) This adds prettier-java to the project for better formatting of java files. --- .lintstagedrc.js | 2 +- CODE_OF_CONDUCT.md | 20 +- CONTRIBUTING.md | 190 ++++++------ app.yaml | 42 ++- package.json | 3 +- postcss.config.js | 6 +- proxy.conf.json | 10 +- src/main/docker/app.yml | 28 +- src/main/docker/mailserver.yml | 10 +- src/main/docker/mysql.yml | 22 +- src/main/docker/sonar.yml | 10 +- .../github/jhipster/online/JhonlineApp.java | 47 +-- .../online/aop/logging/LoggingAspect.java | 17 +- .../online/config/ApplicationProperties.java | 4 +- .../online/config/AsyncConfiguration.java | 3 +- .../online/config/CacheConfiguration.java | 38 ++- .../config/CloudDatabaseConfiguration.java | 4 +- .../jhipster/online/config/Constants.java | 3 +- .../online/config/DatabaseConfiguration.java | 4 +- .../online/config/LiquibaseConfiguration.java | 25 +- .../online/config/LoggingConfiguration.java | 21 +- .../online/config/MDCConfiguration.java | 1 + .../online/config/SecurityConfiguration.java | 3 +- .../jhipster/online/config/WebConfigurer.java | 34 +-- .../config/audit/AuditEventConverter.java | 11 +- .../online/domain/AbstractAuditingEntity.java | 11 +- .../jhipster/online/domain/Authority.java | 13 +- .../jhipster/online/domain/EntityStats.java | 58 ++-- .../online/domain/GeneratorIdentity.java | 14 +- .../jhipster/online/domain/GitCompany.java | 34 ++- .../io/github/jhipster/online/domain/Jdl.java | 9 +- .../jhipster/online/domain/JdlMetadata.java | 16 +- .../online/domain/PersistentAuditEvent.java | 23 +- .../jhipster/online/domain/SubGenEvent.java | 48 ++- .../github/jhipster/online/domain/User.java | 86 ++++-- .../github/jhipster/online/domain/YoRC.java | 164 ++++++++--- .../domain/deserializer/YoRCDeserializer.java | 5 +- .../online/domain/enums/EntityStatColumn.java | 1 - .../online/domain/enums/GitProvider.java | 8 +- .../online/domain/enums/SubGenEventType.java | 8 +- .../domain/interfaces/CompleteDate.java | 2 - .../domain/interfaces/DatabaseColumn.java | 1 - .../online/mdc/logging/MDCInterceptor.java | 8 +- .../repository/AuthorityRepository.java | 3 +- .../CustomAuditEventRepository.java | 35 ++- .../repository/EntityStatsRepository.java | 1 - .../GeneratorIdentityRepository.java | 10 +- .../repository/GitCompanyRepository.java | 4 +- .../repository/JdlMetadataRepository.java | 4 +- .../online/repository/JdlRepository.java | 4 +- .../PersistenceAuditEventRepository.java | 6 +- .../repository/SubGenEventRepository.java | 1 - .../online/repository/UserRepository.java | 10 +- .../online/repository/YoRCRepository.java | 2 - .../online/security/AuthoritiesConstants.java | 3 +- .../security/DomainUserDetailsService.java | 22 +- .../online/security/SecurityUtils.java | 22 +- .../security/SpringSecurityAuditorAware.java | 3 +- .../online/security/jwt/JWTFilter.java | 11 +- .../online/security/jwt/TokenProvider.java | 40 ++- .../online/service/AuditEventService.java | 31 +- .../jhipster/online/service/CiCdService.java | 97 +++--- .../service/EmailAlreadyUsedException.java | 1 - .../online/service/EntityStatsService.java | 35 ++- .../service/GeneratorIdentityService.java | 15 +- .../online/service/GeneratorService.java | 34 ++- .../jhipster/online/service/GitService.java | 74 ++--- .../online/service/GithubService.java | 116 +++++--- .../online/service/GitlabService.java | 151 ++++++---- .../service/InvalidPasswordException.java | 1 - .../online/service/JHipsterService.java | 73 +++-- .../online/service/JdlMetadataService.java | 20 +- .../jhipster/online/service/JdlService.java | 137 ++++++--- .../jhipster/online/service/LogsService.java | 7 +- .../jhipster/online/service/MailService.java | 30 +- .../online/service/StatisticsService.java | 32 +- .../online/service/SubGenEventService.java | 63 ++-- .../jhipster/online/service/UserService.java | 276 ++++++++++-------- .../service/UsernameAlreadyUsedException.java | 1 - .../jhipster/online/service/YoRCService.java | 33 ++- .../online/service/dto/EntityStatsDTO.java | 50 +++- .../service/dto/GeneratorIdentityDTO.java | 9 +- .../service/dto/GitConfigurationDTO.java | 86 +++--- .../online/service/dto/JdlMetadataDTO.java | 24 +- .../online/service/dto/PasswordChangeDTO.java | 2 +- .../jhipster/online/service/dto/RawSQL.java | 8 +- .../online/service/dto/RawSQLField.java | 6 +- .../online/service/dto/SubGenEventDTO.java | 40 ++- .../online/service/dto/TemporalCountDTO.java | 9 +- .../jhipster/online/service/dto/UserDTO.java | 60 ++-- .../jhipster/online/service/dto/YoRCDTO.java | 145 ++++++--- .../online/service/enums/CiCdTool.java | 14 +- .../service/enums/TemporalValueType.java | 12 +- .../interfaces/GitProviderService.java | 16 +- .../online/service/mapper/EntityMapper.java | 5 +- .../service/mapper/EntityStatsMapper.java | 1 - .../mapper/GeneratorIdentityMapper.java | 1 - .../service/mapper/JdlMetadataMapper.java | 1 - .../service/mapper/SubGenEventMapper.java | 1 - .../online/service/mapper/UserMapper.java | 30 +- .../online/service/mapper/YoRCMapper.java | 1 - .../online/service/util/QueryUtil.java | 49 ++-- .../github/jhipster/online/util/DateUtil.java | 13 +- .../jhipster/online/util/SanitizeInputs.java | 12 +- .../online/web/rest/AccountResource.java | 40 +-- .../online/web/rest/AuditResource.java | 15 +- .../online/web/rest/CiCdResource.java | 37 ++- .../online/web/rest/EntityStatsResource.java | 20 +- .../web/rest/GeneratorIdentityResource.java | 24 +- .../online/web/rest/GeneratorResource.java | 41 ++- .../jhipster/online/web/rest/GitResource.java | 93 +++--- .../online/web/rest/JdlMetadataResource.java | 10 +- .../jhipster/online/web/rest/JdlResource.java | 67 +++-- .../online/web/rest/StatisticsResource.java | 46 +-- .../online/web/rest/SubGenEventResource.java | 20 +- .../online/web/rest/UserJWTController.java | 11 +- .../online/web/rest/UserResource.java | 33 ++- .../online/web/rest/YoRCResource.java | 20 +- .../rest/errors/BadRequestAlertException.java | 5 +- .../web/rest/errors/ErrorConstants.java | 3 +- .../web/rest/errors/ExceptionTranslator.java | 64 ++-- .../online/web/rest/errors/FieldErrorVM.java | 1 - .../jhipster/online/web/rest/vm/LoginVM.java | 5 +- .../online/web/rest/vm/ManagedUserVM.java | 1 - src/main/resources/config/application.yml | 2 +- .../user-management/user-modal.service.ts | 54 ++-- .../app/entities/statistics/statistics.scss | 24 +- .../entities/statistics/statistics.service.ts | 50 ++-- .../app/home/generator/git.company.model.ts | 2 +- .../webapp/app/home/welcome/welcome.route.ts | 12 +- src/main/webapp/app/home/welcome/welcome.scss | 10 +- .../app/layouts/footer/footer.component.ts | 6 +- .../webapp/app/layouts/footer/footer.scss | 2 +- .../app/shared/model/crash-report.model.ts | 32 +- .../app/shared/model/entity-stats.model.ts | 64 ++-- .../shared/model/generator-identity.model.ts | 10 +- .../webapp/app/shared/model/language.model.ts | 8 +- .../app/shared/model/sub-gen-event.model.ts | 48 +-- .../app/shared/model/test-framework.model.ts | 8 +- .../webapp/app/shared/model/yo-rc.model.ts | 188 ++++++------ .../io/github/jhipster/online/ArchTest.java | 18 +- .../online/config/AsyncConfiguration.java | 3 +- .../online/config/NoOpMailConfiguration.java | 9 +- .../online/config/WebConfigurerTest.java | 81 +++-- .../config/WebConfigurerTestController.java | 6 +- .../CustomAuditEventRepositoryIT.java | 20 +- .../security/DomainUserDetailsServiceIT.java | 14 +- .../security/SecurityUtilsUnitTest.java | 12 +- .../online/security/jwt/JWTFilterTest.java | 8 +- .../security/jwt/TokenProviderTest.java | 27 +- .../online/service/AuditEventServiceIT.java | 16 +- .../online/service/DataGenerationFixture.java | 8 +- .../service/GeneratorIdentityServiceTest.java | 9 +- .../online/service/MailServiceIT.java | 46 +-- .../online/service/UserServiceIT.java | 30 +- .../service/enums/TemporalValueTypeTest.java | 7 +- .../online/service/mapper/UserMapperTest.java | 11 +- .../yorc/YoRCServiceChoicesIntTest.java | 18 +- .../yorc/YoRCServiceCountsIntTest.java | 18 +- .../jhipster/online/util/DateUtilTest.java | 11 +- .../online/util/SanitizeInputsTest.java | 17 +- .../online/web/rest/AccountResourceIT.java | 271 ++++++++--------- .../online/web/rest/AuditResourceIT.java | 30 +- .../web/rest/ClientForwardControllerTest.java | 22 +- .../web/rest/EntityStatsResourceIntTest.java | 77 ++--- .../GeneratorIdentityResourceIntTest.java | 91 +++--- .../online/web/rest/GitResourceIntTest.java | 38 ++- .../web/rest/StatisticsResourceIntTest.java | 44 +-- .../web/rest/SubGenEventResourceIntTest.java | 79 ++--- .../jhipster/online/web/rest/TestUtil.java | 29 +- .../online/web/rest/UserJWTControllerIT.java | 23 +- .../online/web/rest/UserResourceIT.java | 162 +++++----- .../web/rest/WithUnauthenticatedMockUser.java | 13 +- .../online/web/rest/YoRCResourceIntTest.java | 47 +-- .../rest/errors/ExceptionTranslatorIT.java | 47 +-- .../ExceptionTranslatorTestController.java | 18 +- src/test/javascript/jest.conf.js | 95 +++--- src/test/resources/config/application.yml | 2 +- tsconfig-aot.json | 52 ++-- yarn.lock | 27 ++ 180 files changed, 3125 insertions(+), 2577 deletions(-) diff --git a/.lintstagedrc.js b/.lintstagedrc.js index 58dedb03..c7e45c88 100644 --- a/.lintstagedrc.js +++ b/.lintstagedrc.js @@ -1,3 +1,3 @@ module.exports = { - '{,src/**/}*.{md,json,ts,css,scss,yml}': ['prettier --write', 'git add'] + '{,src/**/}*.{md,json,yaml,yml,java,ts,js,css,scss}': ['prettier --write', 'git add'] }; diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index f7dc3c5b..40cd5251 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -8,19 +8,19 @@ In the interest of fostering an open and welcoming environment, we as contributo Examples of behavior that contributes to creating a positive environment include: -* Using welcoming and inclusive language -* Being respectful of differing viewpoints and experiences -* Gracefully accepting constructive criticism -* Focusing on what is best for the community -* Showing empathy towards other community members +- Using welcoming and inclusive language +- Being respectful of differing viewpoints and experiences +- Gracefully accepting constructive criticism +- Focusing on what is best for the community +- Showing empathy towards other community members Examples of unacceptable behavior by participants include: -* The use of sexualized language or imagery and unwelcome sexual attention or advances -* Trolling, insulting/derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or electronic address, without explicit permission -* Other conduct which could reasonably be considered inappropriate in a professional setting +- The use of sexualized language or imagery and unwelcome sexual attention or advances +- Trolling, insulting/derogatory comments, and personal or political attacks +- Public or private harassment +- Publishing others' private information, such as a physical or electronic address, without explicit permission +- Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 7f6f49fc..14ff22d3 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -2,100 +2,106 @@ Are you ready to contribute to JHipster Online? We'd love to have you on board, and we will help you as much as we can. Here are the guidelines we'd like you to follow so that we can be of more help: - - [Questions and help](#question) - - [Issues and Bugs](#issue) - - [Feature Requests](#feature) - - [Submission Guidelines](#submit) - - [Generator development setup](#setup) - - [Coding Rules](#rules) - - [Git Commit Guidelines](#commit) +- [Questions and help](#question) +- [Issues and Bugs](#issue) +- [Feature Requests](#feature) +- [Submission Guidelines](#submit) +- [Generator development setup](#setup) +- [Coding Rules](#rules) +- [Git Commit Guidelines](#commit) And don't forget we also accept [financial contributions to the project](https://www.jhipster.tech/sponsors/) using OpenCollective. ## Questions and help + This is the JHipster Online bug tracker, and it is used for [Issues and Bugs](#issue) and for [Feature Requests](#feature). It is **not** a help desk or a support forum. If you have a question on using JHipster Online, or if you need help with your JHipster project, please [read our help page](https://www.jhipster.tech/help/) and use the [JHipster tag on StackOverflow](http://stackoverflow.com/tags/jhipster) or join our [Gitter.im chat room](https://gitter.im/jhipster/generator-jhipster). ## Issues and Bugs + If you find a bug in the source code or a mistake in the documentation, you can help us by [submitting a ticket](https://opensource.guide/how-to-contribute/#opening-an-issue) to our [GitHub issues](https://github.com/jhipster/jhipster-online/issues). Even better, you can submit a Pull Request to the [JHipster Online project](https://github.com/jhipster/jhipster-online). **Please see the Submission Guidelines below**. ## Feature Requests + You can request a new feature by submitting a ticket to our [GitHub issues](https://github.com/jhipster/jhipster-online/issues). If you would like to implement a new feature then consider what kind of change it is: -* **Major Changes** that you wish to contribute to the project should be discussed first. Please open a ticket which clearly states that it is a feature request in the title and explain clearly what you want to achieve in the description, and the JHipster team will discuss with you what should be done in that ticket. You can then start working on a Pull Request. -* **Small Changes** can be proposed without any discussion. Open up a ticket which clearly states that it is a feature request in the title. Explain your change in the description, and you can propose a Pull Request straight away. +- **Major Changes** that you wish to contribute to the project should be discussed first. Please open a ticket which clearly states that it is a feature request in the title and explain clearly what you want to achieve in the description, and the JHipster team will discuss with you what should be done in that ticket. You can then start working on a Pull Request. +- **Small Changes** can be proposed without any discussion. Open up a ticket which clearly states that it is a feature request in the title. Explain your change in the description, and you can propose a Pull Request straight away. ## Submission Guidelines ### [Submitting an Issue](https://opensource.guide/how-to-contribute/#opening-an-issue) + Before you submit your issue search the [archive](https://github.com/jhipster/jhipster-online/issues?utf8=%E2%9C%93&q=is%3Aissue), maybe your question was already answered. If your issue appears to be a bug, and has not been reported, open a new issue. Help us to maximize the effort we can spend fixing issues and adding new -features, by not reporting duplicate issues. Providing the following information will increase the +features, by not reporting duplicate issues. Providing the following information will increase the chances of your issue being dealt with quickly: -* **Overview of the issue** - if an error is being thrown a stack trace helps -* **Motivation for or Use Case** - explain why this is a bug for you -* **Reproduce the error** - an unambiguous set of steps to reproduce the error. If you have a JavaScript error, maybe you can provide a live example with +- **Overview of the issue** - if an error is being thrown a stack trace helps +- **Motivation for or Use Case** - explain why this is a bug for you +- **Reproduce the error** - an unambiguous set of steps to reproduce the error. If you have a JavaScript error, maybe you can provide a live example with [JSFiddle](http://jsfiddle.net/)? -* **Related issues** - has a similar issue been reported before? -* **Suggest a Fix** - if you can't fix the bug yourself, perhaps you can point to what might be +- **Related issues** - has a similar issue been reported before? +- **Suggest a Fix** - if you can't fix the bug yourself, perhaps you can point to what might be causing the problem (line of code or commit) -* **JHipster Online Version(s)** - is it a regression? -* **Browsers and Operating System** - is this a problem with all browsers or only IE8? +- **JHipster Online Version(s)** - is it a regression? +- **Browsers and Operating System** - is this a problem with all browsers or only IE8? Click [here](https://github.com/jhipster/jhipster-online/issues/new) to open a ticket. ### [Submitting a Pull Request](https://opensource.guide/how-to-contribute/#opening-a-pull-request) + Before you submit your pull request consider the following guidelines: -* Search [GitHub](https://github.com/jhipster/jhipster-online/pulls?utf8=%E2%9C%93&q=is%3Apr) for an open or closed Pull Request +- Search [GitHub](https://github.com/jhipster/jhipster-online/pulls?utf8=%E2%9C%93&q=is%3Apr) for an open or closed Pull Request that relates to your submission. -* Make your changes in a new git branch +- Make your changes in a new git branch - ```shell - git checkout -b my-fix-branch master - ``` + ```shell + git checkout -b my-fix-branch master + ``` -* Create your patch, **including appropriate test cases**. -* Follow our [Coding Rules](#rules). -* Ensure that all tests pass +- Create your patch, **including appropriate test cases**. +- Follow our [Coding Rules](#rules). +- Ensure that all tests pass - ```shell - ./mvnw verify -Pprod - ``` + ```shell + ./mvnw verify -Pprod + ``` -* Test that the new project runs correctly: +- Test that the new project runs correctly: - ```shell - ./mvnw - ``` + ```shell + ./mvnw + ``` -* Commit your changes using a descriptive commit message that follows our +- Commit your changes using a descriptive commit message that follows our [commit message conventions](#commit-message-format). - ```shell - git commit -a - ``` + ```shell + git commit -a + ``` Note: the optional commit `-a` command line option will automatically "add" and "rm" edited files. -* Push your branch to GitHub: +- Push your branch to GitHub: - ```shell - git push origin my-fix-branch - ``` + ```shell + git push origin my-fix-branch + ``` + +- In GitHub, send a pull request to `jhipster/jhipster-online:master`. +- If we suggest changes then -* In GitHub, send a pull request to `jhipster/jhipster-online:master`. -* If we suggest changes then - * Make the required updates. - * Re-run the JHipster Online tests on your sample generated project to ensure tests are still passing. - * Rebase your branch and force push to your GitHub repository (this will update your Pull Request): + - Make the required updates. + - Re-run the JHipster Online tests on your sample generated project to ensure tests are still passing. + - Rebase your branch and force push to your GitHub repository (this will update your Pull Request): ```shell git rebase master -i @@ -108,71 +114,72 @@ That's it! Thank you for your contribution! Sometimes your PR will have merge conflicts with the upstream repository's master branch. There are several ways to solve this but if not done correctly this can end up as a true nightmare. So here is one method that works quite well. -* First, fetch the latest information from the master +- First, fetch the latest information from the master - ```shell - git fetch upstream - ``` + ```shell + git fetch upstream + ``` -* Rebase your branch against the upstream/master +- Rebase your branch against the upstream/master - ```shell - git rebase upstream/master - ``` + ```shell + git rebase upstream/master + ``` -* Git will stop rebasing at the first merge conflict and indicate which file is in conflict. Edit the file, resolve the conflict then +- Git will stop rebasing at the first merge conflict and indicate which file is in conflict. Edit the file, resolve the conflict then - ```shell - git add - git rebase --continue - ``` + ```shell + git add + git rebase --continue + ``` -* The rebase will continue up to the next conflict. Repeat the previous step until all files are merged and the rebase ends successfully. -* Re-run the JHipster Online tests on your sample generated project to ensure tests are still passing. -* Force push to your GitHub repository (this will update your Pull Request) +- The rebase will continue up to the next conflict. Repeat the previous step until all files are merged and the rebase ends successfully. +- Re-run the JHipster Online tests on your sample generated project to ensure tests are still passing. +- Force push to your GitHub repository (this will update your Pull Request) - ```shell - git push -f - ``` + ```shell + git push -f + ``` #### After your pull request is merged After your pull request is merged, you can safely delete your branch and pull the changes from the main (upstream) repository: -* Delete the remote branch on GitHub either through the GitHub web UI or your local shell as follows: +- Delete the remote branch on GitHub either through the GitHub web UI or your local shell as follows: - ```shell - git push origin --delete my-fix-branch - ``` + ```shell + git push origin --delete my-fix-branch + ``` -* Check out the master branch: +- Check out the master branch: - ```shell - git checkout master -f - ``` + ```shell + git checkout master -f + ``` -* Delete the local branch: +- Delete the local branch: - ```shell - git branch -D my-fix-branch - ``` + ```shell + git branch -D my-fix-branch + ``` -* Update your master with the latest upstream version: +- Update your master with the latest upstream version: - ```shell - git pull --ff upstream master - ``` + ```shell + git pull --ff upstream master + ``` ## Coding Rules + To ensure consistency throughout the source code, keep these rules in mind as you are working: -* All features or bug fixes **must be tested** by one or more tests. -* All files must follow the [.editorconfig file](http://editorconfig.org/) located at the root of the JHipster generator project. Please note that generated projects use the same `.editorconfig` file, so that both the generator and the generated projects share the same configuration. -* Java files **must be** formatted using [Intellij IDEA's code style](http://confluence.jetbrains.com/display/IntelliJIDEA/Code+Style+and+Formatting). Please note that JHipster committers have a free Intellij IDEA Ultimate Edition for developing the project. -* Generators JavaScript files **must follow** the eslint configuration defined at the project root, which is based on [Airbnb JavaScript Style Guide](https://github.com/airbnb/javascript). -* Web apps JavaScript files **must follow** [Google's JavaScript Style Guide](https://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml). -* Angular Typescript files **must follow** [Official Angular style guide](https://angular.io/styleguide). +- All features or bug fixes **must be tested** by one or more tests. +- All files must follow the [.editorconfig file](http://editorconfig.org/) located at the root of the JHipster generator project. Please note that generated projects use the same `.editorconfig` file, so that both the generator and the generated projects share the same configuration. +- Java files **must be** formatted using [Intellij IDEA's code style](http://confluence.jetbrains.com/display/IntelliJIDEA/Code+Style+and+Formatting). Please note that JHipster committers have a free Intellij IDEA Ultimate Edition for developing the project. +- Generators JavaScript files **must follow** the eslint configuration defined at the project root, which is based on [Airbnb JavaScript Style Guide](https://github.com/airbnb/javascript). +- Web apps JavaScript files **must follow** [Google's JavaScript Style Guide](https://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml). +- Angular Typescript files **must follow** [Official Angular style guide](https://angular.io/styleguide). Please ensure to run `yarn lint` and `yarn test` on the project root before submitting a pull request. @@ -181,6 +188,7 @@ Please ensure to run `yarn lint` and `yarn test` on the project root before subm We have rules over how our git commit messages must be formatted. Please ensure to [squash](https://help.github.com/articles/about-git-rebase/#commands-available-while-rebasing) unnecessary commits so that your commit history is clean. ### Commit Message Format + Each commit message consists of a **header**, a **body** and a **footer**. ``` @@ -195,25 +203,29 @@ Any line of the commit message cannot be longer 100 characters! This allows the to read on GitHub as well as in various git tools. ### Header + The Header contains a succinct description of the change: -* use the imperative, present tense: "change" not "changed" nor "changes" -* don't capitalize first letter -* no dot (.) at the end +- use the imperative, present tense: "change" not "changed" nor "changes" +- don't capitalize first letter +- no dot (.) at the end ### Body + If your change is simple, the Body is optional. Just as in the Header, use the imperative, present tense: "change" not "changed" nor "changes". The Body should include the motivation for the change and contrast this with previous behavior. ### Footer + The footer is the place to reference GitHub issues that this commit **Closes**. You **must** use the [GitHub keywords](https://help.github.com/articles/closing-issues-via-commit-messages) for automatically closing the issues referenced in your commit. ### Example + For example, here is a good commit message: ``` diff --git a/app.yaml b/app.yaml index a2d28c59..d9676cf0 100644 --- a/app.yaml +++ b/app.yaml @@ -1,27 +1,25 @@ runtime: custom env: flex resources: - cpu: 1 - memory_gb: 4.0 - disk_size_gb: 10 + cpu: 1 + memory_gb: 4.0 + disk_size_gb: 10 manual_scaling: - instances: 1 + instances: 1 env_variables: - DATABASE_NAME: - GCP_PROJECT_ID: - GCP_REGION: - SQL_INSTANCE_ID: - DATABASE_USERNAME: - DATABASE_PASSWORD: - MAIL_HOST: - MAIL_PORT: - MAIL_USERNAME: - MAIL_PASSWORD: - BASE64_SECRET: - CLIENT_ID_GITHUB: - CLIENT_SECRET_GITHUB: - GITLAB_CLIENT_ID: - GITLAB_CLIENT_SECRET: - GITLAB_REDIRECT_URI: - - + DATABASE_NAME: + GCP_PROJECT_ID: + GCP_REGION: + SQL_INSTANCE_ID: + DATABASE_USERNAME: + DATABASE_PASSWORD: + MAIL_HOST: + MAIL_PORT: + MAIL_USERNAME: + MAIL_PASSWORD: + BASE64_SECRET: + CLIENT_ID_GITHUB: + CLIENT_SECRET_GITHUB: + GITLAB_CLIENT_ID: + GITLAB_CLIENT_SECRET: + GITLAB_REDIRECT_URI: diff --git a/package.json b/package.json index a137f1b3..2306181f 100644 --- a/package.json +++ b/package.json @@ -80,6 +80,7 @@ "optimize-css-assets-webpack-plugin": "5.0.3", "postcss-loader": "3.0.0", "prettier": "1.19.1", + "prettier-plugin-java": "0.8.3", "reflect-metadata": "0.1.13", "rimraf": "3.0.0", "sass": "1.23.7", @@ -106,7 +107,7 @@ "yarn": ">=1.19.0" }, "scripts": { - "prettier:format": "prettier --write \"{,src/**/}*.{md,json,ts,css,scss,yml}\"", + "prettier:format": "prettier --write \"{,src/**/}*.{md,json,yaml,yml,java,ts,js,css,scss}\"", "lint": "eslint . --ext .js,.ts", "lint:fix": "yarn run lint --fix", "ngc": "ngc -p tsconfig.app.json", diff --git a/postcss.config.js b/postcss.config.js index a26de7e9..b0f214d5 100644 --- a/postcss.config.js +++ b/postcss.config.js @@ -1,5 +1,3 @@ module.exports = { - plugins: [ - require('autoprefixer') - ] -} + plugins: [require('autoprefixer')] +}; diff --git a/proxy.conf.json b/proxy.conf.json index 8b41fdf7..3bfe56a3 100644 --- a/proxy.conf.json +++ b/proxy.conf.json @@ -1,7 +1,7 @@ { - "*": { - "target": "http://localhost:8080", - "secure": false, - "loglevel": "debug" - } + "*": { + "target": "http://localhost:8080", + "secure": false, + "loglevel": "debug" + } } diff --git a/src/main/docker/app.yml b/src/main/docker/app.yml index d0d0e943..1eacac08 100644 --- a/src/main/docker/app.yml +++ b/src/main/docker/app.yml @@ -1,16 +1,16 @@ version: '2' services: - jhonline-app: - image: jhonline - environment: - # - _JAVA_OPTIONS=-Xmx512m -Xms256m - - SPRING_PROFILES_ACTIVE=prod,swagger - - MANAGEMENT_METRICS_EXPORT_PROMETHEUS_ENABLED=true - - SPRING_DATASOURCE_URL=jdbc:mysql://jhonline-mysql:3306/jhipster-online?useUnicode=true&characterEncoding=utf8&useSSL=false - - JHIPSTER_SLEEP=30 # gives time for other services to boot before the application - ports: - - 8080:8080 - jhonline-mysql: - extends: - file: mysql.yml - service: jhonline-mysql + jhonline-app: + image: jhonline + environment: + # - _JAVA_OPTIONS=-Xmx512m -Xms256m + - SPRING_PROFILES_ACTIVE=prod,swagger + - MANAGEMENT_METRICS_EXPORT_PROMETHEUS_ENABLED=true + - SPRING_DATASOURCE_URL=jdbc:mysql://jhonline-mysql:3306/jhipster-online?useUnicode=true&characterEncoding=utf8&useSSL=false + - JHIPSTER_SLEEP=30 # gives time for other services to boot before the application + ports: + - 8080:8080 + jhonline-mysql: + extends: + file: mysql.yml + service: jhonline-mysql diff --git a/src/main/docker/mailserver.yml b/src/main/docker/mailserver.yml index cda75ad5..bc2497c9 100644 --- a/src/main/docker/mailserver.yml +++ b/src/main/docker/mailserver.yml @@ -1,7 +1,7 @@ version: '2' services: - mailserver: - image: mailhog/mailhog - ports: - - 1025:1025 - - 8025:8025 + mailserver: + image: mailhog/mailhog + ports: + - 1025:1025 + - 8025:8025 diff --git a/src/main/docker/mysql.yml b/src/main/docker/mysql.yml index d1c2f3bc..66c6fbdf 100644 --- a/src/main/docker/mysql.yml +++ b/src/main/docker/mysql.yml @@ -1,13 +1,13 @@ version: '2' services: - jhonline-mysql: - image: mysql:5.7.20 - # volumes: - # - ~/volumes/jhipster/jhonline/mysql/:/var/lib/mysql/ - environment: - - MYSQL_USER=root - - MYSQL_ALLOW_EMPTY_PASSWORD=yes - - MYSQL_DATABASE=jhipster-online - ports: - - 3306:3306 - command: mysqld --lower_case_table_names=1 --skip-ssl --character_set_server=utf8mb4 --explicit_defaults_for_timestamp + jhonline-mysql: + image: mysql:5.7.20 + # volumes: + # - ~/volumes/jhipster/jhonline/mysql/:/var/lib/mysql/ + environment: + - MYSQL_USER=root + - MYSQL_ALLOW_EMPTY_PASSWORD=yes + - MYSQL_DATABASE=jhipster-online + ports: + - 3306:3306 + command: mysqld --lower_case_table_names=1 --skip-ssl --character_set_server=utf8mb4 --explicit_defaults_for_timestamp diff --git a/src/main/docker/sonar.yml b/src/main/docker/sonar.yml index ec79f02c..5bacea60 100644 --- a/src/main/docker/sonar.yml +++ b/src/main/docker/sonar.yml @@ -1,7 +1,7 @@ version: '2' services: - jhonline-sonar: - image: sonarqube:8.2-community - ports: - - 9000:9000 - - 9092:9092 + jhonline-sonar: + image: sonarqube:8.2-community + ports: + - 9000:9000 + - 9092:9092 diff --git a/src/main/java/io/github/jhipster/online/JhonlineApp.java b/src/main/java/io/github/jhipster/online/JhonlineApp.java index f59d0fe2..4dba8946 100644 --- a/src/main/java/io/github/jhipster/online/JhonlineApp.java +++ b/src/main/java/io/github/jhipster/online/JhonlineApp.java @@ -21,6 +21,11 @@ import io.github.jhipster.config.DefaultProfileUtil; import io.github.jhipster.config.JHipsterConstants; import io.github.jhipster.online.config.ApplicationProperties; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.util.Arrays; +import java.util.Collection; +import javax.annotation.PostConstruct; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -30,14 +35,8 @@ import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.core.env.Environment; -import javax.annotation.PostConstruct; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.Arrays; -import java.util.Collection; - @SpringBootApplication -@EnableConfigurationProperties({LiquibaseProperties.class, ApplicationProperties.class}) +@EnableConfigurationProperties({ LiquibaseProperties.class, ApplicationProperties.class }) public class JhonlineApp { private static final Logger log = LoggerFactory.getLogger(JhonlineApp.class); @@ -58,13 +57,21 @@ public JhonlineApp(Environment env) { @PostConstruct public void initApplication() { Collection activeProfiles = Arrays.asList(env.getActiveProfiles()); - if (activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT) && activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_PRODUCTION)) { - log.error("You have misconfigured your application! It should not run " + - "with both the 'dev' and 'prod' profiles at the same time."); + if ( + activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT) && + activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_PRODUCTION) + ) { + log.error( + "You have misconfigured your application! It should not run " + "with both the 'dev' and 'prod' profiles at the same time." + ); } - if (activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT) && activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_CLOUD)) { - log.error("You have misconfigured your application! It should not " + - "run with both the 'dev' and 'cloud' profiles at the same time."); + if ( + activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT) && + activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_CLOUD) + ) { + log.error( + "You have misconfigured your application! It should not " + "run with both the 'dev' and 'cloud' profiles at the same time." + ); } } @@ -96,11 +103,12 @@ private static void logApplicationStartup(Environment env) { } catch (UnknownHostException e) { log.warn("The host name could not be determined, using `localhost` as fallback"); } - log.info("\n----------------------------------------------------------\n\t" + - "Application '{}' is running! Access URLs:\n\t" + - "Local: \t\t{}://localhost:{}{}\n\t" + - "External: \t{}://{}:{}{}\n\t" + - "Profile(s): \t{}\n----------------------------------------------------------", + log.info( + "\n----------------------------------------------------------\n\t" + + "Application '{}' is running! Access URLs:\n\t" + + "Local: \t\t{}://localhost:{}{}\n\t" + + "External: \t{}://{}:{}{}\n\t" + + "Profile(s): \t{}\n----------------------------------------------------------", env.getProperty("spring.application.name"), protocol, serverPort, @@ -109,6 +117,7 @@ private static void logApplicationStartup(Environment env) { hostAddress, serverPort, contextPath, - env.getActiveProfiles()); + env.getActiveProfiles() + ); } } diff --git a/src/main/java/io/github/jhipster/online/aop/logging/LoggingAspect.java b/src/main/java/io/github/jhipster/online/aop/logging/LoggingAspect.java index 192cb50e..09e1147a 100644 --- a/src/main/java/io/github/jhipster/online/aop/logging/LoggingAspect.java +++ b/src/main/java/io/github/jhipster/online/aop/logging/LoggingAspect.java @@ -19,6 +19,7 @@ package io.github.jhipster.online.aop.logging; import io.github.jhipster.config.JHipsterConstants; +import java.util.Arrays; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.AfterThrowing; @@ -30,8 +31,6 @@ import org.springframework.core.env.Environment; import org.springframework.core.env.Profiles; -import java.util.Arrays; - /** * Aspect for logging execution of service and repository Spring components. * @@ -49,9 +48,11 @@ public LoggingAspect(Environment env) { /** * Pointcut that matches all repositories, services and Web REST endpoints. */ - @Pointcut("within(@org.springframework.stereotype.Repository *)" + + @Pointcut( + "within(@org.springframework.stereotype.Repository *)" + " || within(@org.springframework.stereotype.Service *)" + - " || within(@org.springframework.web.bind.annotation.RestController *)") + " || within(@org.springframework.web.bind.annotation.RestController *)" + ) public void springBeanPointcut() { // Method is empty as this is just a Pointcut, the implementations are in the advices. } @@ -59,9 +60,11 @@ public void springBeanPointcut() { /** * Pointcut that matches all Spring beans in the application's main packages. */ - @Pointcut("within(io.github.jhipster.online.repository..*)"+ - " || within(io.github.jhipster.online.service..*)"+ - " || within(io.github.jhipster.online.web.rest..*)") + @Pointcut( + "within(io.github.jhipster.online.repository..*)" + + " || within(io.github.jhipster.online.service..*)" + + " || within(io.github.jhipster.online.web.rest..*)" + ) public void applicationPackagePointcut() { // Method is empty as this is just a Pointcut, the implementations are in the advices. } diff --git a/src/main/java/io/github/jhipster/online/config/ApplicationProperties.java b/src/main/java/io/github/jhipster/online/config/ApplicationProperties.java index 8ea26264..f934c97d 100644 --- a/src/main/java/io/github/jhipster/online/config/ApplicationProperties.java +++ b/src/main/java/io/github/jhipster/online/config/ApplicationProperties.java @@ -68,6 +68,7 @@ public Mail getMail() { } public static class JhipsterCmd { + private String cmd = "jhipster"; private Integer timeout = 120; @@ -89,6 +90,7 @@ public void setTimeout(Integer timeout) { } public static class Github { + private String clientId; private String clientSecret; private String host = "https://github.com"; @@ -119,6 +121,7 @@ public void setHost(String host) { } public static class Gitlab { + private String clientId; private String clientSecret; private String host = "https://gitlab.com"; @@ -169,5 +172,4 @@ public boolean isEnable() { return enable; } } - } diff --git a/src/main/java/io/github/jhipster/online/config/AsyncConfiguration.java b/src/main/java/io/github/jhipster/online/config/AsyncConfiguration.java index 520b920a..85ef890d 100644 --- a/src/main/java/io/github/jhipster/online/config/AsyncConfiguration.java +++ b/src/main/java/io/github/jhipster/online/config/AsyncConfiguration.java @@ -19,6 +19,7 @@ package io.github.jhipster.online.config; import io.github.jhipster.async.ExceptionHandlingAsyncTaskExecutor; +import java.util.concurrent.Executor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler; @@ -31,8 +32,6 @@ import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; -import java.util.concurrent.Executor; - @Configuration @EnableAsync @EnableScheduling diff --git a/src/main/java/io/github/jhipster/online/config/CacheConfiguration.java b/src/main/java/io/github/jhipster/online/config/CacheConfiguration.java index 4615b047..37041fc3 100644 --- a/src/main/java/io/github/jhipster/online/config/CacheConfiguration.java +++ b/src/main/java/io/github/jhipster/online/config/CacheConfiguration.java @@ -20,6 +20,8 @@ package io.github.jhipster.online.config; import io.github.jhipster.config.JHipsterProperties; +import java.time.Duration; +import javax.cache.CacheManager; import org.ehcache.config.builders.CacheConfigurationBuilder; import org.ehcache.config.builders.ExpiryPolicyBuilder; import org.ehcache.config.builders.ResourcePoolsBuilder; @@ -31,9 +33,6 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import javax.cache.CacheManager; -import java.time.Duration; - @Configuration @EnableCaching public class CacheConfiguration { @@ -49,17 +48,21 @@ public class CacheConfiguration { public CacheConfiguration(JHipsterProperties jHipsterProperties) { JHipsterProperties.Cache.Ehcache ehcache = jHipsterProperties.getCache().getEhcache(); - jcacheConfiguration = Eh107Configuration.fromEhcacheCacheConfiguration( - CacheConfigurationBuilder.newCacheConfigurationBuilder(Object.class, Object.class, - ResourcePoolsBuilder.heap(ehcache.getMaxEntries())) - .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofSeconds(ehcache.getTimeToLiveSeconds()))) - .build()); + jcacheConfiguration = + Eh107Configuration.fromEhcacheCacheConfiguration( + CacheConfigurationBuilder + .newCacheConfigurationBuilder(Object.class, Object.class, ResourcePoolsBuilder.heap(ehcache.getMaxEntries())) + .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofSeconds(ehcache.getTimeToLiveSeconds()))) + .build() + ); - statisticsJcacheConfiguration = Eh107Configuration.fromEhcacheCacheConfiguration( - CacheConfigurationBuilder.newCacheConfigurationBuilder(Object.class, Object.class, - ResourcePoolsBuilder.heap(100L)) - .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMinutes(5))) - .build()); + statisticsJcacheConfiguration = + Eh107Configuration.fromEhcacheCacheConfiguration( + CacheConfigurationBuilder + .newCacheConfigurationBuilder(Object.class, Object.class, ResourcePoolsBuilder.heap(100L)) + .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMinutes(5))) + .build() + ); } @Bean @@ -95,9 +98,12 @@ public JCacheManagerCustomizer cacheManagerCustomizer() { }; } - private void createIfNotExists(CacheManager cacheManager, String cacheName, - javax.cache.configuration.Configuration cacheConfiguration) { - if(cacheManager.getCache(cacheName) == null) { + private void createIfNotExists( + CacheManager cacheManager, + String cacheName, + javax.cache.configuration.Configuration cacheConfiguration + ) { + if (cacheManager.getCache(cacheName) == null) { cacheManager.createCache(cacheName, cacheConfiguration); } } diff --git a/src/main/java/io/github/jhipster/online/config/CloudDatabaseConfiguration.java b/src/main/java/io/github/jhipster/online/config/CloudDatabaseConfiguration.java index e5728716..7f18eed7 100644 --- a/src/main/java/io/github/jhipster/online/config/CloudDatabaseConfiguration.java +++ b/src/main/java/io/github/jhipster/online/config/CloudDatabaseConfiguration.java @@ -20,6 +20,7 @@ package io.github.jhipster.online.config; import io.github.jhipster.config.JHipsterConstants; +import javax.sql.DataSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.context.properties.ConfigurationProperties; @@ -28,9 +29,6 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; -import javax.sql.DataSource; - - @Configuration @Profile(JHipsterConstants.SPRING_PROFILE_CLOUD) public class CloudDatabaseConfiguration extends AbstractCloudConfig { diff --git a/src/main/java/io/github/jhipster/online/config/Constants.java b/src/main/java/io/github/jhipster/online/config/Constants.java index 49922b31..e24c628e 100644 --- a/src/main/java/io/github/jhipster/online/config/Constants.java +++ b/src/main/java/io/github/jhipster/online/config/Constants.java @@ -30,6 +30,5 @@ public final class Constants { public static final String DEFAULT_LANGUAGE = "en"; public static final String ANONYMOUS_USER = "anonymoususer"; - private Constants() { - } + private Constants() {} } diff --git a/src/main/java/io/github/jhipster/online/config/DatabaseConfiguration.java b/src/main/java/io/github/jhipster/online/config/DatabaseConfiguration.java index cd891e63..c8238871 100644 --- a/src/main/java/io/github/jhipster/online/config/DatabaseConfiguration.java +++ b/src/main/java/io/github/jhipster/online/config/DatabaseConfiguration.java @@ -24,10 +24,8 @@ import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.transaction.annotation.EnableTransactionManagement; - @Configuration @EnableJpaRepositories("io.github.jhipster.online.repository") @EnableJpaAuditing(auditorAwareRef = "springSecurityAuditorAware") @EnableTransactionManagement -public class DatabaseConfiguration { -} +public class DatabaseConfiguration {} diff --git a/src/main/java/io/github/jhipster/online/config/LiquibaseConfiguration.java b/src/main/java/io/github/jhipster/online/config/LiquibaseConfiguration.java index 0ed8bad4..95209a06 100644 --- a/src/main/java/io/github/jhipster/online/config/LiquibaseConfiguration.java +++ b/src/main/java/io/github/jhipster/online/config/LiquibaseConfiguration.java @@ -21,6 +21,8 @@ import io.github.jhipster.config.JHipsterConstants; import io.github.jhipster.config.liquibase.SpringLiquibaseUtil; +import java.util.concurrent.Executor; +import javax.sql.DataSource; import liquibase.integration.spring.SpringLiquibase; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -34,9 +36,6 @@ import org.springframework.core.env.Environment; import org.springframework.core.env.Profiles; -import javax.sql.DataSource; -import java.util.concurrent.Executor; - @Configuration public class LiquibaseConfiguration { @@ -49,13 +48,23 @@ public LiquibaseConfiguration(Environment env) { } @Bean - public SpringLiquibase liquibase(@Qualifier("taskExecutor") Executor executor, - @LiquibaseDataSource ObjectProvider liquibaseDataSource, LiquibaseProperties liquibaseProperties, - ObjectProvider dataSource, DataSourceProperties dataSourceProperties) { - + public SpringLiquibase liquibase( + @Qualifier("taskExecutor") Executor executor, + @LiquibaseDataSource ObjectProvider liquibaseDataSource, + LiquibaseProperties liquibaseProperties, + ObjectProvider dataSource, + DataSourceProperties dataSourceProperties + ) { // If you don't want Liquibase to start asynchronously, substitute by this: // SpringLiquibase liquibase = SpringLiquibaseUtil.createSpringLiquibase(liquibaseDataSource.getIfAvailable(), liquibaseProperties, dataSource.getIfUnique(), dataSourceProperties); - SpringLiquibase liquibase = SpringLiquibaseUtil.createAsyncSpringLiquibase(this.env, executor, liquibaseDataSource.getIfAvailable(), liquibaseProperties, dataSource.getIfUnique(), dataSourceProperties); + SpringLiquibase liquibase = SpringLiquibaseUtil.createAsyncSpringLiquibase( + this.env, + executor, + liquibaseDataSource.getIfAvailable(), + liquibaseProperties, + dataSource.getIfUnique(), + dataSourceProperties + ); liquibase.setChangeLog("classpath:config/liquibase/master.xml"); liquibase.setContexts(liquibaseProperties.getContexts()); liquibase.setDefaultSchema(liquibaseProperties.getDefaultSchema()); diff --git a/src/main/java/io/github/jhipster/online/config/LoggingConfiguration.java b/src/main/java/io/github/jhipster/online/config/LoggingConfiguration.java index c58f8598..c85041a1 100644 --- a/src/main/java/io/github/jhipster/online/config/LoggingConfiguration.java +++ b/src/main/java/io/github/jhipster/online/config/LoggingConfiguration.java @@ -18,30 +18,31 @@ */ package io.github.jhipster.online.config; +import static io.github.jhipster.config.logging.LoggingUtils.*; + import ch.qos.logback.classic.LoggerContext; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.jhipster.config.JHipsterProperties; +import java.util.HashMap; +import java.util.Map; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; -import java.util.HashMap; -import java.util.Map; - -import static io.github.jhipster.config.logging.LoggingUtils.*; - /* * Configures the console and Logstash log appenders from the app properties */ @Configuration public class LoggingConfiguration { - public LoggingConfiguration(@Value("${spring.application.name}") String appName, - @Value("${server.port}") String serverPort, - JHipsterProperties jHipsterProperties, - ObjectMapper mapper) throws JsonProcessingException { - + public LoggingConfiguration( + @Value("${spring.application.name}") String appName, + @Value("${server.port}") String serverPort, + JHipsterProperties jHipsterProperties, + ObjectMapper mapper + ) + throws JsonProcessingException { LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); Map map = new HashMap<>(); diff --git a/src/main/java/io/github/jhipster/online/config/MDCConfiguration.java b/src/main/java/io/github/jhipster/online/config/MDCConfiguration.java index 587edc53..3ee32296 100644 --- a/src/main/java/io/github/jhipster/online/config/MDCConfiguration.java +++ b/src/main/java/io/github/jhipster/online/config/MDCConfiguration.java @@ -26,6 +26,7 @@ @Configuration public class MDCConfiguration implements WebMvcConfigurer { + @Override public void addInterceptors(InterceptorRegistry registry) { AsyncHandlerInterceptor mdcInterceptor = new MDCInterceptor(); diff --git a/src/main/java/io/github/jhipster/online/config/SecurityConfiguration.java b/src/main/java/io/github/jhipster/online/config/SecurityConfiguration.java index d9dfa016..d3a7cfe8 100644 --- a/src/main/java/io/github/jhipster/online/config/SecurityConfiguration.java +++ b/src/main/java/io/github/jhipster/online/config/SecurityConfiguration.java @@ -60,7 +60,8 @@ public PasswordEncoder passwordEncoder() { @Override public void configure(WebSecurity web) { - web.ignoring() + web + .ignoring() .antMatchers(HttpMethod.OPTIONS, "/**") .antMatchers("/app/**/*.{js,html}") .antMatchers("/i18n/**") diff --git a/src/main/java/io/github/jhipster/online/config/WebConfigurer.java b/src/main/java/io/github/jhipster/online/config/WebConfigurer.java index 426f7130..0fb3f358 100644 --- a/src/main/java/io/github/jhipster/online/config/WebConfigurer.java +++ b/src/main/java/io/github/jhipster/online/config/WebConfigurer.java @@ -18,9 +18,20 @@ */ package io.github.jhipster.online.config; +import static java.net.URLDecoder.decode; + import io.github.jhipster.config.JHipsterConstants; import io.github.jhipster.config.JHipsterProperties; import io.github.jhipster.web.filter.CachingHttpHeadersFilter; +import java.io.File; +import java.io.UnsupportedEncodingException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Paths; +import java.util.EnumSet; +import javax.servlet.DispatcherType; +import javax.servlet.FilterRegistration; +import javax.servlet.ServletContext; +import javax.servlet.ServletException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.web.server.MimeMappings; @@ -37,18 +48,6 @@ import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; -import javax.servlet.DispatcherType; -import javax.servlet.FilterRegistration; -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import java.io.File; -import java.io.UnsupportedEncodingException; -import java.nio.charset.StandardCharsets; -import java.nio.file.Paths; -import java.util.EnumSet; - -import static java.net.URLDecoder.decode; - /** * Configuration of web application with Servlet 3.0 APIs. */ @@ -135,12 +134,12 @@ private String resolvePathPrefix() { /** * Initializes the caching HTTP Headers Filter. */ - private void initCachingHttpHeadersFilter(ServletContext servletContext, - EnumSet disps) { + private void initCachingHttpHeadersFilter(ServletContext servletContext, EnumSet disps) { log.debug("Registering Caching HTTP Headers Filter"); - FilterRegistration.Dynamic cachingHttpHeadersFilter = - servletContext.addFilter("cachingHttpHeadersFilter", - new CachingHttpHeadersFilter(jHipsterProperties)); + FilterRegistration.Dynamic cachingHttpHeadersFilter = servletContext.addFilter( + "cachingHttpHeadersFilter", + new CachingHttpHeadersFilter(jHipsterProperties) + ); cachingHttpHeadersFilter.addMappingForUrlPatterns(disps, true, "/content/*"); cachingHttpHeadersFilter.addMappingForUrlPatterns(disps, true, "/app/*"); @@ -159,5 +158,4 @@ public CorsFilter corsFilter() { } return new CorsFilter(source); } - } diff --git a/src/main/java/io/github/jhipster/online/config/audit/AuditEventConverter.java b/src/main/java/io/github/jhipster/online/config/audit/AuditEventConverter.java index 5f98bac7..7c94d61a 100644 --- a/src/main/java/io/github/jhipster/online/config/audit/AuditEventConverter.java +++ b/src/main/java/io/github/jhipster/online/config/audit/AuditEventConverter.java @@ -19,12 +19,11 @@ package io.github.jhipster.online.config.audit; import io.github.jhipster.online.domain.PersistentAuditEvent; +import java.util.*; import org.springframework.boot.actuate.audit.AuditEvent; import org.springframework.security.web.authentication.WebAuthenticationDetails; import org.springframework.stereotype.Component; -import java.util.*; - @Component public class AuditEventConverter { @@ -55,8 +54,12 @@ public AuditEvent convertToAuditEvent(PersistentAuditEvent persistentAuditEvent) if (persistentAuditEvent == null) { return null; } - return new AuditEvent(persistentAuditEvent.getAuditEventDate(), persistentAuditEvent.getPrincipal(), - persistentAuditEvent.getAuditEventType(), convertDataToObjects(persistentAuditEvent.getData())); + return new AuditEvent( + persistentAuditEvent.getAuditEventDate(), + persistentAuditEvent.getPrincipal(), + persistentAuditEvent.getAuditEventType(), + convertDataToObjects(persistentAuditEvent.getData()) + ); } /** diff --git a/src/main/java/io/github/jhipster/online/domain/AbstractAuditingEntity.java b/src/main/java/io/github/jhipster/online/domain/AbstractAuditingEntity.java index b177f677..a019f6a6 100644 --- a/src/main/java/io/github/jhipster/online/domain/AbstractAuditingEntity.java +++ b/src/main/java/io/github/jhipster/online/domain/AbstractAuditingEntity.java @@ -19,18 +19,17 @@ package io.github.jhipster.online.domain; import com.fasterxml.jackson.annotation.JsonIgnore; +import java.io.Serializable; +import java.time.Instant; +import javax.persistence.Column; +import javax.persistence.EntityListeners; +import javax.persistence.MappedSuperclass; import org.springframework.data.annotation.CreatedBy; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.LastModifiedBy; import org.springframework.data.annotation.LastModifiedDate; import org.springframework.data.jpa.domain.support.AuditingEntityListener; -import javax.persistence.Column; -import javax.persistence.EntityListeners; -import javax.persistence.MappedSuperclass; -import java.io.Serializable; -import java.time.Instant; - /** * Base abstract class for entities which will hold definitions for created, last modified, created by, * last modified by attributes. diff --git a/src/main/java/io/github/jhipster/online/domain/Authority.java b/src/main/java/io/github/jhipster/online/domain/Authority.java index d27aff0f..05229610 100644 --- a/src/main/java/io/github/jhipster/online/domain/Authority.java +++ b/src/main/java/io/github/jhipster/online/domain/Authority.java @@ -18,17 +18,16 @@ */ package io.github.jhipster.online.domain; -import org.hibernate.annotations.Cache; -import org.hibernate.annotations.CacheConcurrencyStrategy; - +import java.io.Serializable; +import java.util.Objects; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; -import java.io.Serializable; -import java.util.Objects; +import org.hibernate.annotations.Cache; +import org.hibernate.annotations.CacheConcurrencyStrategy; /** * An authority (a security role) used by Spring Security. @@ -72,8 +71,6 @@ public int hashCode() { @Override public String toString() { - return "Authority{" + - "name='" + name + '\'' + - "}"; + return "Authority{" + "name='" + name + '\'' + "}"; } } diff --git a/src/main/java/io/github/jhipster/online/domain/EntityStats.java b/src/main/java/io/github/jhipster/online/domain/EntityStats.java index 69c8ade9..12a03bfb 100644 --- a/src/main/java/io/github/jhipster/online/domain/EntityStats.java +++ b/src/main/java/io/github/jhipster/online/domain/EntityStats.java @@ -21,13 +21,12 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import io.github.jhipster.online.domain.interfaces.CompleteDate; -import org.hibernate.annotations.Cache; -import org.hibernate.annotations.CacheConcurrencyStrategy; - -import javax.persistence.*; import java.io.Serializable; import java.time.Instant; import java.util.Objects; +import javax.persistence.*; +import org.hibernate.annotations.Cache; +import org.hibernate.annotations.CacheConcurrencyStrategy; /** * A EntityStats. @@ -260,6 +259,7 @@ public EntityStats owner(GeneratorIdentity generatorIdentity) { public void setOwner(GeneratorIdentity generatorIdentity) { this.owner = generatorIdentity; } + // jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove @Override @@ -284,20 +284,40 @@ public int hashCode() { @Override public String toString() { - return "EntityStats{" + - "id=" + getId() + - ", year=" + getYear() + - ", month=" + getMonth() + - ", week=" + getWeek() + - ", day=" + getDay() + - ", hour=" + getHour() + - ", fields=" + getFields() + - ", relationships=" + getRelationships() + - ", pagination='" + getPagination() + "'" + - ", dto='" + getDto() + "'" + - ", service='" + getService() + "'" + - ", fluentMethods='" + isFluentMethods() + "'" + - ", date='" + getDate() + "'" + - "}"; + return ( + "EntityStats{" + + "id=" + + getId() + + ", year=" + + getYear() + + ", month=" + + getMonth() + + ", week=" + + getWeek() + + ", day=" + + getDay() + + ", hour=" + + getHour() + + ", fields=" + + getFields() + + ", relationships=" + + getRelationships() + + ", pagination='" + + getPagination() + + "'" + + ", dto='" + + getDto() + + "'" + + ", service='" + + getService() + + "'" + + ", fluentMethods='" + + isFluentMethods() + + "'" + + ", date='" + + getDate() + + "'" + + "}" + ); } } diff --git a/src/main/java/io/github/jhipster/online/domain/GeneratorIdentity.java b/src/main/java/io/github/jhipster/online/domain/GeneratorIdentity.java index 94bb0c0a..cc57b17a 100644 --- a/src/main/java/io/github/jhipster/online/domain/GeneratorIdentity.java +++ b/src/main/java/io/github/jhipster/online/domain/GeneratorIdentity.java @@ -20,12 +20,11 @@ package io.github.jhipster.online.domain; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import org.hibernate.annotations.Cache; -import org.hibernate.annotations.CacheConcurrencyStrategy; - -import javax.persistence.*; import java.io.Serializable; import java.util.Objects; +import javax.persistence.*; +import org.hibernate.annotations.Cache; +import org.hibernate.annotations.CacheConcurrencyStrategy; /** * A GeneratorIdentity. @@ -98,6 +97,7 @@ public GeneratorIdentity owner(User user) { public void setOwner(User user) { this.owner = user; } + // jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove @Override @@ -122,10 +122,6 @@ public int hashCode() { @Override public String toString() { - return "GeneratorIdentity{" + - "id=" + getId() + - ", host='" + getHost() + "'" + - ", guid='" + getGuid() + "'" + - "}"; + return "GeneratorIdentity{" + "id=" + getId() + ", host='" + getHost() + "'" + ", guid='" + getGuid() + "'" + "}"; } } diff --git a/src/main/java/io/github/jhipster/online/domain/GitCompany.java b/src/main/java/io/github/jhipster/online/domain/GitCompany.java index 840fe6db..a28ef85d 100644 --- a/src/main/java/io/github/jhipster/online/domain/GitCompany.java +++ b/src/main/java/io/github/jhipster/online/domain/GitCompany.java @@ -20,15 +20,14 @@ package io.github.jhipster.online.domain; import com.fasterxml.jackson.annotation.JsonIgnore; -import org.hibernate.annotations.Cache; -import org.hibernate.annotations.CacheConcurrencyStrategy; - -import javax.persistence.*; -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Size; import java.io.Serializable; import java.util.List; import java.util.Objects; +import javax.persistence.*; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; +import org.hibernate.annotations.Cache; +import org.hibernate.annotations.CacheConcurrencyStrategy; /** * An authority (a security role) used by Spring Security. @@ -123,12 +122,21 @@ public int hashCode() { @Override public String toString() { - return "GitCompany{" + - "id=" + id + - ", name='" + name + '\'' + - ", user=" + user.getLogin() + - ", gitProvider='" + gitProvider + '\'' + - ", gitProjects=" + gitProjects.size() + - '}'; + return ( + "GitCompany{" + + "id=" + + id + + ", name='" + + name + + '\'' + + ", user=" + + user.getLogin() + + ", gitProvider='" + + gitProvider + + '\'' + + ", gitProjects=" + + gitProjects.size() + + '}' + ); } } diff --git a/src/main/java/io/github/jhipster/online/domain/Jdl.java b/src/main/java/io/github/jhipster/online/domain/Jdl.java index b85b70f4..e3c57358 100644 --- a/src/main/java/io/github/jhipster/online/domain/Jdl.java +++ b/src/main/java/io/github/jhipster/online/domain/Jdl.java @@ -19,12 +19,11 @@ package io.github.jhipster.online.domain; import com.fasterxml.jackson.annotation.JsonIgnore; - +import java.io.Serializable; +import java.util.Objects; import javax.persistence.*; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; -import java.io.Serializable; -import java.util.Objects; /** * A JDL. @@ -101,8 +100,6 @@ public int hashCode() { @Override public String toString() { - return "JdlMetadata{" + - "id=" + getId() + - "}"; + return "JdlMetadata{" + "id=" + getId() + "}"; } } diff --git a/src/main/java/io/github/jhipster/online/domain/JdlMetadata.java b/src/main/java/io/github/jhipster/online/domain/JdlMetadata.java index 7a22e74a..79412333 100644 --- a/src/main/java/io/github/jhipster/online/domain/JdlMetadata.java +++ b/src/main/java/io/github/jhipster/online/domain/JdlMetadata.java @@ -19,14 +19,13 @@ package io.github.jhipster.online.domain; import com.fasterxml.jackson.annotation.JsonIgnore; -import org.hibernate.annotations.Cache; -import org.hibernate.annotations.CacheConcurrencyStrategy; - -import javax.persistence.*; -import javax.validation.constraints.NotNull; import java.io.Serializable; import java.time.Instant; import java.util.Objects; +import javax.persistence.*; +import javax.validation.constraints.NotNull; +import org.hibernate.annotations.Cache; +import org.hibernate.annotations.CacheConcurrencyStrategy; /** * A JdlMetadata. @@ -122,6 +121,7 @@ public JdlMetadata user(User user) { public void setUser(User user) { this.user = user; } + // jhipster-needle-entity-add-getters-setters - Jhipster will add getters and setters here, do not remove @Override @@ -146,10 +146,6 @@ public int hashCode() { @Override public String toString() { - return "JdlMetadata{" + - "id=" + getId() + - ", name='" + getName() + "'" + - ", isPublic='" + isIsPublic() + "'" + - "}"; + return "JdlMetadata{" + "id=" + getId() + ", name='" + getName() + "'" + ", isPublic='" + isIsPublic() + "'" + "}"; } } diff --git a/src/main/java/io/github/jhipster/online/domain/PersistentAuditEvent.java b/src/main/java/io/github/jhipster/online/domain/PersistentAuditEvent.java index d75ad982..d410d618 100644 --- a/src/main/java/io/github/jhipster/online/domain/PersistentAuditEvent.java +++ b/src/main/java/io/github/jhipster/online/domain/PersistentAuditEvent.java @@ -18,12 +18,12 @@ */ package io.github.jhipster.online.domain; -import javax.persistence.*; -import javax.validation.constraints.NotNull; import java.io.Serializable; import java.time.Instant; import java.util.HashMap; import java.util.Map; +import javax.persistence.*; +import javax.validation.constraints.NotNull; /** * Persist AuditEvent managed by the Spring Boot actuator. @@ -54,7 +54,7 @@ public class PersistentAuditEvent implements Serializable { @ElementCollection @MapKeyColumn(name = "name") @Column(name = "value") - @CollectionTable(name = "jhi_persistent_audit_evt_data", joinColumns=@JoinColumn(name="event_id")) + @CollectionTable(name = "jhi_persistent_audit_evt_data", joinColumns = @JoinColumn(name = "event_id")) private Map data = new HashMap<>(); public Long getId() { @@ -115,10 +115,17 @@ public int hashCode() { @Override public String toString() { - return "PersistentAuditEvent{" + - "principal='" + principal + '\'' + - ", auditEventDate=" + auditEventDate + - ", auditEventType='" + auditEventType + '\'' + - '}'; + return ( + "PersistentAuditEvent{" + + "principal='" + + principal + + '\'' + + ", auditEventDate=" + + auditEventDate + + ", auditEventType='" + + auditEventType + + '\'' + + '}' + ); } } diff --git a/src/main/java/io/github/jhipster/online/domain/SubGenEvent.java b/src/main/java/io/github/jhipster/online/domain/SubGenEvent.java index b70e8f53..d402e577 100644 --- a/src/main/java/io/github/jhipster/online/domain/SubGenEvent.java +++ b/src/main/java/io/github/jhipster/online/domain/SubGenEvent.java @@ -21,13 +21,12 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import io.github.jhipster.online.domain.interfaces.CompleteDate; -import org.hibernate.annotations.Cache; -import org.hibernate.annotations.CacheConcurrencyStrategy; - -import javax.persistence.*; import java.io.Serializable; import java.time.Instant; import java.util.Objects; +import javax.persistence.*; +import org.hibernate.annotations.Cache; +import org.hibernate.annotations.CacheConcurrencyStrategy; /** * A SubGenEvent. @@ -212,6 +211,7 @@ public SubGenEvent owner(GeneratorIdentity generatorIdentity) { public void setOwner(GeneratorIdentity generatorIdentity) { this.owner = generatorIdentity; } + // jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove @Override @@ -236,17 +236,33 @@ public int hashCode() { @Override public String toString() { - return "SubGenEvent{" + - "id=" + getId() + - ", year=" + getYear() + - ", month=" + getMonth() + - ", week=" + getWeek() + - ", day=" + getDay() + - ", hour=" + getHour() + - ", source='" + getSource() + "'" + - ", type='" + getType() + "'" + - ", event='" + getEvent() + "'" + - ", date='" + getDate() + "'" + - "}"; + return ( + "SubGenEvent{" + + "id=" + + getId() + + ", year=" + + getYear() + + ", month=" + + getMonth() + + ", week=" + + getWeek() + + ", day=" + + getDay() + + ", hour=" + + getHour() + + ", source='" + + getSource() + + "'" + + ", type='" + + getType() + + "'" + + ", event='" + + getEvent() + + "'" + + ", date='" + + getDate() + + "'" + + "}" + ); } } diff --git a/src/main/java/io/github/jhipster/online/domain/User.java b/src/main/java/io/github/jhipster/online/domain/User.java index 034b5b5b..e4d447ef 100644 --- a/src/main/java/io/github/jhipster/online/domain/User.java +++ b/src/main/java/io/github/jhipster/online/domain/User.java @@ -21,21 +21,20 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import io.github.jhipster.online.config.Constants; -import org.apache.commons.lang3.StringUtils; -import org.hibernate.annotations.BatchSize; -import org.hibernate.annotations.Cache; -import org.hibernate.annotations.CacheConcurrencyStrategy; - -import javax.persistence.*; -import javax.validation.constraints.Email; -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Pattern; -import javax.validation.constraints.Size; import java.io.Serializable; import java.time.Instant; import java.util.HashSet; import java.util.Locale; import java.util.Set; +import javax.persistence.*; +import javax.validation.constraints.Email; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Pattern; +import javax.validation.constraints.Size; +import org.apache.commons.lang3.StringUtils; +import org.hibernate.annotations.BatchSize; +import org.hibernate.annotations.Cache; +import org.hibernate.annotations.CacheConcurrencyStrategy; /** * A user. @@ -102,35 +101,35 @@ public class User extends AbstractAuditingEntity implements Serializable { private Instant resetDate = null; @JsonIgnore - @Column(name ="github_company") + @Column(name = "github_company") private String githubCompany = null; @JsonIgnore - @Column(name ="github_location") + @Column(name = "github_location") private String githubLocation = null; @JsonIgnore - @Column(name ="gitlab_oauth_token") + @Column(name = "gitlab_oauth_token") private String gitlabOAuthToken; @JsonIgnore - @Column(name ="github_oauth_token") + @Column(name = "github_oauth_token") private String githubOAuthToken; @JsonIgnore - @Column(name ="gitlab_user") + @Column(name = "gitlab_user") private String gitlabUser; @JsonIgnore - @Column(name ="github_user") + @Column(name = "github_user") private String githubUser; @JsonIgnore - @Column(name ="github_email") + @Column(name = "github_email") private String githubEmail; @JsonIgnore - @Column(name ="gitlab_email") + @Column(name = "gitlab_email") private String gitlabEmail; @JsonIgnore @@ -142,8 +141,9 @@ public class User extends AbstractAuditingEntity implements Serializable { @ManyToMany @JoinTable( name = "jhi_user_authority", - joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id")}, - inverseJoinColumns = {@JoinColumn(name = "authority_name", referencedColumnName = "name")}) + joinColumns = { @JoinColumn(name = "user_id", referencedColumnName = "id") }, + inverseJoinColumns = { @JoinColumn(name = "authority_name", referencedColumnName = "name") } + ) @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) @BatchSize(size = 20) private Set authorities = new HashSet<>(); @@ -277,9 +277,13 @@ public void setGithubOAuthToken(String githubOAuthToken) { this.githubOAuthToken = githubOAuthToken; } - public String getGitlabUser() { return gitlabUser; } + public String getGitlabUser() { + return gitlabUser; + } - public void setGitlabUser(String gitlabUser) { this.gitlabUser = gitlabUser; } + public void setGitlabUser(String gitlabUser) { + this.gitlabUser = gitlabUser; + } public String getGithubUser() { return githubUser; @@ -331,15 +335,33 @@ public int hashCode() { @Override public String toString() { - return "User{" + - "login='" + login + '\'' + - ", firstName='" + firstName + '\'' + - ", lastName='" + lastName + '\'' + - ", email='" + email + '\'' + - ", imageUrl='" + imageUrl + '\'' + - ", activated='" + activated + '\'' + - ", langKey='" + langKey + '\'' + - ", activationKey='" + activationKey + '\'' + - "}"; + return ( + "User{" + + "login='" + + login + + '\'' + + ", firstName='" + + firstName + + '\'' + + ", lastName='" + + lastName + + '\'' + + ", email='" + + email + + '\'' + + ", imageUrl='" + + imageUrl + + '\'' + + ", activated='" + + activated + + '\'' + + ", langKey='" + + langKey + + '\'' + + ", activationKey='" + + activationKey + + '\'' + + "}" + ); } } diff --git a/src/main/java/io/github/jhipster/online/domain/YoRC.java b/src/main/java/io/github/jhipster/online/domain/YoRC.java index 6834ead5..ab562e8d 100644 --- a/src/main/java/io/github/jhipster/online/domain/YoRC.java +++ b/src/main/java/io/github/jhipster/online/domain/YoRC.java @@ -23,15 +23,14 @@ import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import io.github.jhipster.online.domain.deserializer.YoRCDeserializer; import io.github.jhipster.online.domain.interfaces.CompleteDate; -import org.hibernate.annotations.Cache; -import org.hibernate.annotations.CacheConcurrencyStrategy; - -import javax.persistence.*; import java.io.Serializable; import java.time.Instant; import java.util.HashSet; import java.util.Objects; import java.util.Set; +import javax.persistence.*; +import org.hibernate.annotations.Cache; +import org.hibernate.annotations.CacheConcurrencyStrategy; /** * A YoRC. @@ -708,6 +707,7 @@ public YoRC owner(GeneratorIdentity ownerIdentity) { public void setOwner(GeneratorIdentity ownerIdentity) { this.owner = ownerIdentity; } + // jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove @Override @@ -732,46 +732,120 @@ public int hashCode() { @Override public String toString() { - return "YoRC{" + - "id=" + getId() + - ", jhipsterVersion='" + getJhipsterVersion() + "'" + - ", creationDate='" + getCreationDate() + "'" + - ", gitProvider='" + getGitProvider() + "'" + - ", nodeVersion='" + getNodeVersion() + "'" + - ", os='" + getOs() + "'" + - ", arch='" + getArch() + "'" + - ", cpu='" + getCpu() + "'" + - ", cores='" + getCores() + "'" + - ", memory='" + getMemory() + "'" + - ", userLanguage='" + getUserLanguage() + "'" + - ", year=" + getYear() + - ", month=" + getMonth() + - ", week=" + getWeek() + - ", day=" + getDay() + - ", hour=" + getHour() + - ", serverPort='" + getServerPort() + "'" + - ", authenticationType='" + getAuthenticationType() + "'" + - ", cacheProvider='" + getCacheProvider() + "'" + - ", enableHibernateCache='" + isEnableHibernateCache() + "'" + - ", websocket='" + isWebsocket() + "'" + - ", databaseType='" + getDatabaseType() + "'" + - ", devDatabaseType='" + getDevDatabaseType() + "'" + - ", prodDatabaseType='" + getProdDatabaseType() + "'" + - ", searchEngine='" + isSearchEngine() + "'" + - ", messageBroker='" + isMessageBroker() + "'" + - ", serviceDiscoveryType='" + isServiceDiscoveryType() + "'" + - ", buildTool='" + getBuildTool() + "'" + - ", enableSwaggerCodegen='" + isEnableSwaggerCodegen() + "'" + - ", clientFramework='" + getClientFramework() + "'" + - ", useSass='" + isUseSass() + "'" + - ", clientPackageManager='" + getClientPackageManager() + "'" + - ", applicationType='" + getApplicationType() + "'" + - ", jhiPrefix='" + getJhiPrefix() + "'" + - ", enableTranslation='" + isEnableTranslation() + "'" + - ", nativeLanguage='" + getNativeLanguage() + "'" + - ", hasProtractor='" + isHasProtractor() + "'" + - ", hasGatling='" + isHasGatling() + "'" + - ", hasCucumber='" + isHasCucumber() + "'" + - "}"; + return ( + "YoRC{" + + "id=" + + getId() + + ", jhipsterVersion='" + + getJhipsterVersion() + + "'" + + ", creationDate='" + + getCreationDate() + + "'" + + ", gitProvider='" + + getGitProvider() + + "'" + + ", nodeVersion='" + + getNodeVersion() + + "'" + + ", os='" + + getOs() + + "'" + + ", arch='" + + getArch() + + "'" + + ", cpu='" + + getCpu() + + "'" + + ", cores='" + + getCores() + + "'" + + ", memory='" + + getMemory() + + "'" + + ", userLanguage='" + + getUserLanguage() + + "'" + + ", year=" + + getYear() + + ", month=" + + getMonth() + + ", week=" + + getWeek() + + ", day=" + + getDay() + + ", hour=" + + getHour() + + ", serverPort='" + + getServerPort() + + "'" + + ", authenticationType='" + + getAuthenticationType() + + "'" + + ", cacheProvider='" + + getCacheProvider() + + "'" + + ", enableHibernateCache='" + + isEnableHibernateCache() + + "'" + + ", websocket='" + + isWebsocket() + + "'" + + ", databaseType='" + + getDatabaseType() + + "'" + + ", devDatabaseType='" + + getDevDatabaseType() + + "'" + + ", prodDatabaseType='" + + getProdDatabaseType() + + "'" + + ", searchEngine='" + + isSearchEngine() + + "'" + + ", messageBroker='" + + isMessageBroker() + + "'" + + ", serviceDiscoveryType='" + + isServiceDiscoveryType() + + "'" + + ", buildTool='" + + getBuildTool() + + "'" + + ", enableSwaggerCodegen='" + + isEnableSwaggerCodegen() + + "'" + + ", clientFramework='" + + getClientFramework() + + "'" + + ", useSass='" + + isUseSass() + + "'" + + ", clientPackageManager='" + + getClientPackageManager() + + "'" + + ", applicationType='" + + getApplicationType() + + "'" + + ", jhiPrefix='" + + getJhiPrefix() + + "'" + + ", enableTranslation='" + + isEnableTranslation() + + "'" + + ", nativeLanguage='" + + getNativeLanguage() + + "'" + + ", hasProtractor='" + + isHasProtractor() + + "'" + + ", hasGatling='" + + isHasGatling() + + "'" + + ", hasCucumber='" + + isHasCucumber() + + "'" + + "}" + ); } } diff --git a/src/main/java/io/github/jhipster/online/domain/deserializer/YoRCDeserializer.java b/src/main/java/io/github/jhipster/online/domain/deserializer/YoRCDeserializer.java index c288c286..15dfcc14 100644 --- a/src/main/java/io/github/jhipster/online/domain/deserializer/YoRCDeserializer.java +++ b/src/main/java/io/github/jhipster/online/domain/deserializer/YoRCDeserializer.java @@ -6,7 +6,6 @@ import com.fasterxml.jackson.databind.deser.std.StdDeserializer; import com.fasterxml.jackson.databind.node.ArrayNode; import io.github.jhipster.online.domain.YoRC; - import java.io.IOException; import java.util.HashSet; import java.util.Set; @@ -59,12 +58,12 @@ public YoRC deserialize(JsonParser jp, DeserializationContext ctxt) throws IOExc hasCucumber = true; break; default: - // No action necessary as all possible cases are handled above + // No action necessary as all possible cases are handled above } } } - Set languages = getLanguagesFromArrayNode((ArrayNode)node.get("languages")); + Set languages = getLanguagesFromArrayNode((ArrayNode) node.get("languages")); return result .serverPort(serverPort) diff --git a/src/main/java/io/github/jhipster/online/domain/enums/EntityStatColumn.java b/src/main/java/io/github/jhipster/online/domain/enums/EntityStatColumn.java index 5ea8a918..9b2a037d 100644 --- a/src/main/java/io/github/jhipster/online/domain/enums/EntityStatColumn.java +++ b/src/main/java/io/github/jhipster/online/domain/enums/EntityStatColumn.java @@ -22,7 +22,6 @@ import io.github.jhipster.online.domain.interfaces.DatabaseColumn; public enum EntityStatColumn implements DatabaseColumn { - FIELDS("fields"), RELATIONSHIPS("relationships"), PAGINATION("pagination"), diff --git a/src/main/java/io/github/jhipster/online/domain/enums/GitProvider.java b/src/main/java/io/github/jhipster/online/domain/enums/GitProvider.java index 60b00fe2..af0d9de6 100644 --- a/src/main/java/io/github/jhipster/online/domain/enums/GitProvider.java +++ b/src/main/java/io/github/jhipster/online/domain/enums/GitProvider.java @@ -23,8 +23,8 @@ import java.util.Optional; public enum GitProvider { - - GITHUB("github"), GITLAB("gitlab"); + GITHUB("github"), + GITLAB("gitlab"); private final String value; @@ -37,8 +37,6 @@ public String getValue() { } public static Optional getGitProviderByValue(String value) { - return Arrays.stream(GitProvider.values()) - .filter(e -> e.value.equalsIgnoreCase(value)) - .findFirst(); + return Arrays.stream(GitProvider.values()).filter(e -> e.value.equalsIgnoreCase(value)).findFirst(); } } diff --git a/src/main/java/io/github/jhipster/online/domain/enums/SubGenEventType.java b/src/main/java/io/github/jhipster/online/domain/enums/SubGenEventType.java index c16c309a..1c02bcb9 100644 --- a/src/main/java/io/github/jhipster/online/domain/enums/SubGenEventType.java +++ b/src/main/java/io/github/jhipster/online/domain/enums/SubGenEventType.java @@ -47,12 +47,6 @@ public String getDatabaseValue() { } public static SubGenEventType[] getDeploymentTools() { - return new SubGenEventType[]{ - HEROKU, - CLOUDFOUNDRY, - AWS, - OPENSHIFT, - KUBERNETES - }; + return new SubGenEventType[] { HEROKU, CLOUDFOUNDRY, AWS, OPENSHIFT, KUBERNETES }; } } diff --git a/src/main/java/io/github/jhipster/online/domain/interfaces/CompleteDate.java b/src/main/java/io/github/jhipster/online/domain/interfaces/CompleteDate.java index 28a850dc..149084ea 100644 --- a/src/main/java/io/github/jhipster/online/domain/interfaces/CompleteDate.java +++ b/src/main/java/io/github/jhipster/online/domain/interfaces/CompleteDate.java @@ -1,7 +1,6 @@ package io.github.jhipster.online.domain.interfaces; public interface CompleteDate { - void setYear(Integer year); void setMonth(Integer month); @@ -29,5 +28,4 @@ public interface CompleteDate { CompleteDate day(Integer day); CompleteDate hour(Integer hour); - } diff --git a/src/main/java/io/github/jhipster/online/domain/interfaces/DatabaseColumn.java b/src/main/java/io/github/jhipster/online/domain/interfaces/DatabaseColumn.java index 0572f842..97d962b4 100644 --- a/src/main/java/io/github/jhipster/online/domain/interfaces/DatabaseColumn.java +++ b/src/main/java/io/github/jhipster/online/domain/interfaces/DatabaseColumn.java @@ -1,6 +1,5 @@ package io.github.jhipster.online.domain.interfaces; public interface DatabaseColumn { - String getDatabaseValue(); } diff --git a/src/main/java/io/github/jhipster/online/mdc/logging/MDCInterceptor.java b/src/main/java/io/github/jhipster/online/mdc/logging/MDCInterceptor.java index 73bc9714..10893917 100644 --- a/src/main/java/io/github/jhipster/online/mdc/logging/MDCInterceptor.java +++ b/src/main/java/io/github/jhipster/online/mdc/logging/MDCInterceptor.java @@ -20,14 +20,14 @@ package io.github.jhipster.online.mdc.logging; import io.github.jhipster.online.security.SecurityUtils; -import org.slf4j.MDC; -import org.springframework.web.servlet.AsyncHandlerInterceptor; - +import java.util.Optional; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import java.util.Optional; +import org.slf4j.MDC; +import org.springframework.web.servlet.AsyncHandlerInterceptor; public class MDCInterceptor implements AsyncHandlerInterceptor { + @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { Optional currentUser = SecurityUtils.getCurrentUserLogin(); diff --git a/src/main/java/io/github/jhipster/online/repository/AuthorityRepository.java b/src/main/java/io/github/jhipster/online/repository/AuthorityRepository.java index 370903fe..9fa4d087 100644 --- a/src/main/java/io/github/jhipster/online/repository/AuthorityRepository.java +++ b/src/main/java/io/github/jhipster/online/repository/AuthorityRepository.java @@ -24,5 +24,4 @@ /** * Spring Data JPA repository for the {@link Authority} entity. */ -public interface AuthorityRepository extends JpaRepository { -} +public interface AuthorityRepository extends JpaRepository {} diff --git a/src/main/java/io/github/jhipster/online/repository/CustomAuditEventRepository.java b/src/main/java/io/github/jhipster/online/repository/CustomAuditEventRepository.java index c2de36d7..f3dd7f07 100644 --- a/src/main/java/io/github/jhipster/online/repository/CustomAuditEventRepository.java +++ b/src/main/java/io/github/jhipster/online/repository/CustomAuditEventRepository.java @@ -21,6 +21,10 @@ import io.github.jhipster.online.config.Constants; import io.github.jhipster.online.config.audit.AuditEventConverter; import io.github.jhipster.online.domain.PersistentAuditEvent; +import java.time.Instant; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.actuate.audit.AuditEvent; @@ -29,11 +33,6 @@ import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; -import java.time.Instant; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - /** * An implementation of Spring Boot's {@link AuditEventRepository}. */ @@ -53,26 +52,28 @@ public class CustomAuditEventRepository implements AuditEventRepository { private final Logger log = LoggerFactory.getLogger(getClass()); - public CustomAuditEventRepository(PersistenceAuditEventRepository persistenceAuditEventRepository, - AuditEventConverter auditEventConverter) { - + public CustomAuditEventRepository( + PersistenceAuditEventRepository persistenceAuditEventRepository, + AuditEventConverter auditEventConverter + ) { this.persistenceAuditEventRepository = persistenceAuditEventRepository; this.auditEventConverter = auditEventConverter; } @Override public List find(String principal, Instant after, String type) { - Iterable persistentAuditEvents = - persistenceAuditEventRepository.findByPrincipalAndAuditEventDateAfterAndAuditEventType(principal, after, type); + Iterable persistentAuditEvents = persistenceAuditEventRepository.findByPrincipalAndAuditEventDateAfterAndAuditEventType( + principal, + after, + type + ); return auditEventConverter.convertToAuditEvent(persistentAuditEvents); } @Override @Transactional(propagation = Propagation.REQUIRES_NEW) public void add(AuditEvent event) { - if (!AUTHORIZATION_FAILURE.equals(event.getType()) && - !Constants.ANONYMOUS_USER.equals(event.getPrincipal())) { - + if (!AUTHORIZATION_FAILURE.equals(event.getType()) && !Constants.ANONYMOUS_USER.equals(event.getPrincipal())) { PersistentAuditEvent persistentAuditEvent = new PersistentAuditEvent(); persistentAuditEvent.setPrincipal(event.getPrincipal()); persistentAuditEvent.setAuditEventType(event.getType()); @@ -96,8 +97,12 @@ private Map truncate(Map data) { int length = value.length(); if (length > EVENT_DATA_COLUMN_MAX_LENGTH) { value = value.substring(0, EVENT_DATA_COLUMN_MAX_LENGTH); - log.warn("Event data for {} too long ({}) has been truncated to {}. Consider increasing column width.", - entry.getKey(), length, EVENT_DATA_COLUMN_MAX_LENGTH); + log.warn( + "Event data for {} too long ({}) has been truncated to {}. Consider increasing column width.", + entry.getKey(), + length, + EVENT_DATA_COLUMN_MAX_LENGTH + ); } } results.put(entry.getKey(), value); diff --git a/src/main/java/io/github/jhipster/online/repository/EntityStatsRepository.java b/src/main/java/io/github/jhipster/online/repository/EntityStatsRepository.java index 96c03a7a..13ffcdd1 100644 --- a/src/main/java/io/github/jhipster/online/repository/EntityStatsRepository.java +++ b/src/main/java/io/github/jhipster/online/repository/EntityStatsRepository.java @@ -24,7 +24,6 @@ import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; - /** * Spring Data repository for the EntityStats entity. */ diff --git a/src/main/java/io/github/jhipster/online/repository/GeneratorIdentityRepository.java b/src/main/java/io/github/jhipster/online/repository/GeneratorIdentityRepository.java index 09a010f2..4eeed300 100644 --- a/src/main/java/io/github/jhipster/online/repository/GeneratorIdentityRepository.java +++ b/src/main/java/io/github/jhipster/online/repository/GeneratorIdentityRepository.java @@ -21,24 +21,24 @@ import io.github.jhipster.online.domain.GeneratorIdentity; import io.github.jhipster.online.domain.User; +import java.util.List; +import java.util.Optional; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; -import java.util.List; -import java.util.Optional; - /** * Spring Data JPA repository for the GeneratorIdentity entity. */ @SuppressWarnings("unused") @Repository public interface GeneratorIdentityRepository extends JpaRepository { - Optional findFirstByGuidEquals(String guid); List findAllByOwner(User owner); - @Query("select generator_identity from GeneratorIdentity generator_identity where generator_identity.owner.login = ?#{principal.username}") + @Query( + "select generator_identity from GeneratorIdentity generator_identity where generator_identity.owner.login = ?#{principal.username}" + ) List findByOwnerIsCurrentUser(); } diff --git a/src/main/java/io/github/jhipster/online/repository/GitCompanyRepository.java b/src/main/java/io/github/jhipster/online/repository/GitCompanyRepository.java index c8b51100..f3b9ff48 100644 --- a/src/main/java/io/github/jhipster/online/repository/GitCompanyRepository.java +++ b/src/main/java/io/github/jhipster/online/repository/GitCompanyRepository.java @@ -21,17 +21,15 @@ import io.github.jhipster.online.domain.GitCompany; import io.github.jhipster.online.domain.User; +import java.util.Set; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; -import java.util.Set; - /** * Spring Data JPA repository for the GitCompany entity. */ @Repository public interface GitCompanyRepository extends JpaRepository { - Set findAllByUserAndGitProvider(User user, String gitProvider); void deleteAllByUserLoginAndGitProvider(String user, String gitProvider); diff --git a/src/main/java/io/github/jhipster/online/repository/JdlMetadataRepository.java b/src/main/java/io/github/jhipster/online/repository/JdlMetadataRepository.java index 637d09f4..56847abd 100644 --- a/src/main/java/io/github/jhipster/online/repository/JdlMetadataRepository.java +++ b/src/main/java/io/github/jhipster/online/repository/JdlMetadataRepository.java @@ -20,19 +20,17 @@ package io.github.jhipster.online.repository; import io.github.jhipster.online.domain.JdlMetadata; +import java.util.List; import org.springframework.data.domain.Sort; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; -import java.util.List; - /** * Spring Data JPA repository for the JdlMetadata entity. */ @SuppressWarnings("unused") @Repository public interface JdlMetadataRepository extends JpaRepository { - List findAllByUserLogin(String userLogin, Sort sort); List findAllByUserLogin(String userLogin); diff --git a/src/main/java/io/github/jhipster/online/repository/JdlRepository.java b/src/main/java/io/github/jhipster/online/repository/JdlRepository.java index 5f06b280..50479a1c 100644 --- a/src/main/java/io/github/jhipster/online/repository/JdlRepository.java +++ b/src/main/java/io/github/jhipster/online/repository/JdlRepository.java @@ -20,18 +20,16 @@ package io.github.jhipster.online.repository; import io.github.jhipster.online.domain.Jdl; +import java.util.Optional; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; -import java.util.Optional; - /** * Spring Data JPA repository for the Jdl entity. */ @SuppressWarnings("unused") @Repository public interface JdlRepository extends JpaRepository { - Optional findOneByJdlMetadataId(String id); void deleteAllByJdlMetadataId(String id); diff --git a/src/main/java/io/github/jhipster/online/repository/PersistenceAuditEventRepository.java b/src/main/java/io/github/jhipster/online/repository/PersistenceAuditEventRepository.java index 2db8a1e1..0f74f15c 100644 --- a/src/main/java/io/github/jhipster/online/repository/PersistenceAuditEventRepository.java +++ b/src/main/java/io/github/jhipster/online/repository/PersistenceAuditEventRepository.java @@ -19,18 +19,16 @@ package io.github.jhipster.online.repository; import io.github.jhipster.online.domain.PersistentAuditEvent; +import java.time.Instant; +import java.util.List; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; -import java.time.Instant; -import java.util.List; - /** * Spring Data JPA repository for the {@link PersistentAuditEvent} entity. */ public interface PersistenceAuditEventRepository extends JpaRepository { - List findByPrincipal(String principal); List findByPrincipalAndAuditEventDateAfterAndAuditEventType(String principal, Instant after, String type); diff --git a/src/main/java/io/github/jhipster/online/repository/SubGenEventRepository.java b/src/main/java/io/github/jhipster/online/repository/SubGenEventRepository.java index 9aac18b6..57e1312f 100644 --- a/src/main/java/io/github/jhipster/online/repository/SubGenEventRepository.java +++ b/src/main/java/io/github/jhipster/online/repository/SubGenEventRepository.java @@ -24,7 +24,6 @@ import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; - /** * Spring Data repository for the SubGenEvent entity. */ diff --git a/src/main/java/io/github/jhipster/online/repository/UserRepository.java b/src/main/java/io/github/jhipster/online/repository/UserRepository.java index c58fbfc1..33c391ea 100644 --- a/src/main/java/io/github/jhipster/online/repository/UserRepository.java +++ b/src/main/java/io/github/jhipster/online/repository/UserRepository.java @@ -19,6 +19,9 @@ package io.github.jhipster.online.repository; import io.github.jhipster.online.domain.User; +import java.time.Instant; +import java.util.List; +import java.util.Optional; import org.springframework.cache.annotation.Cacheable; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; @@ -26,16 +29,11 @@ import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; -import java.time.Instant; -import java.util.List; -import java.util.Optional; - /** * Spring Data JPA repository for the {@link User} entity. */ @Repository public interface UserRepository extends JpaRepository { - String USERS_BY_LOGIN_CACHE = "usersByLogin"; String USERS_BY_EMAIL_CACHE = "usersByEmail"; @@ -50,8 +48,6 @@ public interface UserRepository extends JpaRepository { Optional findOneByLogin(String login); - - @EntityGraph(attributePaths = "authorities") Optional findOneWithAuthoritiesById(Long id); diff --git a/src/main/java/io/github/jhipster/online/repository/YoRCRepository.java b/src/main/java/io/github/jhipster/online/repository/YoRCRepository.java index 0a3fd69e..ef97b241 100644 --- a/src/main/java/io/github/jhipster/online/repository/YoRCRepository.java +++ b/src/main/java/io/github/jhipster/online/repository/YoRCRepository.java @@ -30,7 +30,5 @@ @SuppressWarnings("unused") @Repository public interface YoRCRepository extends JpaRepository { - void deleteAllByOwner(GeneratorIdentity owner); - } diff --git a/src/main/java/io/github/jhipster/online/security/AuthoritiesConstants.java b/src/main/java/io/github/jhipster/online/security/AuthoritiesConstants.java index bc8acfd8..c7ee6135 100644 --- a/src/main/java/io/github/jhipster/online/security/AuthoritiesConstants.java +++ b/src/main/java/io/github/jhipster/online/security/AuthoritiesConstants.java @@ -29,6 +29,5 @@ public final class AuthoritiesConstants { public static final String ANONYMOUS = "ROLE_ANONYMOUS"; - private AuthoritiesConstants() { - } + private AuthoritiesConstants() {} } diff --git a/src/main/java/io/github/jhipster/online/security/DomainUserDetailsService.java b/src/main/java/io/github/jhipster/online/security/DomainUserDetailsService.java index 2e5394da..d767a4b3 100644 --- a/src/main/java/io/github/jhipster/online/security/DomainUserDetailsService.java +++ b/src/main/java/io/github/jhipster/online/security/DomainUserDetailsService.java @@ -20,6 +20,9 @@ import io.github.jhipster.online.domain.User; import io.github.jhipster.online.repository.UserRepository; +import java.util.List; +import java.util.Locale; +import java.util.stream.Collectors; import org.hibernate.validator.internal.constraintvalidators.hv.EmailValidator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -31,10 +34,6 @@ import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; -import java.util.List; -import java.util.Locale; -import java.util.stream.Collectors; - /** * Authenticate a user from the database. */ @@ -55,27 +54,28 @@ public UserDetails loadUserByUsername(final String login) { log.debug("Authenticating {}", login); if (new EmailValidator().isValid(login, null)) { - return userRepository.findOneWithAuthoritiesByEmailIgnoreCase(login) + return userRepository + .findOneWithAuthoritiesByEmailIgnoreCase(login) .map(user -> createSpringSecurityUser(login, user)) .orElseThrow(() -> new UsernameNotFoundException("User with email " + login + " was not found in the database")); } String lowercaseLogin = login.toLowerCase(Locale.ENGLISH); - return userRepository.findOneWithAuthoritiesByLogin(lowercaseLogin) + return userRepository + .findOneWithAuthoritiesByLogin(lowercaseLogin) .map(user -> createSpringSecurityUser(lowercaseLogin, user)) .orElseThrow(() -> new UsernameNotFoundException("User " + lowercaseLogin + " was not found in the database")); - } private org.springframework.security.core.userdetails.User createSpringSecurityUser(String lowercaseLogin, User user) { if (!user.getActivated()) { throw new UserNotActivatedException("User " + lowercaseLogin + " was not activated"); } - List grantedAuthorities = user.getAuthorities().stream() + List grantedAuthorities = user + .getAuthorities() + .stream() .map(authority -> new SimpleGrantedAuthority(authority.getName())) .collect(Collectors.toList()); - return new org.springframework.security.core.userdetails.User(user.getLogin(), - user.getPassword(), - grantedAuthorities); + return new org.springframework.security.core.userdetails.User(user.getLogin(), user.getPassword(), grantedAuthorities); } } diff --git a/src/main/java/io/github/jhipster/online/security/SecurityUtils.java b/src/main/java/io/github/jhipster/online/security/SecurityUtils.java index 03428f77..a0a0bffe 100644 --- a/src/main/java/io/github/jhipster/online/security/SecurityUtils.java +++ b/src/main/java/io/github/jhipster/online/security/SecurityUtils.java @@ -18,22 +18,20 @@ */ package io.github.jhipster.online.security; +import java.util.Optional; +import java.util.stream.Stream; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; -import java.util.Optional; -import java.util.stream.Stream; - /** * Utility class for Spring Security. */ public final class SecurityUtils { - private SecurityUtils() { - } + private SecurityUtils() {} /** * Get the login of the current user. @@ -57,7 +55,6 @@ private static String extractPrincipal(Authentication authentication) { return null; } - /** * Get the JWT of the current user. * @@ -65,7 +62,8 @@ private static String extractPrincipal(Authentication authentication) { */ public static Optional getCurrentUserJWT() { SecurityContext securityContext = SecurityContextHolder.getContext(); - return Optional.ofNullable(securityContext.getAuthentication()) + return Optional + .ofNullable(securityContext.getAuthentication()) .filter(authentication -> authentication.getCredentials() instanceof String) .map(authentication -> (String) authentication.getCredentials()); } @@ -77,8 +75,7 @@ public static Optional getCurrentUserJWT() { */ public static boolean isAuthenticated() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); - return authentication != null && - getAuthorities(authentication).noneMatch(AuthoritiesConstants.ANONYMOUS::equals); + return authentication != null && getAuthorities(authentication).noneMatch(AuthoritiesConstants.ANONYMOUS::equals); } /** @@ -91,13 +88,10 @@ public static boolean isAuthenticated() { */ public static boolean isCurrentUserInRole(String authority) { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); - return authentication != null && - getAuthorities(authentication).anyMatch(authority::equals); + return authentication != null && getAuthorities(authentication).anyMatch(authority::equals); } private static Stream getAuthorities(Authentication authentication) { - return authentication.getAuthorities().stream() - .map(GrantedAuthority::getAuthority); + return authentication.getAuthorities().stream().map(GrantedAuthority::getAuthority); } - } diff --git a/src/main/java/io/github/jhipster/online/security/SpringSecurityAuditorAware.java b/src/main/java/io/github/jhipster/online/security/SpringSecurityAuditorAware.java index 95d99ef1..a9dfba95 100644 --- a/src/main/java/io/github/jhipster/online/security/SpringSecurityAuditorAware.java +++ b/src/main/java/io/github/jhipster/online/security/SpringSecurityAuditorAware.java @@ -19,11 +19,10 @@ package io.github.jhipster.online.security; import io.github.jhipster.online.config.Constants; +import java.util.Optional; import org.springframework.data.domain.AuditorAware; import org.springframework.stereotype.Component; -import java.util.Optional; - /** * Implementation of {@link AuditorAware} based on Spring Security. */ diff --git a/src/main/java/io/github/jhipster/online/security/jwt/JWTFilter.java b/src/main/java/io/github/jhipster/online/security/jwt/JWTFilter.java index cbd79aaa..8a70374e 100644 --- a/src/main/java/io/github/jhipster/online/security/jwt/JWTFilter.java +++ b/src/main/java/io/github/jhipster/online/security/jwt/JWTFilter.java @@ -18,17 +18,16 @@ */ package io.github.jhipster.online.security.jwt; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.util.StringUtils; -import org.springframework.web.filter.GenericFilterBean; - +import java.io.IOException; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; -import java.io.IOException; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.util.StringUtils; +import org.springframework.web.filter.GenericFilterBean; /** * Filters incoming requests and installs a Spring Security principal if a header corresponding to a valid user is diff --git a/src/main/java/io/github/jhipster/online/security/jwt/TokenProvider.java b/src/main/java/io/github/jhipster/online/security/jwt/TokenProvider.java index 24f65f12..c4d99fdc 100644 --- a/src/main/java/io/github/jhipster/online/security/jwt/TokenProvider.java +++ b/src/main/java/io/github/jhipster/online/security/jwt/TokenProvider.java @@ -22,6 +22,12 @@ import io.jsonwebtoken.*; import io.jsonwebtoken.io.Decoders; import io.jsonwebtoken.security.Keys; +import java.nio.charset.StandardCharsets; +import java.security.Key; +import java.util.Arrays; +import java.util.Collection; +import java.util.Date; +import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; @@ -32,13 +38,6 @@ import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; -import java.nio.charset.StandardCharsets; -import java.security.Key; -import java.util.Arrays; -import java.util.Collection; -import java.util.Date; -import java.util.stream.Collectors; - @Component public class TokenProvider { @@ -58,8 +57,10 @@ public TokenProvider(JHipsterProperties jHipsterProperties) { byte[] keyBytes; String secret = jHipsterProperties.getSecurity().getAuthentication().getJwt().getSecret(); if (!StringUtils.isEmpty(secret)) { - log.warn("Warning: the JWT key used is not Base64-encoded. " + - "We recommend using the `jhipster.security.authentication.jwt.base64-secret` key for optimum security."); + log.warn( + "Warning: the JWT key used is not Base64-encoded. " + + "We recommend using the `jhipster.security.authentication.jwt.base64-secret` key for optimum security." + ); keyBytes = secret.getBytes(StandardCharsets.UTF_8); } else { log.debug("Using a Base64-encoded JWT secret key"); @@ -67,17 +68,13 @@ public TokenProvider(JHipsterProperties jHipsterProperties) { } key = Keys.hmacShaKeyFor(keyBytes); jwtParser = Jwts.parserBuilder().setSigningKey(key).build(); - this.tokenValidityInMilliseconds = - 1000 * jHipsterProperties.getSecurity().getAuthentication().getJwt().getTokenValidityInSeconds(); + this.tokenValidityInMilliseconds = 1000 * jHipsterProperties.getSecurity().getAuthentication().getJwt().getTokenValidityInSeconds(); this.tokenValidityInMillisecondsForRememberMe = - 1000 * jHipsterProperties.getSecurity().getAuthentication().getJwt() - .getTokenValidityInSecondsForRememberMe(); + 1000 * jHipsterProperties.getSecurity().getAuthentication().getJwt().getTokenValidityInSecondsForRememberMe(); } public String createToken(Authentication authentication, boolean rememberMe) { - String authorities = authentication.getAuthorities().stream() - .map(GrantedAuthority::getAuthority) - .collect(Collectors.joining(",")); + String authorities = authentication.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.joining(",")); long now = (new Date()).getTime(); Date validity; @@ -87,7 +84,8 @@ public String createToken(Authentication authentication, boolean rememberMe) { validity = new Date(now + this.tokenValidityInMilliseconds); } - return Jwts.builder() + return Jwts + .builder() .setSubject(authentication.getName()) .claim(AUTHORITIES_KEY, authorities) .signWith(key, SignatureAlgorithm.HS512) @@ -98,10 +96,10 @@ public String createToken(Authentication authentication, boolean rememberMe) { public Authentication getAuthentication(String token) { Claims claims = jwtParser.parseClaimsJws(token).getBody(); - Collection authorities = - Arrays.stream(claims.get(AUTHORITIES_KEY).toString().split(",")) - .map(SimpleGrantedAuthority::new) - .collect(Collectors.toList()); + Collection authorities = Arrays + .stream(claims.get(AUTHORITIES_KEY).toString().split(",")) + .map(SimpleGrantedAuthority::new) + .collect(Collectors.toList()); User principal = new User(claims.getSubject(), "", authorities); diff --git a/src/main/java/io/github/jhipster/online/service/AuditEventService.java b/src/main/java/io/github/jhipster/online/service/AuditEventService.java index f03f5310..3ff19502 100644 --- a/src/main/java/io/github/jhipster/online/service/AuditEventService.java +++ b/src/main/java/io/github/jhipster/online/service/AuditEventService.java @@ -22,6 +22,9 @@ import io.github.jhipster.config.JHipsterProperties; import io.github.jhipster.online.config.audit.AuditEventConverter; import io.github.jhipster.online.repository.PersistenceAuditEventRepository; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.actuate.audit.AuditEvent; @@ -31,10 +34,6 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import java.time.Instant; -import java.time.temporal.ChronoUnit; -import java.util.Optional; - /** * Service for managing audit events. *

@@ -54,8 +53,9 @@ public class AuditEventService { public AuditEventService( PersistenceAuditEventRepository persistenceAuditEventRepository, - AuditEventConverter auditEventConverter, JHipsterProperties jhipsterProperties) { - + AuditEventConverter auditEventConverter, + JHipsterProperties jhipsterProperties + ) { this.persistenceAuditEventRepository = persistenceAuditEventRepository; this.auditEventConverter = auditEventConverter; this.jHipsterProperties = jhipsterProperties; @@ -70,24 +70,25 @@ public AuditEventService( public void removeOldAuditEvents() { persistenceAuditEventRepository .findByAuditEventDateBefore(Instant.now().minus(jHipsterProperties.getAuditEvents().getRetentionPeriod(), ChronoUnit.DAYS)) - .forEach(auditEvent -> { - log.debug("Deleting audit data {}", auditEvent); - persistenceAuditEventRepository.delete(auditEvent); - }); + .forEach( + auditEvent -> { + log.debug("Deleting audit data {}", auditEvent); + persistenceAuditEventRepository.delete(auditEvent); + } + ); } public Page findAll(Pageable pageable) { - return persistenceAuditEventRepository.findAll(pageable) - .map(auditEventConverter::convertToAuditEvent); + return persistenceAuditEventRepository.findAll(pageable).map(auditEventConverter::convertToAuditEvent); } public Page findByDates(Instant fromDate, Instant toDate, Pageable pageable) { - return persistenceAuditEventRepository.findAllByAuditEventDateBetween(fromDate, toDate, pageable) + return persistenceAuditEventRepository + .findAllByAuditEventDateBetween(fromDate, toDate, pageable) .map(auditEventConverter::convertToAuditEvent); } public Optional find(Long id) { - return persistenceAuditEventRepository.findById(id) - .map(auditEventConverter::convertToAuditEvent); + return persistenceAuditEventRepository.findById(id).map(auditEventConverter::convertToAuditEvent); } } diff --git a/src/main/java/io/github/jhipster/online/service/CiCdService.java b/src/main/java/io/github/jhipster/online/service/CiCdService.java index 3ef3c4c7..6b24dfa1 100644 --- a/src/main/java/io/github/jhipster/online/service/CiCdService.java +++ b/src/main/java/io/github/jhipster/online/service/CiCdService.java @@ -23,6 +23,7 @@ import io.github.jhipster.online.domain.User; import io.github.jhipster.online.domain.enums.GitProvider; import io.github.jhipster.online.service.enums.CiCdTool; +import java.io.File; import org.apache.commons.io.FileUtils; import org.eclipse.jgit.api.Git; import org.slf4j.Logger; @@ -30,8 +31,6 @@ import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; -import java.io.File; - @Service public class CiCdService { @@ -49,12 +48,14 @@ public class CiCdService { private final ApplicationProperties applicationProperties; - public CiCdService(LogsService logsService, + public CiCdService( + LogsService logsService, GitService gitService, GithubService githubService, GitlabService gitlabService, JHipsterService jHipsterService, - ApplicationProperties applicationProperties) { + ApplicationProperties applicationProperties + ) { this.logsService = logsService; this.gitService = gitService; this.githubService = githubService; @@ -67,16 +68,23 @@ public CiCdService(LogsService logsService, * Apply a CI-CD configuration to an existing repository. */ @Async - public void configureCiCd(User user, String organizationName, String projectName, CiCdTool ciCdTool, String ciCdId, - GitProvider gitProvider) { + public void configureCiCd( + User user, + String organizationName, + String projectName, + CiCdTool ciCdTool, + String ciCdId, + GitProvider gitProvider + ) { try { log.info("Beginning to configure CI with {} to {} / {}", ciCdTool, organizationName, projectName); boolean isGitHub = gitProvider.equals(GitProvider.GITHUB); - this.logsService.addLog(ciCdId, "Cloning " + (isGitHub ? "GitHub" : "GitLab") + " repository `" + - organizationName + "/" + projectName + "`"); + this.logsService.addLog( + ciCdId, + "Cloning " + (isGitHub ? "GitHub" : "GitLab") + " repository `" + organizationName + "/" + projectName + "`" + ); - File workingDir = new File(applicationProperties.getTmpFolder() + "/jhipster/applications/" + - ciCdId); + File workingDir = new File(applicationProperties.getTmpFolder() + "/jhipster/applications/" + ciCdId); FileUtils.forceMkdir(workingDir); Git git = this.gitService.cloneRepository(user, workingDir, organizationName, projectName, gitProvider); @@ -89,12 +97,12 @@ public void configureCiCd(User user, String organizationName, String projectName this.jHipsterService.addCiCd(ciCdId, workingDir, ciCdTool); this.gitService.addAllFilesToRepository(git, workingDir); - this.gitService.commit(git, workingDir, "Configure " + - ciCdTool.capitalize() + - " Continuous Integration"); + this.gitService.commit(git, workingDir, "Configure " + ciCdTool.capitalize() + " Continuous Integration"); - this.logsService.addLog(ciCdId, "Pushing the application to the " + (isGitHub ? "GitHub" : "GitLab") + " " + - "remote repository"); + this.logsService.addLog( + ciCdId, + "Pushing the application to the " + (isGitHub ? "GitHub" : "GitLab") + " " + "remote repository" + ); this.gitService.push(git, workingDir, user, organizationName, projectName, gitProvider); this.logsService.addLog(ciCdId, "Application successfully pushed!"); this.logsService.addLog(ciCdId, "Creating " + (isGitHub ? "Pull" : "Merge") + " Request"); @@ -104,29 +112,46 @@ public void configureCiCd(User user, String organizationName, String projectName if (isGitHub) { int pullRequestNumber = - this.githubService.createPullRequest(user, organizationName, projectName, pullRequestTitle, - branchName, pullRequestBody); - this.logsService.addLog(ciCdId, "Pull Request created at " + applicationProperties.getGitlab() - .getHost() + - "/" + - organizationName + - "/" + - projectName + - "/pull/" + - pullRequestNumber - ); + this.githubService.createPullRequest( + user, + organizationName, + projectName, + pullRequestTitle, + branchName, + pullRequestBody + ); + this.logsService.addLog( + ciCdId, + "Pull Request created at " + + applicationProperties.getGitlab().getHost() + + "/" + + organizationName + + "/" + + projectName + + "/pull/" + + pullRequestNumber + ); } else if (gitProvider.equals(GitProvider.GITLAB)) { int pullRequestNumber = - this.gitlabService.createPullRequest(user, organizationName, projectName, pullRequestTitle, - branchName, pullRequestBody); - this.logsService.addLog(ciCdId, "Pull Request created at " + gitlabService.getHost() + - "/" + - organizationName + - "/" + - projectName + - "/merge_requests/" + - pullRequestNumber - ); + this.gitlabService.createPullRequest( + user, + organizationName, + projectName, + pullRequestTitle, + branchName, + pullRequestBody + ); + this.logsService.addLog( + ciCdId, + "Pull Request created at " + + gitlabService.getHost() + + "/" + + organizationName + + "/" + + projectName + + "/merge_requests/" + + pullRequestNumber + ); } this.gitService.cleanUpDirectory(workingDir); diff --git a/src/main/java/io/github/jhipster/online/service/EmailAlreadyUsedException.java b/src/main/java/io/github/jhipster/online/service/EmailAlreadyUsedException.java index a2078ab0..d3f05ce0 100644 --- a/src/main/java/io/github/jhipster/online/service/EmailAlreadyUsedException.java +++ b/src/main/java/io/github/jhipster/online/service/EmailAlreadyUsedException.java @@ -7,5 +7,4 @@ public class EmailAlreadyUsedException extends RuntimeException { public EmailAlreadyUsedException() { super("Email is already in use!"); } - } diff --git a/src/main/java/io/github/jhipster/online/service/EntityStatsService.java b/src/main/java/io/github/jhipster/online/service/EntityStatsService.java index 312a5567..9730fe3c 100644 --- a/src/main/java/io/github/jhipster/online/service/EntityStatsService.java +++ b/src/main/java/io/github/jhipster/online/service/EntityStatsService.java @@ -28,19 +28,18 @@ import io.github.jhipster.online.service.enums.TemporalValueType; import io.github.jhipster.online.service.mapper.EntityStatsMapper; import io.github.jhipster.online.service.util.QueryUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - +import java.time.Instant; +import java.util.List; +import java.util.Optional; import javax.persistence.EntityManager; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.ParameterExpression; import javax.persistence.criteria.Root; -import java.time.Instant; -import java.util.List; -import java.util.Optional; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; /** * Service Implementation for managing EntityStats. @@ -57,7 +56,11 @@ public class EntityStatsService { private final EntityStatsMapper entityStatsMapper; - public EntityStatsService(EntityStatsRepository entityStatsRepository, EntityManager entityManager, EntityStatsMapper entityStatsMapper) { + public EntityStatsService( + EntityStatsRepository entityStatsRepository, + EntityManager entityManager, + EntityStatsMapper entityStatsMapper + ) { this.entityStatsRepository = entityStatsRepository; this.entityManager = entityManager; this.entityStatsMapper = entityStatsMapper; @@ -87,7 +90,6 @@ public List findAll() { return entityStatsRepository.findAll(); } - /** * Get one entityStats by id. * @@ -121,7 +123,8 @@ public List getCount(Instant after, TemporalValueType dbTempor Root root = query.from(EntityStats.class); ParameterExpression parameter = builder.parameter(Instant.class, QueryUtil.DATE); - query.select(builder.construct(RawSQL.class, root.get(dbTemporalFunction.getFieldName()), builder.count(root))) + query + .select(builder.construct(RawSQL.class, root.get(dbTemporalFunction.getFieldName()), builder.count(root))) .where(builder.greaterThan(root.get(EntityStats_.date).as(Instant.class), parameter)) .groupBy(root.get(dbTemporalFunction.getFieldName())); @@ -134,7 +137,15 @@ public List getFieldCount(Instant after, EntityStatColu Root root = query.from(EntityStats.class); ParameterExpression parameter = builder.parameter(Instant.class, QueryUtil.DATE); - query.select(builder.construct(RawSQLField.class, root.get(dbTemporalFunction.getFieldName()), root.get(field.getDatabaseValue()).as(String.class), builder.count(root))) + query + .select( + builder.construct( + RawSQLField.class, + root.get(dbTemporalFunction.getFieldName()), + root.get(field.getDatabaseValue()).as(String.class), + builder.count(root) + ) + ) .where(builder.greaterThan(root.get(EntityStats_.date).as(Instant.class), parameter)) .groupBy(root.get(field.getDatabaseValue()), root.get(dbTemporalFunction.getFieldName())); diff --git a/src/main/java/io/github/jhipster/online/service/GeneratorIdentityService.java b/src/main/java/io/github/jhipster/online/service/GeneratorIdentityService.java index f6ee1a4e..21942b0a 100644 --- a/src/main/java/io/github/jhipster/online/service/GeneratorIdentityService.java +++ b/src/main/java/io/github/jhipster/online/service/GeneratorIdentityService.java @@ -24,6 +24,8 @@ import io.github.jhipster.online.repository.GeneratorIdentityRepository; import io.github.jhipster.online.service.dto.GeneratorIdentityDTO; import io.github.jhipster.online.service.mapper.GeneratorIdentityMapper; +import java.util.List; +import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.dao.DataIntegrityViolationException; @@ -31,9 +33,6 @@ import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; -import java.util.List; -import java.util.Optional; - /** * Service Implementation for managing GeneratorIdentity. */ @@ -47,7 +46,10 @@ public class GeneratorIdentityService { private final GeneratorIdentityMapper generatorIdentityMapper; - public GeneratorIdentityService(GeneratorIdentityRepository generatorIdentityRepository, GeneratorIdentityMapper generatorIdentityMapper) { + public GeneratorIdentityService( + GeneratorIdentityRepository generatorIdentityRepository, + GeneratorIdentityMapper generatorIdentityMapper + ) { this.generatorIdentityRepository = generatorIdentityRepository; this.generatorIdentityMapper = generatorIdentityMapper; } @@ -88,7 +90,6 @@ public List findAllOwned(User user) { return generatorIdentityRepository.findAllByOwner(user); } - /** * Get one generatorIdentity by id. * @@ -142,7 +143,7 @@ public boolean bindUserToGenerator(User user, String guid) { return false; } // Check if the generator has already an owner - if(generatorIdentity.get().getOwner() != null) { + if (generatorIdentity.get().getOwner() != null) { return false; } generatorIdentity.get().owner(user); @@ -157,7 +158,7 @@ public boolean unbindUserFromGenerator(User user, String guid) { return false; } - User owner = maybeGeneratorIdentity.get().getOwner(); + User owner = maybeGeneratorIdentity.get().getOwner(); if (owner == null || !owner.equals(user)) { return false; } diff --git a/src/main/java/io/github/jhipster/online/service/GeneratorService.java b/src/main/java/io/github/jhipster/online/service/GeneratorService.java index a598d69a..e770e7ba 100644 --- a/src/main/java/io/github/jhipster/online/service/GeneratorService.java +++ b/src/main/java/io/github/jhipster/online/service/GeneratorService.java @@ -22,6 +22,10 @@ import io.github.jhipster.online.config.ApplicationProperties; import io.github.jhipster.online.domain.User; import io.github.jhipster.online.domain.enums.GitProvider; +import java.io.File; +import java.io.IOException; +import java.io.PrintWriter; +import java.net.URISyntaxException; import org.apache.commons.io.FileUtils; import org.eclipse.jgit.api.errors.GitAPIException; import org.slf4j.Logger; @@ -30,11 +34,6 @@ import org.springframework.util.StopWatch; import org.zeroturnaround.zip.ZipUtil; -import java.io.File; -import java.io.IOException; -import java.io.PrintWriter; -import java.net.URISyntaxException; - @Service public class GeneratorService { @@ -48,8 +47,13 @@ public class GeneratorService { private final LogsService logsService; - public GeneratorService(ApplicationProperties applicationProperties, GitService gitService, JHipsterService - jHipsterService, LogsService logsService, YoRCService yoRCService) { + public GeneratorService( + ApplicationProperties applicationProperties, + GitService gitService, + JHipsterService jHipsterService, + LogsService logsService, + YoRCService yoRCService + ) { this.applicationProperties = applicationProperties; this.gitService = gitService; this.jHipsterService = jHipsterService; @@ -66,9 +70,15 @@ public String generateZippedApplication(String applicationId, String application return workingDir + ".zip"; } - public void generateGitApplication(User user, String applicationId, - String applicationConfiguration, String githubOrganization, String repositoryName, - GitProvider gitProvider) throws IOException, GitAPIException, URISyntaxException { + public void generateGitApplication( + User user, + String applicationId, + String applicationConfiguration, + String githubOrganization, + String repositoryName, + GitProvider gitProvider + ) + throws IOException, GitAPIException, URISyntaxException { File workingDir = generateApplication(applicationId, applicationConfiguration); this.logsService.addLog(applicationId, "Pushing the application to the Git remote repository"); this.gitService.pushNewApplicationToGit(user, workingDir, githubOrganization, repositoryName, gitProvider); @@ -86,9 +96,7 @@ private File generateApplication(String applicationId, String applicationConfigu return workingDir; } - private void generateYoRc(String applicationId, File workingDir, String applicationConfiguration) - throws IOException { - + private void generateYoRc(String applicationId, File workingDir, String applicationConfiguration) throws IOException { this.logsService.addLog(applicationId, "Creating `.yo-rc.json` file"); try { PrintWriter writer = new PrintWriter(workingDir + "/.yo-rc.json", "UTF-8"); diff --git a/src/main/java/io/github/jhipster/online/service/GitService.java b/src/main/java/io/github/jhipster/online/service/GitService.java index a85dd655..e3d6f390 100644 --- a/src/main/java/io/github/jhipster/online/service/GitService.java +++ b/src/main/java/io/github/jhipster/online/service/GitService.java @@ -22,6 +22,9 @@ import io.github.jhipster.online.config.ApplicationProperties; import io.github.jhipster.online.domain.User; import io.github.jhipster.online.domain.enums.GitProvider; +import java.io.File; +import java.io.IOException; +import java.net.URISyntaxException; import org.apache.commons.io.FileUtils; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.RemoteAddCommand; @@ -34,10 +37,6 @@ import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; -import java.io.File; -import java.io.IOException; -import java.net.URISyntaxException; - @Service public class GitService { @@ -49,10 +48,8 @@ public GitService(ApplicationProperties applicationProperties) { this.applicationProperties = applicationProperties; } - public void pushNewApplicationToGit(User user, File workingDir, String organization, String applicationName, - GitProvider gitProvider) + public void pushNewApplicationToGit(User user, File workingDir, String organization, String applicationName, GitProvider gitProvider) throws GitAPIException, URISyntaxException { - log.info("Create Git repository for {}", workingDir); Git git = Git.init().setDirectory(workingDir).call(); @@ -64,8 +61,9 @@ public void pushNewApplicationToGit(User user, File workingDir, String organizat if (gitProvider.equals(GitProvider.GITHUB)) { urIish = new URIish(applicationProperties.getGithub().getHost() + "/" + organization + "/" + applicationName + ".git"); } else if (gitProvider.equals(GitProvider.GITLAB)) { - urIish = new URIish(applicationProperties.getGitlab().getHost() + "/" + organization + "/" + - applicationName + ".git").setPass(user.getGitlabOAuthToken()); + urIish = + new URIish(applicationProperties.getGitlab().getHost() + "/" + organization + "/" + applicationName + ".git") + .setPass(user.getGitlabOAuthToken()); } RemoteAddCommand remoteAddCommand = git.remoteAdd(); remoteAddCommand.setName("origin"); @@ -79,48 +77,43 @@ public void pushNewApplicationToGit(User user, File workingDir, String organizat public void addAllFilesToRepository(Git git, File workingDir) throws GitAPIException { log.debug("Adding all files to repository {}", workingDir); - git.add() - .addFilepattern(".") - .call(); + git.add().addFilepattern(".").call(); } public void commit(Git git, File workingDir, String message) throws GitAPIException { log.debug("Commiting all files to repository {}", workingDir); - git.commit() - .setCommitter("JHipster Bot", "jhipster-bot@jhipster.tech") - .setMessage(message) - .call(); + git.commit().setCommitter("JHipster Bot", "jhipster-bot@jhipster.tech").setMessage(message).call(); } - public void push(Git git, File workingDir, User user, String organization, String applicationName, GitProvider - gitProvider) throws - GitAPIException { + public void push(Git git, File workingDir, User user, String organization, String applicationName, GitProvider gitProvider) + throws GitAPIException { log.info("Pushing {} to {} / {} for user {}", workingDir, organization, applicationName, user); git.push().setCredentialsProvider(getCredentialProvider(user, gitProvider)).call(); } - public Git cloneRepository(User user, File workingDir, String organization, String applicationName, GitProvider - gitProvider) + public Git cloneRepository(User user, File workingDir, String organization, String applicationName, GitProvider gitProvider) throws GitAPIException { - log.debug("Cloning repository {} / {}", organization, applicationName); Git git = null; if (gitProvider.equals(GitProvider.GITLAB)) { - git = Git.cloneRepository() - .setURI(applicationProperties.getGitlab().getHost() + "/" + organization + "/" + applicationName + "" + - ".git") - .setDirectory(workingDir) - .setCredentialsProvider(getCredentialProvider(user, gitProvider)) - .setCloneAllBranches(false) - .call(); + git = + Git + .cloneRepository() + .setURI(applicationProperties.getGitlab().getHost() + "/" + organization + "/" + applicationName + "" + ".git") + .setDirectory(workingDir) + .setCredentialsProvider(getCredentialProvider(user, gitProvider)) + .setCloneAllBranches(false) + .call(); } else if (gitProvider.equals(GitProvider.GITHUB)) { - git = Git.cloneRepository() - .setURI(applicationProperties.getGithub().getHost() + "/" + organization + "/" + applicationName + ".git") - .setDirectory(workingDir) - .setCredentialsProvider(getCredentialProvider(user, gitProvider)) - .setCloneAllBranches(false) - .call(); + git = + Git + .cloneRepository() + .setURI(applicationProperties.getGithub().getHost() + "/" + organization + "/" + applicationName + ".git") + .setDirectory(workingDir) + .setCredentialsProvider(getCredentialProvider(user, gitProvider)) + .setCloneAllBranches(false) + .call(); } log.debug("Repository successfully cloned"); @@ -128,10 +121,7 @@ public Git cloneRepository(User user, File workingDir, String organization, Stri } public void createBranch(Git git, String branchName) throws GitAPIException { - git.checkout() - .setName(branchName) - .setCreateBranch(true) - .call(); + git.checkout().setName(branchName).setCreateBranch(true).call(); log.debug("Branch successfully created"); } @@ -161,11 +151,9 @@ public void cleanUpDirectory(File workingDir) throws IOException { private CredentialsProvider getCredentialProvider(User user, GitProvider gitProvider) { if (gitProvider.equals(GitProvider.GITHUB)) { - return new UsernamePasswordCredentialsProvider(user.getGithubUser(), - user.getGithubOAuthToken()); + return new UsernamePasswordCredentialsProvider(user.getGithubUser(), user.getGithubOAuthToken()); } else if (gitProvider.equals(GitProvider.GITLAB)) { - return new UsernamePasswordCredentialsProvider("oauth2", - user.getGitlabOAuthToken()); + return new UsernamePasswordCredentialsProvider("oauth2", user.getGitlabOAuthToken()); } return null; } diff --git a/src/main/java/io/github/jhipster/online/service/GithubService.java b/src/main/java/io/github/jhipster/online/service/GithubService.java index 11866d5a..f53bb162 100644 --- a/src/main/java/io/github/jhipster/online/service/GithubService.java +++ b/src/main/java/io/github/jhipster/online/service/GithubService.java @@ -27,6 +27,11 @@ import io.github.jhipster.online.repository.UserRepository; import io.github.jhipster.online.security.SecurityUtils; import io.github.jhipster.online.service.interfaces.GitProviderService; +import java.io.IOException; +import java.net.ConnectException; +import java.util.*; +import java.util.stream.Collectors; +import javax.annotation.PostConstruct; import org.kohsuke.github.GHCreateRepositoryBuilder; import org.kohsuke.github.GHMyself; import org.kohsuke.github.GHOrganization; @@ -37,12 +42,6 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import javax.annotation.PostConstruct; -import java.io.IOException; -import java.net.ConnectException; -import java.util.*; -import java.util.stream.Collectors; - @Service public class GithubService implements GitProviderService { @@ -58,11 +57,13 @@ public class GithubService implements GitProviderService { private final UserRepository userRepository; - public GithubService(GeneratorService generatorService, + public GithubService( + GeneratorService generatorService, LogsService logsService, ApplicationProperties applicationProperties, GitCompanyRepository gitCompanyRepository, - UserRepository userRepository) { + UserRepository userRepository + ) { this.generatorService = generatorService; this.applicationProperties = applicationProperties; this.logsService = logsService; @@ -76,16 +77,19 @@ public void init() { if (this.applicationProperties.getGithub().getHost().equals("https://github.com")) { log.warn("JHipster Online is configured to work on the public GitHub instance at https://github.com"); } else { - log.warn("JHipster Online is configured to work on a private GitHub instance at {}", this.applicationProperties.getGithub().getHost()); + log.warn( + "JHipster Online is configured to work on a private GitHub instance at {}", + this.applicationProperties.getGithub().getHost() + ); } } } @Override public boolean isEnabled() { - return - this.applicationProperties.getGithub().getClientId() != null && - this.applicationProperties.getGithub().getClientSecret() != null; + return ( + this.applicationProperties.getGithub().getClientId() != null && this.applicationProperties.getGithub().getClientSecret() != null + ); } @Override @@ -94,7 +98,9 @@ public String getHost() { } @Override - public String getClientId() { return applicationProperties.getGithub().getClientId(); } + public String getClientId() { + return applicationProperties.getGithub().getClientId(); + } /** * Sync User data from GitHub. @@ -125,19 +131,21 @@ public User getSyncedUserFromGitProvider(User user) { user.setGithubEmail(ghMyself.getEmail()); user.setGithubCompany(ghMyself.getCompany()); user.setGithubLocation(ghMyself.getLocation()); - Set currentGithubCompanies = - user.getGitCompanies().stream().filter(c -> c.getGitProvider().equals(GitProvider.GITHUB.getValue())).collect(Collectors.toSet()); + Set currentGithubCompanies = user + .getGitCompanies() + .stream() + .filter(c -> c.getGitProvider().equals(GitProvider.GITHUB.getValue())) + .collect(Collectors.toSet()); Set updatedGithubCompanies = new HashSet<>(); syncUserProjectsFromCompanies(user, gitHub, currentGithubCompanies, updatedGithubCompanies); user.setGitCompanies(updatedGithubCompanies); - List organizationsProjects = updatedGithubCompanies.stream() - .filter(o -> - o.getGitProvider().equals("github") && !o.getName().equals(githubLogin)) - .flatMap(o -> - o.getGitProjects().stream()) + List organizationsProjects = updatedGithubCompanies + .stream() + .filter(o -> o.getGitProvider().equals("github") && !o.getName().equals(githubLogin)) + .flatMap(o -> o.getGitProjects().stream()) .collect(Collectors.toList()); syncUserProjects(user, gitHub, ghMyself, githubLogin, currentGithubCompanies, organizationsProjects); @@ -152,8 +160,13 @@ public User getSyncedUserFromGitProvider(User user) { */ @Async @Override - public void createGitProviderRepository(User user, String applicationId, String applicationConfiguration, String - organization, String repositoryName) { + public void createGitProviderRepository( + User user, + String applicationId, + String applicationConfiguration, + String organization, + String repositoryName + ) { try { log.info("Beginning to create repository {} / {}", organization, repositoryName); this.logsService.addLog(applicationId, "Creating GitHub repository"); @@ -170,8 +183,14 @@ public void createGitProviderRepository(User user, String applicationId, String builder.create(); this.logsService.addLog(applicationId, "GitHub repository created!"); - this.generatorService.generateGitApplication(user, applicationId, applicationConfiguration, organization, - repositoryName, GitProvider.GITHUB); + this.generatorService.generateGitApplication( + user, + applicationId, + applicationConfiguration, + organization, + repositoryName, + GitProvider.GITHUB + ); this.logsService.addLog(applicationId, "Generation finished"); } catch (Exception e) { @@ -180,9 +199,8 @@ public void createGitProviderRepository(User user, String applicationId, String } } - public int createPullRequest(User user, String organization, String repositoryName, - String title, String branchName, String body) throws IOException { - + public int createPullRequest(User user, String organization, String repositoryName, String title, String branchName, String body) + throws IOException { log.info("Creating Pull Request on repository {} / {}", organization, repositoryName); GitHub gitHub = this.getConnection(user); @@ -226,14 +244,22 @@ public void deleteAllOrganizationsUser(User user) { /** * Sync the projects from the user's companies */ - private void syncUserProjectsFromCompanies(User user, GitHub gitHub, Set currentGithubCompanies, Set updatedGithubCompanies) throws IOException { + private void syncUserProjectsFromCompanies( + User user, + GitHub gitHub, + Set currentGithubCompanies, + Set updatedGithubCompanies + ) + throws IOException { Map githubOrganizations = gitHub.getMyOrganizations(); for (String githubOrganizationName : githubOrganizations.keySet()) { log.debug("Syncing company `{}`", githubOrganizationName); GitCompany company; // Create company if it does not already exist - Optional currentGitHubOrganization = - currentGithubCompanies.stream().filter(g -> g.getName().equals(githubOrganizationName)).findFirst(); + Optional currentGitHubOrganization = currentGithubCompanies + .stream() + .filter(g -> g.getName().equals(githubOrganizationName)) + .findFirst(); if (currentGitHubOrganization.isEmpty()) { log.debug("Saving new company `{}`", githubOrganizationName); @@ -254,7 +280,15 @@ private void syncUserProjectsFromCompanies(User user, GitHub gitHub, Set currentGithubCompanies, List organizationsProjects) throws Exception { + private void syncUserProjects( + User user, + GitHub gitHub, + GHMyself ghMyself, + String githubLogin, + Set currentGithubCompanies, + List organizationsProjects + ) + throws Exception { log.debug("Syncing user's projects"); GitCompany myOrganization; if (currentGithubCompanies.stream().noneMatch(g -> g.getName().equals(ghMyself.getLogin()))) { @@ -264,16 +298,20 @@ private void syncUserProjects(User user, GitHub gitHub, GHMyself ghMyself, Strin myOrganization.setGitProvider(GitProvider.GITHUB.getValue()); gitCompanyRepository.save(myOrganization); } else { - myOrganization = currentGithubCompanies.stream() - .filter(g -> g.getName().equals(ghMyself.getLogin())) - .findFirst() - .orElseThrow(Exception::new); + myOrganization = + currentGithubCompanies + .stream() + .filter(g -> g.getName().equals(ghMyself.getLogin())) + .findFirst() + .orElseThrow(Exception::new); } try { - List ownedProjects = gitHub.getMyself().getAllRepositories().keySet().stream() - .filter(ghRepository -> organizationsProjects.stream() - .noneMatch(p -> - p.equals(ghRepository))) + List ownedProjects = gitHub + .getMyself() + .getAllRepositories() + .keySet() + .stream() + .filter(ghRepository -> organizationsProjects.stream().noneMatch(p -> p.equals(ghRepository))) .collect(Collectors.toList()); myOrganization.setGitProjects(ownedProjects); } catch (IOException e) { diff --git a/src/main/java/io/github/jhipster/online/service/GitlabService.java b/src/main/java/io/github/jhipster/online/service/GitlabService.java index c7e28938..96a28097 100644 --- a/src/main/java/io/github/jhipster/online/service/GitlabService.java +++ b/src/main/java/io/github/jhipster/online/service/GitlabService.java @@ -27,6 +27,12 @@ import io.github.jhipster.online.repository.UserRepository; import io.github.jhipster.online.security.SecurityUtils; import io.github.jhipster.online.service.interfaces.GitProviderService; +import java.io.IOException; +import java.lang.module.FindException; +import java.net.ConnectException; +import java.util.*; +import java.util.stream.Collectors; +import javax.annotation.PostConstruct; import org.eclipse.jgit.api.errors.GitAPIException; import org.gitlab.api.GitlabAPI; import org.gitlab.api.GitlabAPIException; @@ -41,13 +47,6 @@ import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StopWatch; -import javax.annotation.PostConstruct; -import java.io.IOException; -import java.lang.module.FindException; -import java.net.ConnectException; -import java.util.*; -import java.util.stream.Collectors; - @Service public class GitlabService implements GitProviderService { @@ -63,10 +62,13 @@ public class GitlabService implements GitProviderService { private final GitCompanyRepository gitCompanyRepository; - public GitlabService(GeneratorService generatorService, + public GitlabService( + GeneratorService generatorService, ApplicationProperties applicationProperties, - LogsService logsService, UserRepository userRepository, - GitCompanyRepository gitCompanyRepository) { + LogsService logsService, + UserRepository userRepository, + GitCompanyRepository gitCompanyRepository + ) { this.generatorService = generatorService; this.applicationProperties = applicationProperties; this.logsService = logsService; @@ -80,7 +82,10 @@ public void init() { if (this.applicationProperties.getGitlab().getHost().equals("https://gitlab.com")) { log.warn("JHipster Online is configured to work on the public GitLab instance at https://gitlab.com"); } else { - log.warn("JHipster Online is configured to work on a private GitLab instance at {}", this.applicationProperties.getGitlab().getHost()); + log.warn( + "JHipster Online is configured to work on a private GitLab instance at {}", + this.applicationProperties.getGitlab().getHost() + ); } } } @@ -91,7 +96,9 @@ public String getHost() { } @Override - public String getClientId() { return applicationProperties.getGitlab().getClientId(); } + public String getClientId() { + return applicationProperties.getGitlab().getClientId(); + } public String getRedirectUri() { return applicationProperties.getGitlab().getRedirectUri(); @@ -99,11 +106,12 @@ public String getRedirectUri() { @Override public boolean isEnabled() { - return + return ( this.applicationProperties.getGitlab().getClientId() != null && - this.applicationProperties.getGitlab().getClientSecret() != null && - this.applicationProperties.getGitlab().getHost() != null && - this.applicationProperties.getGitlab().getRedirectUri() != null; + this.applicationProperties.getGitlab().getClientSecret() != null && + this.applicationProperties.getGitlab().getHost() != null && + this.applicationProperties.getGitlab().getRedirectUri() != null + ); } @Transactional @@ -128,8 +136,11 @@ public User getSyncedUserFromGitProvider(User user) throws IOException { GitlabUser myself = gitlab.getUser(); user.setGitlabUser(myself.getUsername()); user.setGitlabEmail(myself.getEmail()); - Set currentGitlabCompanies = - user.getGitCompanies().stream().filter(c -> c.getGitProvider().equals(GitProvider.GITLAB.getValue())).collect(Collectors.toSet()); + Set currentGitlabCompanies = user + .getGitCompanies() + .stream() + .filter(c -> c.getGitProvider().equals(GitProvider.GITLAB.getValue())) + .collect(Collectors.toSet()); GitCompany gitCompany; @@ -141,15 +152,20 @@ public User getSyncedUserFromGitProvider(User user) throws IOException { gitCompany.setGitProvider(GitProvider.GITLAB.getValue()); gitCompany.setGitProjects(new ArrayList<>()); gitCompanyRepository.save(gitCompany); - } else { - gitCompany = currentGitlabCompanies.stream().filter(g -> g.getName().equals(myself.getUsername())).findFirst().orElseThrow( - () -> new NoSuchElementException("Could not find any GitCompany for user.")); + gitCompany = + currentGitlabCompanies + .stream() + .filter(g -> g.getName().equals(myself.getUsername())) + .findFirst() + .orElseThrow(() -> new NoSuchElementException("Could not find any GitCompany for user.")); } try { - List projectList = gitlab.getMembershipProjects().stream() - .filter(p -> p.getOwner() != null && p.getOwner().getId().equals(myself.getId())) + List projectList = gitlab + .getMembershipProjects() + .stream() + .filter(p -> p.getOwner() != null && p.getOwner().getId().equals(myself.getId())) .collect(Collectors.toList()); List projects = projectList.stream().map(GitlabProject::getName).collect(Collectors.toList()); @@ -161,32 +177,38 @@ public User getSyncedUserFromGitProvider(User user) throws IOException { // Sync the projects from the user's groups Set updatedGitlabCompanies = new HashSet<>(); - gitlab.getGroups().forEach(group -> { - log.debug("Syncing organization `{}`", group.getName()); - GitCompany company; - Optional currentGitlabCompany = - currentGitlabCompanies.stream().filter(g -> g.getName().equals(group.getName())).findFirst(); - - if (!currentGitlabCompany.isPresent()) { - log.debug("Saving new company `{}`", group.getName()); - company = new GitCompany(); - company.setName(group.getName()); - company.setUser(user); - company.setGitProvider(GitProvider.GITLAB.getValue()); - gitCompanyRepository.save(company); - } else { - company = currentGitlabCompany.get(); - } - log.debug("Adding company `{}` to user", company.getName()); - updatedGitlabCompanies.add(company); - try { - List projectList = gitlab.getGroupProjects(group); - List projects = projectList.stream().map(GitlabProject::getName).collect(Collectors.toList()); - company.setGitProjects(projects); - } catch (IOException e) { - log.error("Could not sync GitLab repositories for user `{}`: {}", user.getLogin(), e.getMessage()); - } - }); + gitlab + .getGroups() + .forEach( + group -> { + log.debug("Syncing organization `{}`", group.getName()); + GitCompany company; + Optional currentGitlabCompany = currentGitlabCompanies + .stream() + .filter(g -> g.getName().equals(group.getName())) + .findFirst(); + + if (!currentGitlabCompany.isPresent()) { + log.debug("Saving new company `{}`", group.getName()); + company = new GitCompany(); + company.setName(group.getName()); + company.setUser(user); + company.setGitProvider(GitProvider.GITLAB.getValue()); + gitCompanyRepository.save(company); + } else { + company = currentGitlabCompany.get(); + } + log.debug("Adding company `{}` to user", company.getName()); + updatedGitlabCompanies.add(company); + try { + List projectList = gitlab.getGroupProjects(group); + List projects = projectList.stream().map(GitlabProject::getName).collect(Collectors.toList()); + company.setGitProjects(projects); + } catch (IOException e) { + log.error("Could not sync GitLab repositories for user `{}`: {}", user.getLogin(), e.getMessage()); + } + } + ); user.setGitCompanies(updatedGitlabCompanies); watch.stop(); @@ -199,9 +221,13 @@ public User getSyncedUserFromGitProvider(User user) throws IOException { */ @Async @Override - public void createGitProviderRepository(User user, String applicationId, String applicationConfiguration, String - group, - String repositoryName) { + public void createGitProviderRepository( + User user, + String applicationId, + String applicationConfiguration, + String group, + String repositoryName + ) { try { log.info("Beginning to create repository {} / {}", group, repositoryName); this.logsService.addLog(applicationId, "Creating GitLab repository"); @@ -217,8 +243,14 @@ public void createGitProviderRepository(User user, String applicationId, String } this.logsService.addLog(applicationId, "GitLab repository created!"); - this.generatorService.generateGitApplication(user, applicationId, applicationConfiguration, group, - repositoryName, GitProvider.GITLAB); + this.generatorService.generateGitApplication( + user, + applicationId, + applicationConfiguration, + group, + repositoryName, + GitProvider.GITLAB + ); this.logsService.addLog(applicationId, "Generation finished"); } catch (Exception e) { @@ -228,8 +260,8 @@ public void createGitProviderRepository(User user, String applicationId, String } @Override - public int createPullRequest(User user, String group, String repositoryName, - String title, String branchName, String body) throws IOException { + public int createPullRequest(User user, String group, String repositoryName, String title, String branchName, String body) + throws IOException { log.info("Creating Merge Request on repository {} / {}", group, repositoryName); GitlabAPI gitlab = getConnection(user); int number = gitlab.getProject(group, repositoryName).getId(); @@ -253,8 +285,11 @@ private GitlabAPI getConnection(User user) throws IOException { if (user.getGitlabOAuthToken() == null) { throw new ConnectException("No GitLab token configured"); } - GitlabAPI gitlab = GitlabAPI.connect(applicationProperties.getGitlab().getHost(), user.getGitlabOAuthToken(), - TokenType.ACCESS_TOKEN); + GitlabAPI gitlab = GitlabAPI.connect( + applicationProperties.getGitlab().getHost(), + user.getGitlabOAuthToken(), + TokenType.ACCESS_TOKEN + ); log.debug("User `{}` authenticated as `{}` on GitLab", user.getLogin(), gitlab.getUser().getUsername()); return gitlab; diff --git a/src/main/java/io/github/jhipster/online/service/InvalidPasswordException.java b/src/main/java/io/github/jhipster/online/service/InvalidPasswordException.java index a207361a..f18f6ba2 100644 --- a/src/main/java/io/github/jhipster/online/service/InvalidPasswordException.java +++ b/src/main/java/io/github/jhipster/online/service/InvalidPasswordException.java @@ -7,5 +7,4 @@ public class InvalidPasswordException extends RuntimeException { public InvalidPasswordException() { super("Incorrect password"); } - } diff --git a/src/main/java/io/github/jhipster/online/service/JHipsterService.java b/src/main/java/io/github/jhipster/online/service/JHipsterService.java index e1727dae..f1f4946d 100644 --- a/src/main/java/io/github/jhipster/online/service/JHipsterService.java +++ b/src/main/java/io/github/jhipster/online/service/JHipsterService.java @@ -21,16 +21,15 @@ import io.github.jhipster.online.config.ApplicationProperties; import io.github.jhipster.online.service.enums.CiCdTool; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Service; - import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; @Service public class JHipsterService { @@ -62,14 +61,32 @@ public void installNpmDependencies(String generationId, File workingDir) throws public void generateApplication(String generationId, File workingDir) throws IOException { this.logsService.addLog(generationId, "Running JHipster"); - this.runProcess(generationId, workingDir, jhipsterCommand, "--force-insight", "--skip-checks", - "--skip-install", "--skip-cache", "--skip-git", "--prettier-java"); + this.runProcess( + generationId, + workingDir, + jhipsterCommand, + "--force-insight", + "--skip-checks", + "--skip-install", + "--skip-cache", + "--skip-git", + "--prettier-java" + ); } public void runImportJdl(String generationId, File workingDir, String jdlFileName) throws IOException { this.logsService.addLog(generationId, "Running `jhipster import-jdl"); - this.runProcess(generationId, workingDir, jhipsterCommand, "import-jdl", - jdlFileName + ".jh", "--force-insight", "--skip-checks", "--skip-install", "--force"); + this.runProcess( + generationId, + workingDir, + jhipsterCommand, + "import-jdl", + jdlFileName + ".jh", + "--force-insight", + "--skip-checks", + "--skip-install", + "--force" + ); } public void addCiCd(String generationId, File workingDir, CiCdTool ciCdTool) throws IOException { @@ -78,8 +95,17 @@ public void addCiCd(String generationId, File workingDir, CiCdTool ciCdTool) thr throw new IllegalArgumentException("Invalid Continuous Integration system"); } this.logsService.addLog(generationId, "Running `jhipster ci-cd`"); - this.runProcess(generationId, workingDir, jhipsterCommand, "ci-cd", - "--autoconfigure-" + ciCdTool.command(), "--force-insight", "--skip-checks", "--skip-install", "--force"); + this.runProcess( + generationId, + workingDir, + jhipsterCommand, + "ci-cd", + "--autoconfigure-" + ciCdTool.command(), + "--force-insight", + "--skip-checks", + "--skip-install", + "--force" + ); } private void runProcess(String generationId, File workingDir, String... command) throws IOException { @@ -87,22 +113,25 @@ private void runProcess(String generationId, File workingDir, String... command) BufferedReader input = null; try { String line; - ProcessBuilder processBuilder = new ProcessBuilder().directory(workingDir).command(command).redirectError(ProcessBuilder.Redirect.DISCARD); + ProcessBuilder processBuilder = new ProcessBuilder() + .directory(workingDir) + .command(command) + .redirectError(ProcessBuilder.Redirect.DISCARD); Process p = processBuilder.start(); - taskExecutor.execute(() -> { - try { - p.waitFor(timeout, TimeUnit.SECONDS); - p.destroyForcibly(); - } catch (InterruptedException e) { - log.error("Unable to execute process successfully.", e); - Thread.currentThread().interrupt(); + taskExecutor.execute( + () -> { + try { + p.waitFor(timeout, TimeUnit.SECONDS); + p.destroyForcibly(); + } catch (InterruptedException e) { + log.error("Unable to execute process successfully.", e); + Thread.currentThread().interrupt(); + } } - }); + ); - input = - new BufferedReader - (new InputStreamReader(p.getInputStream())); + input = new BufferedReader(new InputStreamReader(p.getInputStream())); while ((line = input.readLine()) != null) { log.debug(line); this.logsService.addLog(generationId, line); diff --git a/src/main/java/io/github/jhipster/online/service/JdlMetadataService.java b/src/main/java/io/github/jhipster/online/service/JdlMetadataService.java index a6fed48d..185e6ccd 100644 --- a/src/main/java/io/github/jhipster/online/service/JdlMetadataService.java +++ b/src/main/java/io/github/jhipster/online/service/JdlMetadataService.java @@ -28,6 +28,11 @@ import io.github.jhipster.online.security.SecurityUtils; import io.github.jhipster.online.service.dto.JdlMetadataDTO; import io.github.jhipster.online.service.mapper.JdlMetadataMapper; +import java.nio.file.FileSystemException; +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import java.util.UUID; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.domain.Sort; @@ -35,12 +40,6 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import java.nio.file.FileSystemException; -import java.time.Instant; -import java.util.List; -import java.util.Optional; -import java.util.UUID; - /** * Service Implementation for managing JdlMetadata. */ @@ -58,9 +57,12 @@ public class JdlMetadataService { private final JdlMetadataMapper jdlMetadataMapper; - public JdlMetadataService(JdlMetadataRepository jdlMetadataRepository, JdlRepository jdlRepository, - UserRepository userRepository, JdlMetadataMapper jdlMetadataMapper) { - + public JdlMetadataService( + JdlMetadataRepository jdlMetadataRepository, + JdlRepository jdlRepository, + UserRepository userRepository, + JdlMetadataMapper jdlMetadataMapper + ) { this.jdlMetadataRepository = jdlMetadataRepository; this.jdlRepository = jdlRepository; this.userRepository = userRepository; diff --git a/src/main/java/io/github/jhipster/online/service/JdlService.java b/src/main/java/io/github/jhipster/online/service/JdlService.java index 5cc4b011..409dd1af 100644 --- a/src/main/java/io/github/jhipster/online/service/JdlService.java +++ b/src/main/java/io/github/jhipster/online/service/JdlService.java @@ -26,6 +26,12 @@ import io.github.jhipster.online.domain.User; import io.github.jhipster.online.domain.enums.GitProvider; import io.github.jhipster.online.repository.JdlRepository; +import java.io.File; +import java.io.IOException; +import java.io.PrintWriter; +import java.nio.charset.StandardCharsets; +import java.nio.file.FileSystemException; +import java.util.Optional; import org.apache.commons.io.FileUtils; import org.eclipse.jgit.api.Git; import org.slf4j.Logger; @@ -35,13 +41,6 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import java.io.File; -import java.io.IOException; -import java.io.PrintWriter; -import java.nio.charset.StandardCharsets; -import java.nio.file.FileSystemException; -import java.util.Optional; - @Service public class JdlService { @@ -61,12 +60,15 @@ public class JdlService { private final ApplicationProperties applicationProperties; - public JdlService(LogsService logsService, + public JdlService( + LogsService logsService, GitService gitService, JHipsterService jHipsterService, GithubService githubService, - GitlabService gitlabService, JdlRepository jdlRepository, - ApplicationProperties applicationProperties) { + GitlabService gitlabService, + JdlRepository jdlRepository, + ApplicationProperties applicationProperties + ) { this.logsService = logsService; this.gitService = gitService; this.jHipsterService = jHipsterService; @@ -80,16 +82,23 @@ public JdlService(LogsService logsService, * Apply a JDL Model to an existing repository. */ @Async - public void applyJdl(User user, String organizationName, String projectName, JdlMetadata jdlMetadata, String - applyJdlId, GitProvider gitProvider) { + public void applyJdl( + User user, + String organizationName, + String projectName, + JdlMetadata jdlMetadata, + String applyJdlId, + GitProvider gitProvider + ) { try { log.info("Beginning to apply JDL Model {} to {} / {}", jdlMetadata.getId(), organizationName, projectName); boolean isGitHub = gitProvider.equals(GitProvider.GITHUB); - this.logsService.addLog(applyJdlId, "Cloning " + (isGitHub ? "GitHub" : "GitLab") + " repository `" + - organizationName + "/" + projectName + "`"); + this.logsService.addLog( + applyJdlId, + "Cloning " + (isGitHub ? "GitHub" : "GitLab") + " repository `" + organizationName + "/" + projectName + "`" + ); - File workingDir = new File(applicationProperties.getTmpFolder() + "/jhipster/applications/" + - applyJdlId); + File workingDir = new File(applicationProperties.getTmpFolder() + "/jhipster/applications/" + applyJdlId); FileUtils.forceMkdir(workingDir); Git git = this.gitService.cloneRepository(user, workingDir, organizationName, projectName, gitProvider); @@ -100,52 +109,87 @@ public void applyJdl(User user, String organizationName, String projectName, Jdl this.logsService.addLog(applyJdlId, "Adding JDL file into the project"); this.generateJdlFile(workingDir, jdlMetadata); this.gitService.addAllFilesToRepository(git, workingDir); - this.gitService.commit(git, workingDir, "Add JDL Model `" + jdlMetadata.getName() + "`\n\n" + - "See https://start.jhipster.tech/jdl-studio/#!/view/" + jdlMetadata.getId()); + this.gitService.commit( + git, + workingDir, + "Add JDL Model `" + + jdlMetadata.getName() + + "`\n\n" + + "See https://start.jhipster.tech/jdl-studio/#!/view/" + + jdlMetadata.getId() + ); this.logsService.addLog(applyJdlId, "Generating entities from JDL Model"); //this.jHipsterService.installNpmDependencies(applyJdlId, workingDir); this.jHipsterService.runImportJdl(applyJdlId, workingDir, this.kebabCaseJdlName(jdlMetadata)); this.gitService.addAllFilesToRepository(git, workingDir); - this.gitService.commit(git, workingDir, "Generate entities from JDL Model `" + jdlMetadata.getName() + - "`\n\n" + - "See https://start.jhipster.tech/jdl-studio/#!/view/" + jdlMetadata.getId()); + this.gitService.commit( + git, + workingDir, + "Generate entities from JDL Model `" + + jdlMetadata.getName() + + "`\n\n" + + "See https://start.jhipster.tech/jdl-studio/#!/view/" + + jdlMetadata.getId() + ); - this.logsService.addLog(applyJdlId, "Pushing the application to the " + (isGitHub ? "GitHub" : "GitLab") - + " remote repository"); + this.logsService.addLog( + applyJdlId, + "Pushing the application to the " + (isGitHub ? "GitHub" : "GitLab") + " remote repository" + ); this.gitService.push(git, workingDir, user, organizationName, projectName, gitProvider); this.logsService.addLog(applyJdlId, "Application successfully pushed!"); this.logsService.addLog(applyJdlId, "Creating " + (isGitHub ? "Pull" : "Merge") + " Request"); String pullRequestTitle = "Add entities using the JDL model `" + jdlMetadata.getName() + "`"; - String pullRequestBody = "Entities generated by JHipster using the model at https://start.jhipster" + - ".tech/jdl-studio/#!/view/" + jdlMetadata.getId(); + String pullRequestBody = + "Entities generated by JHipster using the model at https://start.jhipster" + + ".tech/jdl-studio/#!/view/" + + jdlMetadata.getId(); if (isGitHub) { int pullRequestNumber = - this.githubService.createPullRequest(user, organizationName, projectName, pullRequestTitle, - branchName, pullRequestBody); - this.logsService.addLog(applyJdlId, "Pull Request created at " + githubService.getHost() + - "/" + - organizationName + - "/" + - projectName + - "/pull/" + - pullRequestNumber - ); + this.githubService.createPullRequest( + user, + organizationName, + projectName, + pullRequestTitle, + branchName, + pullRequestBody + ); + this.logsService.addLog( + applyJdlId, + "Pull Request created at " + + githubService.getHost() + + "/" + + organizationName + + "/" + + projectName + + "/pull/" + + pullRequestNumber + ); } else { int pullRequestNumber = - this.gitlabService.createPullRequest(user, organizationName, projectName, pullRequestTitle, - branchName, pullRequestBody); - this.logsService.addLog(applyJdlId, "Merge Request created at " + gitlabService.getHost() + - "/" + - organizationName + - "/" + - projectName + - "/merge_requests/" + - pullRequestNumber - ); + this.gitlabService.createPullRequest( + user, + organizationName, + projectName, + pullRequestTitle, + branchName, + pullRequestBody + ); + this.logsService.addLog( + applyJdlId, + "Merge Request created at " + + gitlabService.getHost() + + "/" + + organizationName + + "/" + + projectName + + "/merge_requests/" + + pullRequestNumber + ); } this.gitService.cleanUpDirectory(workingDir); @@ -163,8 +207,7 @@ private void generateJdlFile(File workingDir, JdlMetadata jdlMetadata) throws IO if (jdl.isEmpty()) { throw new FileSystemException("Error creating file jhipster-jdl.jh, the JDL could not be found"); } - PrintWriter writer = new PrintWriter(workingDir + "/" + this.kebabCaseJdlName(jdlMetadata) + ".jh", - StandardCharsets.UTF_8); + PrintWriter writer = new PrintWriter(workingDir + "/" + this.kebabCaseJdlName(jdlMetadata) + ".jh", StandardCharsets.UTF_8); writer.print(jdl.get().getContent()); writer.close(); } catch (IOException ioe) { diff --git a/src/main/java/io/github/jhipster/online/service/LogsService.java b/src/main/java/io/github/jhipster/online/service/LogsService.java index f47ff7e1..df33dada 100644 --- a/src/main/java/io/github/jhipster/online/service/LogsService.java +++ b/src/main/java/io/github/jhipster/online/service/LogsService.java @@ -21,20 +21,17 @@ import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; +import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; -import java.util.concurrent.TimeUnit; - @Service public class LogsService { private final Logger log = LoggerFactory.getLogger(LogsService.class); - private Cache logsCache = CacheBuilder.newBuilder() - .expireAfterWrite(5, TimeUnit.MINUTES) - .build(); + private Cache logsCache = CacheBuilder.newBuilder().expireAfterWrite(5, TimeUnit.MINUTES).build(); public synchronized void addLog(String logID, String logMessage) { log.info("log `{}` : {}", logID, logMessage); diff --git a/src/main/java/io/github/jhipster/online/service/MailService.java b/src/main/java/io/github/jhipster/online/service/MailService.java index 9262b14c..2824e037 100644 --- a/src/main/java/io/github/jhipster/online/service/MailService.java +++ b/src/main/java/io/github/jhipster/online/service/MailService.java @@ -21,6 +21,10 @@ import io.github.jhipster.config.JHipsterProperties; import io.github.jhipster.online.domain.User; +import java.nio.charset.StandardCharsets; +import java.util.Locale; +import javax.mail.MessagingException; +import javax.mail.internet.MimeMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.MessageSource; @@ -32,11 +36,6 @@ import org.thymeleaf.context.Context; import org.thymeleaf.spring5.SpringTemplateEngine; -import javax.mail.MessagingException; -import javax.mail.internet.MimeMessage; -import java.nio.charset.StandardCharsets; -import java.util.Locale; - /** * Service for sending emails. *

@@ -59,9 +58,12 @@ public class MailService { private final SpringTemplateEngine templateEngine; - public MailService(JHipsterProperties jHipsterProperties, JavaMailSender javaMailSender, - MessageSource messageSource, SpringTemplateEngine templateEngine) { - + public MailService( + JHipsterProperties jHipsterProperties, + JavaMailSender javaMailSender, + MessageSource messageSource, + SpringTemplateEngine templateEngine + ) { this.jHipsterProperties = jHipsterProperties; this.javaMailSender = javaMailSender; this.messageSource = messageSource; @@ -70,8 +72,14 @@ public MailService(JHipsterProperties jHipsterProperties, JavaMailSender javaMai @Async public void sendEmail(String to, String subject, String content, boolean isMultipart, boolean isHtml) { - log.debug("Send email[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}", - isMultipart, isHtml, to, subject, content); + log.debug( + "Send email[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}", + isMultipart, + isHtml, + to, + subject, + content + ); // Prepare message using a Spring helper MimeMessage mimeMessage = javaMailSender.createMimeMessage(); @@ -83,7 +91,7 @@ public void sendEmail(String to, String subject, String content, boolean isMulti message.setText(content, isHtml); javaMailSender.send(mimeMessage); log.debug("Sent email to User '{}'", to); - } catch (MailException | MessagingException e) { + } catch (MailException | MessagingException e) { log.warn("Email could not be sent to user '{}'", to, e); } } diff --git a/src/main/java/io/github/jhipster/online/service/StatisticsService.java b/src/main/java/io/github/jhipster/online/service/StatisticsService.java index 3decfb19..864cc359 100644 --- a/src/main/java/io/github/jhipster/online/service/StatisticsService.java +++ b/src/main/java/io/github/jhipster/online/service/StatisticsService.java @@ -28,17 +28,16 @@ import io.github.jhipster.online.service.mapper.SubGenEventMapper; import io.github.jhipster.online.service.mapper.YoRCMapper; import io.github.jhipster.online.util.DateUtil; +import java.io.IOException; +import java.time.Instant; +import java.util.List; +import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import java.io.IOException; -import java.time.Instant; -import java.util.List; -import java.util.Optional; - @Service public class StatisticsService { @@ -58,13 +57,15 @@ public class StatisticsService { private YoRCMapper yoRCMapper; - public StatisticsService(YoRCService yoRCService, - GeneratorIdentityService generatorIdentityService, - SubGenEventService subGenEventService, - EntityStatsService entityStatsService, - SubGenEventMapper subGenEventMapper, - EntityStatsMapper entityStatsMapper, - YoRCMapper yoRCMapper) { + public StatisticsService( + YoRCService yoRCService, + GeneratorIdentityService generatorIdentityService, + SubGenEventService subGenEventService, + EntityStatsService entityStatsService, + SubGenEventMapper subGenEventMapper, + EntityStatsMapper entityStatsMapper, + YoRCMapper yoRCMapper + ) { this.yoRCService = yoRCService; this.generatorIdentityService = generatorIdentityService; this.subGenEventService = subGenEventService; @@ -96,7 +97,8 @@ public void addEntry(String entry, String host) throws IOException { Instant now = Instant.now(); DateUtil.setAbsoluteDate(yorc, now); - yorc.jhipsterVersion(generatorVersion) + yorc + .jhipsterVersion(generatorVersion) .gitProvider(gitProvider) .nodeVersion(nodeVersion) .os(os) @@ -124,7 +126,7 @@ public void addEntry(String entry, String host) throws IOException { @Transactional @Async("statisticsExecutor") - public void addSubGenEvent(SubGenEventDTO subGenEventDTO, String generatorGuid) { + public void addSubGenEvent(SubGenEventDTO subGenEventDTO, String generatorGuid) { Instant now = Instant.now(); SubGenEvent subGenEvent = subGenEventMapper.toEntity(subGenEventDTO); DateUtil.setAbsoluteDate(subGenEvent, now); @@ -143,7 +145,7 @@ public void addSubGenEvent(SubGenEventDTO subGenEventDTO, String generatorGuid) @Transactional @Async("statisticsExecutor") - public void addEntityStats(EntityStatsDTO entityStatsDTO, String generatorGuid) { + public void addEntityStats(EntityStatsDTO entityStatsDTO, String generatorGuid) { Instant now = Instant.now(); EntityStats entityStats = entityStatsMapper.toEntity(entityStatsDTO); DateUtil.setAbsoluteDate(entityStats, now); diff --git a/src/main/java/io/github/jhipster/online/service/SubGenEventService.java b/src/main/java/io/github/jhipster/online/service/SubGenEventService.java index 98806a06..598065f8 100644 --- a/src/main/java/io/github/jhipster/online/service/SubGenEventService.java +++ b/src/main/java/io/github/jhipster/online/service/SubGenEventService.java @@ -31,19 +31,18 @@ import io.github.jhipster.online.service.enums.TemporalValueType; import io.github.jhipster.online.service.mapper.SubGenEventMapper; import io.github.jhipster.online.service.util.QueryUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - +import java.time.Instant; +import java.util.*; +import java.util.stream.Collectors; import javax.persistence.EntityManager; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.ParameterExpression; import javax.persistence.criteria.Root; -import java.time.Instant; -import java.util.*; -import java.util.stream.Collectors; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; /** * Service Implementation for managing SubGenEvent. @@ -60,7 +59,11 @@ public class SubGenEventService { private final SubGenEventMapper subGenEventMapper; - public SubGenEventService(SubGenEventRepository subGenEventRepository, EntityManager entityManager, SubGenEventMapper subGenEventMapper) { + public SubGenEventService( + SubGenEventRepository subGenEventRepository, + EntityManager entityManager, + SubGenEventMapper subGenEventMapper + ) { this.subGenEventRepository = subGenEventRepository; this.entityManager = entityManager; this.subGenEventMapper = subGenEventMapper; @@ -90,7 +93,6 @@ public List findAll() { return subGenEventRepository.findAll(); } - /** * Get one subGenEvent by id. * @@ -125,8 +127,19 @@ public List getFieldCount(Instant after, SubGenEventType field ParameterExpression dateParameter = builder.parameter(Instant.class, QueryUtil.DATE); ParameterExpression typeParameter = builder.parameter(String.class, QueryUtil.TYPE); - query.select(builder.construct(RawSQLField.class, root.get(dbTemporalFunction.getFieldName()), root.get(SubGenEvent_.type), builder.count(root))) - .where(builder.greaterThan(root.get(SubGenEvent_.date).as(Instant.class), dateParameter), builder.equal(root.get(SubGenEvent_.type), typeParameter)) + query + .select( + builder.construct( + RawSQLField.class, + root.get(dbTemporalFunction.getFieldName()), + root.get(SubGenEvent_.type), + builder.count(root) + ) + ) + .where( + builder.greaterThan(root.get(SubGenEvent_.date).as(Instant.class), dateParameter), + builder.equal(root.get(SubGenEvent_.type), typeParameter) + ) .groupBy(root.get(SubGenEvent_.type), root.get(dbTemporalFunction.getFieldName())); return entityManager @@ -135,21 +148,27 @@ public List getFieldCount(Instant after, SubGenEventType field .setParameter(QueryUtil.TYPE, field.getDatabaseValue()) .getResultList() .stream() - .map(entry -> - new TemporalCountDTO(TemporalValueType.absoluteMomentToInstant(entry.getMoment().longValue(), dbTemporalFunction), entry.getCount()) - ).collect(Collectors.toList()); + .map( + entry -> + new TemporalCountDTO( + TemporalValueType.absoluteMomentToInstant(entry.getMoment().longValue(), dbTemporalFunction), + entry.getCount() + ) + ) + .collect(Collectors.toList()); } public List getDeploymentToolDistribution(Instant after, TemporalValueType dbTemporalFunction) { - Map> entries = Arrays.stream(SubGenEventType.getDeploymentTools()) - .map(deploymentTool -> - new AbstractMap.SimpleEntry<>(deploymentTool, getFieldCount(after, deploymentTool, dbTemporalFunction)) - ).collect(Collectors.toMap(AbstractMap.SimpleEntry::getKey, AbstractMap.SimpleEntry::getValue)); + Map> entries = Arrays + .stream(SubGenEventType.getDeploymentTools()) + .map(deploymentTool -> new AbstractMap.SimpleEntry<>(deploymentTool, getFieldCount(after, deploymentTool, dbTemporalFunction))) + .collect(Collectors.toMap(AbstractMap.SimpleEntry::getKey, AbstractMap.SimpleEntry::getValue)); List result = new ArrayList<>(); - for (Map.Entry> entry: entries.entrySet()) { - for (TemporalCountDTO count: entry.getValue()) { - Optional maybeDistribution = result.stream() + for (Map.Entry> entry : entries.entrySet()) { + for (TemporalCountDTO count : entry.getValue()) { + Optional maybeDistribution = result + .stream() .filter(td -> td.getDate().equals(count.getDate())) .findFirst(); TemporalDistributionDTO distributionDTO; diff --git a/src/main/java/io/github/jhipster/online/service/UserService.java b/src/main/java/io/github/jhipster/online/service/UserService.java index 170750c3..f1ace96e 100644 --- a/src/main/java/io/github/jhipster/online/service/UserService.java +++ b/src/main/java/io/github/jhipster/online/service/UserService.java @@ -34,6 +34,10 @@ import io.github.jhipster.online.security.SecurityUtils; import io.github.jhipster.online.service.dto.UserDTO; import io.github.jhipster.security.RandomUtil; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.*; +import java.util.stream.Collectors; import org.hibernate.Hibernate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -46,11 +50,6 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import java.time.Instant; -import java.time.temporal.ChronoUnit; -import java.util.*; -import java.util.stream.Collectors; - /** * Service class for managing users. */ @@ -80,15 +79,19 @@ public class UserService { private final JdlService jdlService; - public UserService(UserRepository userRepository, - PasswordEncoder passwordEncoder, - AuthorityRepository authorityRepository, - GithubService githubService, - CacheManager cacheManager, - MailService mailService, - JHipsterProperties jHipsterProperties, - GitCompanyRepository gitCompanyRepository, - GitlabService gitlabService, JdlMetadataService jdlMetadataService, JdlService jdlService) { + public UserService( + UserRepository userRepository, + PasswordEncoder passwordEncoder, + AuthorityRepository authorityRepository, + GithubService githubService, + CacheManager cacheManager, + MailService mailService, + JHipsterProperties jHipsterProperties, + GitCompanyRepository gitCompanyRepository, + GitlabService gitlabService, + JdlMetadataService jdlMetadataService, + JdlService jdlService + ) { this.userRepository = userRepository; this.passwordEncoder = passwordEncoder; this.authorityRepository = authorityRepository; @@ -103,39 +106,48 @@ public UserService(UserRepository userRepository, public Optional activateRegistration(String key) { log.debug("Activating user for activation key {}", key); - return userRepository.findOneByActivationKey(key) - .map(user -> { - // activate given user for the registration key. - user.setActivated(true); - user.setActivationKey(null); - this.clearUserCaches(user); - log.debug("Activated user: {}", user); - return user; - }); + return userRepository + .findOneByActivationKey(key) + .map( + user -> { + // activate given user for the registration key. + user.setActivated(true); + user.setActivationKey(null); + this.clearUserCaches(user); + log.debug("Activated user: {}", user); + return user; + } + ); } public Optional completePasswordReset(String newPassword, String key) { log.debug("Reset user password for reset key {}", key); - return userRepository.findOneByResetKey(key) + return userRepository + .findOneByResetKey(key) .filter(user -> user.getResetDate().isAfter(Instant.now().minusSeconds(86400))) - .map(user -> { - user.setPassword(passwordEncoder.encode(newPassword)); - user.setResetKey(null); - user.setResetDate(null); - this.clearUserCaches(user); - return user; - }); + .map( + user -> { + user.setPassword(passwordEncoder.encode(newPassword)); + user.setResetKey(null); + user.setResetDate(null); + this.clearUserCaches(user); + return user; + } + ); } public Optional requestPasswordReset(String mail) { - return userRepository.findOneByEmailIgnoreCase(mail) + return userRepository + .findOneByEmailIgnoreCase(mail) .filter(User::getActivated) - .map(user -> { - user.setResetKey(RandomUtil.generateResetKey()); - user.setResetDate(Instant.now()); - this.clearUserCaches(user); - return user; - }); + .map( + user -> { + user.setResetKey(RandomUtil.generateResetKey()); + user.setResetDate(Instant.now()); + this.clearUserCaches(user); + return user; + } + ); } public String generatePasswordResetLink(String resetKey) { @@ -144,18 +156,26 @@ public String generatePasswordResetLink(String resetKey) { } public User registerUser(UserDTO userDTO, String password) { - userRepository.findOneByLogin(userDTO.getLogin().toLowerCase()).ifPresent(existingUser -> { - boolean removed = removeNonActivatedUser(existingUser); - if (!removed) { - throw new UsernameAlreadyUsedException(); - } - }); - userRepository.findOneByEmailIgnoreCase(userDTO.getEmail()).ifPresent(existingUser -> { - boolean removed = removeNonActivatedUser(existingUser); - if (!removed) { - throw new EmailAlreadyUsedException(); - } - }); + userRepository + .findOneByLogin(userDTO.getLogin().toLowerCase()) + .ifPresent( + existingUser -> { + boolean removed = removeNonActivatedUser(existingUser); + if (!removed) { + throw new UsernameAlreadyUsedException(); + } + } + ); + userRepository + .findOneByEmailIgnoreCase(userDTO.getEmail()) + .ifPresent( + existingUser -> { + boolean removed = removeNonActivatedUser(existingUser); + if (!removed) { + throw new EmailAlreadyUsedException(); + } + } + ); User newUser = new User(); String encryptedPassword = passwordEncoder.encode(password); newUser.setLogin(userDTO.getLogin().toLowerCase()); @@ -213,7 +233,9 @@ public User createUser(UserDTO userDTO) { user.setResetDate(Instant.now()); user.setActivated(true); if (userDTO.getAuthorities() != null) { - Set authorities = userDTO.getAuthorities().stream() + Set authorities = userDTO + .getAuthorities() + .stream() .map(authorityRepository::findById) .filter(Optional::isPresent) .map(Optional::get) @@ -236,19 +258,22 @@ public User createUser(UserDTO userDTO) { * @param imageUrl image URL of user. */ public void updateUser(String firstName, String lastName, String email, String langKey, String imageUrl) { - SecurityUtils.getCurrentUserLogin() + SecurityUtils + .getCurrentUserLogin() .flatMap(userRepository::findOneByLogin) - .ifPresent(user -> { - user.setFirstName(firstName); - user.setLastName(lastName); - if (email != null) { - user.setEmail(email.toLowerCase()); + .ifPresent( + user -> { + user.setFirstName(firstName); + user.setLastName(lastName); + if (email != null) { + user.setEmail(email.toLowerCase()); + } + user.setLangKey(langKey); + user.setImageUrl(imageUrl); + this.clearUserCaches(user); + log.debug("Changed Information for User: {}", user); } - user.setLangKey(langKey); - user.setImageUrl(imageUrl); - this.clearUserCaches(user); - log.debug("Changed Information for User: {}", user); - }); + ); } /** @@ -258,56 +283,65 @@ public void updateUser(String firstName, String lastName, String email, String l * @return updated user. */ public Optional updateUser(UserDTO userDTO) { - return Optional.of(userRepository - .findById(userDTO.getId())) + return Optional + .of(userRepository.findById(userDTO.getId())) .filter(Optional::isPresent) .map(Optional::get) - .map(user -> { - this.clearUserCaches(user); - user.setLogin(userDTO.getLogin().toLowerCase()); - user.setFirstName(userDTO.getFirstName()); - user.setLastName(userDTO.getLastName()); - if (userDTO.getEmail() != null) { - user.setEmail(userDTO.getEmail().toLowerCase()); + .map( + user -> { + this.clearUserCaches(user); + user.setLogin(userDTO.getLogin().toLowerCase()); + user.setFirstName(userDTO.getFirstName()); + user.setLastName(userDTO.getLastName()); + if (userDTO.getEmail() != null) { + user.setEmail(userDTO.getEmail().toLowerCase()); + } + user.setImageUrl(userDTO.getImageUrl()); + user.setActivated(userDTO.isActivated()); + user.setLangKey(userDTO.getLangKey()); + Set managedAuthorities = user.getAuthorities(); + managedAuthorities.clear(); + userDTO + .getAuthorities() + .stream() + .map(authorityRepository::findById) + .filter(Optional::isPresent) + .map(Optional::get) + .forEach(managedAuthorities::add); + this.clearUserCaches(user); + log.debug("Changed Information for User: {}", user); + return user; } - user.setImageUrl(userDTO.getImageUrl()); - user.setActivated(userDTO.isActivated()); - user.setLangKey(userDTO.getLangKey()); - Set managedAuthorities = user.getAuthorities(); - managedAuthorities.clear(); - userDTO.getAuthorities().stream() - .map(authorityRepository::findById) - .filter(Optional::isPresent) - .map(Optional::get) - .forEach(managedAuthorities::add); - this.clearUserCaches(user); - log.debug("Changed Information for User: {}", user); - return user; - }) + ) .map(UserDTO::new); } public void deleteUser(String login) { - userRepository.findOneByLogin(login).ifPresent(user -> { - for (JdlMetadata jdlMetadata : jdlMetadataService.findAllForUser(user)) { - jdlService.deleteAllForJdlMetadata(jdlMetadata.getId()); - } - jdlMetadataService.deleteAllForUser(user); - if (githubService.isEnabled()) { - githubService.deleteAllOrganizationsUser(user); - } - if (gitlabService.isEnabled()) { - gitlabService.deleteAllOrganizationsUser(user); - } - userRepository.delete(user); - this.clearUserCaches(user); - log.debug("Deleted User: {}", user); - }); + userRepository + .findOneByLogin(login) + .ifPresent( + user -> { + for (JdlMetadata jdlMetadata : jdlMetadataService.findAllForUser(user)) { + jdlService.deleteAllForJdlMetadata(jdlMetadata.getId()); + } + jdlMetadataService.deleteAllForUser(user); + if (githubService.isEnabled()) { + githubService.deleteAllOrganizationsUser(user); + } + if (gitlabService.isEnabled()) { + gitlabService.deleteAllOrganizationsUser(user); + } + userRepository.delete(user); + this.clearUserCaches(user); + log.debug("Deleted User: {}", user); + } + ); } public void saveToken(String code, GitProvider gitProvider) throws Exception { - User user = userRepository.findOneByLogin(SecurityUtils.getCurrentUserLogin().orElse(null)).orElseThrow(() -> - new Exception("No authenticated user can be found.")); + User user = userRepository + .findOneByLogin(SecurityUtils.getCurrentUserLogin().orElse(null)) + .orElseThrow(() -> new Exception("No authenticated user can be found.")); if (gitProvider.equals(GitProvider.GITHUB)) { user.setGithubOAuthToken(code); @@ -322,18 +356,21 @@ public void saveToken(String code, GitProvider gitProvider) throws Exception { } public void changePassword(String currentClearTextPassword, String newPassword) { - SecurityUtils.getCurrentUserLogin() + SecurityUtils + .getCurrentUserLogin() .flatMap(userRepository::findOneByLogin) - .ifPresent(user -> { - String currentEncryptedPassword = user.getPassword(); - if (!passwordEncoder.matches(currentClearTextPassword, currentEncryptedPassword)) { - throw new InvalidPasswordException(); + .ifPresent( + user -> { + String currentEncryptedPassword = user.getPassword(); + if (!passwordEncoder.matches(currentClearTextPassword, currentEncryptedPassword)) { + throw new InvalidPasswordException(); + } + String encryptedPassword = passwordEncoder.encode(newPassword); + user.setPassword(encryptedPassword); + this.clearUserCaches(user); + log.debug("Changed password for User: {}", user); } - String encryptedPassword = passwordEncoder.encode(newPassword); - user.setPassword(encryptedPassword); - this.clearUserCaches(user); - log.debug("Changed password for User: {}", user); - }); + ); } @Transactional(readOnly = true) @@ -376,8 +413,7 @@ public List getProjects(String organizationName, GitProvider gitProvider if (organizations.size() == 0) { return Collections.emptyList(); } - Optional organization = organizations.stream().filter(test -> test.getName().equals - (organizationName)).findFirst(); + Optional organization = organizations.stream().filter(test -> test.getName().equals(organizationName)).findFirst(); if (organization.isEmpty()) { return Collections.emptyList(); } else { @@ -406,11 +442,13 @@ public Optional getUserWithAuthorities() { public void removeNotActivatedUsers() { userRepository .findAllByActivatedIsFalseAndActivationKeyIsNotNullAndCreatedDateBefore(Instant.now().minus(3, ChronoUnit.DAYS)) - .forEach(user -> { - log.debug("Deleting not activated user {}", user.getLogin()); - userRepository.delete(user); - this.clearUserCaches(user); - }); + .forEach( + user -> { + log.debug("Deleting not activated user {}", user.getLogin()); + userRepository.delete(user); + this.clearUserCaches(user); + } + ); } /** diff --git a/src/main/java/io/github/jhipster/online/service/UsernameAlreadyUsedException.java b/src/main/java/io/github/jhipster/online/service/UsernameAlreadyUsedException.java index 930f771c..3a0026c4 100644 --- a/src/main/java/io/github/jhipster/online/service/UsernameAlreadyUsedException.java +++ b/src/main/java/io/github/jhipster/online/service/UsernameAlreadyUsedException.java @@ -7,5 +7,4 @@ public class UsernameAlreadyUsedException extends RuntimeException { public UsernameAlreadyUsedException() { super("Login name already used!"); } - } diff --git a/src/main/java/io/github/jhipster/online/service/YoRCService.java b/src/main/java/io/github/jhipster/online/service/YoRCService.java index 681ad434..8f90ef7a 100644 --- a/src/main/java/io/github/jhipster/online/service/YoRCService.java +++ b/src/main/java/io/github/jhipster/online/service/YoRCService.java @@ -33,21 +33,20 @@ import io.github.jhipster.online.service.enums.TemporalValueType; import io.github.jhipster.online.service.mapper.YoRCMapper; import io.github.jhipster.online.service.util.QueryUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.cache.annotation.Cacheable; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - +import java.io.IOException; +import java.time.Instant; +import java.util.List; +import java.util.Optional; import javax.persistence.EntityManager; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.ParameterExpression; import javax.persistence.criteria.Root; -import java.io.IOException; -import java.time.Instant; -import java.util.List; -import java.util.Optional; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.cache.annotation.Cacheable; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; /** * Service Implementation for managing YoRC. @@ -153,7 +152,8 @@ public List getCount(Instant after, TemporalValueType dbTempor Root root = query.from(YoRC.class); ParameterExpression parameter = builder.parameter(Instant.class, QueryUtil.DATE); - query.select(builder.construct(RawSQL.class, root.get(dbTemporalFunction.getFieldName()), builder.count(root))) + query + .select(builder.construct(RawSQL.class, root.get(dbTemporalFunction.getFieldName()), builder.count(root))) .where(builder.greaterThan(root.get(YoRC_.creationDate).as(Instant.class), parameter)) .groupBy(root.get(dbTemporalFunction.getFieldName())); @@ -166,11 +166,18 @@ public List getFieldCount(Instant after, YoRCColumn fie Root root = query.from(YoRC.class); ParameterExpression parameter = builder.parameter(Instant.class, QueryUtil.DATE); - query.select(builder.construct(RawSQLField.class, root.get(dbTemporalFunction.getFieldName()), root.get(field.getDatabaseValue()), builder.count(root))) + query + .select( + builder.construct( + RawSQLField.class, + root.get(dbTemporalFunction.getFieldName()), + root.get(field.getDatabaseValue()), + builder.count(root) + ) + ) .where(builder.greaterThan(root.get(YoRC_.creationDate).as(Instant.class), parameter)) .groupBy(root.get(field.getDatabaseValue()), root.get(dbTemporalFunction.getFieldName())); return QueryUtil.createDistributionQueryAndCollectData(after, dbTemporalFunction, query, entityManager); } - } diff --git a/src/main/java/io/github/jhipster/online/service/dto/EntityStatsDTO.java b/src/main/java/io/github/jhipster/online/service/dto/EntityStatsDTO.java index bb6685cb..a6b46032 100644 --- a/src/main/java/io/github/jhipster/online/service/dto/EntityStatsDTO.java +++ b/src/main/java/io/github/jhipster/online/service/dto/EntityStatsDTO.java @@ -7,6 +7,7 @@ * A DTO for the {@link io.github.jhipster.online.domain.EntityStats} entity. */ public class EntityStatsDTO implements Serializable { + private Long id; private Integer year; @@ -139,21 +140,38 @@ public void setDate(Instant date) { @Override public String toString() { - return "EntityStatsDTO{" + - "id=" + id + - ", year=" + year + - ", month=" + month + - ", week=" + week + - ", day=" + day + - ", hour=" + hour + - ", fields=" + fields + - ", relationships=" + relationships + - ", pagination='" + pagination + '\'' + - ", dto='" + dto + '\'' + - ", service='" + service + '\'' + - ", fluentMethods=" + fluentMethods + - ", date=" + date + - '}'; + return ( + "EntityStatsDTO{" + + "id=" + + id + + ", year=" + + year + + ", month=" + + month + + ", week=" + + week + + ", day=" + + day + + ", hour=" + + hour + + ", fields=" + + fields + + ", relationships=" + + relationships + + ", pagination='" + + pagination + + '\'' + + ", dto='" + + dto + + '\'' + + ", service='" + + service + + '\'' + + ", fluentMethods=" + + fluentMethods + + ", date=" + + date + + '}' + ); } } - diff --git a/src/main/java/io/github/jhipster/online/service/dto/GeneratorIdentityDTO.java b/src/main/java/io/github/jhipster/online/service/dto/GeneratorIdentityDTO.java index e4bce664..44c9380c 100644 --- a/src/main/java/io/github/jhipster/online/service/dto/GeneratorIdentityDTO.java +++ b/src/main/java/io/github/jhipster/online/service/dto/GeneratorIdentityDTO.java @@ -1,13 +1,13 @@ package io.github.jhipster.online.service.dto; import io.github.jhipster.online.domain.User; - import java.io.Serializable; /** * A DTO for the {@link io.github.jhipster.online.domain.GeneratorIdentity} entity. */ public class GeneratorIdentityDTO implements Serializable { + private Long id; private String host; @@ -55,11 +55,6 @@ public GeneratorIdentityDTO guid(String guid) { @Override public String toString() { - return "GeneratorIdentityDTO{" + - "id=" + id + - ", host='" + host + '\'' + - ", guid='" + guid + '\'' + - ", owner=" + owner + - '}'; + return "GeneratorIdentityDTO{" + "id=" + id + ", host='" + host + '\'' + ", guid='" + guid + '\'' + ", owner=" + owner + '}'; } } diff --git a/src/main/java/io/github/jhipster/online/service/dto/GitConfigurationDTO.java b/src/main/java/io/github/jhipster/online/service/dto/GitConfigurationDTO.java index bfcefbd9..745f339c 100644 --- a/src/main/java/io/github/jhipster/online/service/dto/GitConfigurationDTO.java +++ b/src/main/java/io/github/jhipster/online/service/dto/GitConfigurationDTO.java @@ -41,13 +41,17 @@ public class GitConfigurationDTO { private boolean gitlabConfigured; - public GitConfigurationDTO(String githubHost, - String githubClientId, - boolean githubAvailable, - String gitlabHost, - String gitlabRedirectUri, - String gitlabClientId, - boolean gitlabAvailable, boolean githubConfigured, boolean gitlabConfigured) { + public GitConfigurationDTO( + String githubHost, + String githubClientId, + boolean githubAvailable, + String gitlabHost, + String gitlabRedirectUri, + String gitlabClientId, + boolean gitlabAvailable, + boolean githubConfigured, + boolean gitlabConfigured + ) { this.githubHost = githubHost; this.githubClientId = githubClientId; this.githubAvailable = githubAvailable; @@ -133,29 +137,19 @@ public void setGithubConfigured(boolean githubConfigured) { @Override public boolean equals(Object o) { - if (this == o) - return true; - if (o == null || getClass() != o.getClass()) - return false; + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; GitConfigurationDTO that = (GitConfigurationDTO) o; - if (githubAvailable != that.githubAvailable) - return false; - if (gitlabAvailable != that.gitlabAvailable) - return false; - if (githubConfigured != that.githubConfigured) - return false; - if (gitlabConfigured != that.gitlabConfigured) - return false; - if (!Objects.equals(githubHost, that.githubHost)) - return false; - if (!Objects.equals(githubClientId, that.githubClientId)) - return false; - if (!Objects.equals(gitlabHost, that.gitlabHost)) - return false; - if (!Objects.equals(gitlabRedirectUri, that.gitlabRedirectUri)) - return false; + if (githubAvailable != that.githubAvailable) return false; + if (gitlabAvailable != that.gitlabAvailable) return false; + if (githubConfigured != that.githubConfigured) return false; + if (gitlabConfigured != that.gitlabConfigured) return false; + if (!Objects.equals(githubHost, that.githubHost)) return false; + if (!Objects.equals(githubClientId, that.githubClientId)) return false; + if (!Objects.equals(gitlabHost, that.gitlabHost)) return false; + if (!Objects.equals(gitlabRedirectUri, that.gitlabRedirectUri)) return false; return Objects.equals(gitlabClientId, that.gitlabClientId); } @@ -175,16 +169,32 @@ public int hashCode() { @Override public String toString() { - return "GitConfigurationDTO{" + - "githubHost='" + githubHost + '\'' + - ", githubClientId='" + githubClientId + '\'' + - ", githubAvailable=" + githubAvailable + - ", gitlabHost='" + gitlabHost + '\'' + - ", gitlabRedirectUri='" + gitlabRedirectUri + '\'' + - ", gitlabClientId='" + gitlabClientId + '\'' + - ", gitlabAvailable=" + gitlabAvailable + - ", githubConfigured=" + githubConfigured + - ", gitlabConfigured=" + gitlabConfigured + - '}'; + return ( + "GitConfigurationDTO{" + + "githubHost='" + + githubHost + + '\'' + + ", githubClientId='" + + githubClientId + + '\'' + + ", githubAvailable=" + + githubAvailable + + ", gitlabHost='" + + gitlabHost + + '\'' + + ", gitlabRedirectUri='" + + gitlabRedirectUri + + '\'' + + ", gitlabClientId='" + + gitlabClientId + + '\'' + + ", gitlabAvailable=" + + gitlabAvailable + + ", githubConfigured=" + + githubConfigured + + ", gitlabConfigured=" + + gitlabConfigured + + '}' + ); } } diff --git a/src/main/java/io/github/jhipster/online/service/dto/JdlMetadataDTO.java b/src/main/java/io/github/jhipster/online/service/dto/JdlMetadataDTO.java index a6aaeb80..f8c7d2eb 100644 --- a/src/main/java/io/github/jhipster/online/service/dto/JdlMetadataDTO.java +++ b/src/main/java/io/github/jhipster/online/service/dto/JdlMetadataDTO.java @@ -7,6 +7,7 @@ * A DTO for the {@link io.github.jhipster.online.domain.JdlMetadata} entity. */ public class JdlMetadataDTO implements Serializable { + private String id; private String name; @@ -59,12 +60,21 @@ public void setPublic(Boolean aPublic) { @Override public String toString() { - return "JdlMetadataDTO{" + - "id='" + id + '\'' + - ", name='" + name + '\'' + - ", createdDate=" + createdDate + - ", updatedDate=" + updatedDate + - ", isPublic=" + isPublic + - '}'; + return ( + "JdlMetadataDTO{" + + "id='" + + id + + '\'' + + ", name='" + + name + + '\'' + + ", createdDate=" + + createdDate + + ", updatedDate=" + + updatedDate + + ", isPublic=" + + isPublic + + '}' + ); } } diff --git a/src/main/java/io/github/jhipster/online/service/dto/PasswordChangeDTO.java b/src/main/java/io/github/jhipster/online/service/dto/PasswordChangeDTO.java index 228841b8..28ed308e 100644 --- a/src/main/java/io/github/jhipster/online/service/dto/PasswordChangeDTO.java +++ b/src/main/java/io/github/jhipster/online/service/dto/PasswordChangeDTO.java @@ -23,6 +23,7 @@ * A DTO representing a password change required data - current and new password. */ public class PasswordChangeDTO { + private String currentPassword; private String newPassword; @@ -36,7 +37,6 @@ public PasswordChangeDTO(String currentPassword, String newPassword) { } public String getCurrentPassword() { - return currentPassword; } diff --git a/src/main/java/io/github/jhipster/online/service/dto/RawSQL.java b/src/main/java/io/github/jhipster/online/service/dto/RawSQL.java index 7b132cd1..1f84eea8 100644 --- a/src/main/java/io/github/jhipster/online/service/dto/RawSQL.java +++ b/src/main/java/io/github/jhipster/online/service/dto/RawSQL.java @@ -53,8 +53,7 @@ public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; RawSQL rawSQL = (RawSQL) o; - return Objects.equals(moment, rawSQL.moment) && - Objects.equals(count, rawSQL.count); + return Objects.equals(moment, rawSQL.moment) && Objects.equals(count, rawSQL.count); } @Override @@ -64,9 +63,6 @@ public int hashCode() { @Override public String toString() { - return "RawSQL{" + - "moment=" + moment + - ", count=" + count + - '}'; + return "RawSQL{" + "moment=" + moment + ", count=" + count + '}'; } } diff --git a/src/main/java/io/github/jhipster/online/service/dto/RawSQLField.java b/src/main/java/io/github/jhipster/online/service/dto/RawSQLField.java index 0864f81f..b60a184f 100644 --- a/src/main/java/io/github/jhipster/online/service/dto/RawSQLField.java +++ b/src/main/java/io/github/jhipster/online/service/dto/RawSQLField.java @@ -59,10 +59,6 @@ public void setCount(Long count) { @Override public String toString() { - return "RawSQLField{" + - "moment=" + moment + - ", field='" + field + '\'' + - ", count=" + count + - '}'; + return "RawSQLField{" + "moment=" + moment + ", field='" + field + '\'' + ", count=" + count + '}'; } } diff --git a/src/main/java/io/github/jhipster/online/service/dto/SubGenEventDTO.java b/src/main/java/io/github/jhipster/online/service/dto/SubGenEventDTO.java index 18b905a3..5be88b00 100644 --- a/src/main/java/io/github/jhipster/online/service/dto/SubGenEventDTO.java +++ b/src/main/java/io/github/jhipster/online/service/dto/SubGenEventDTO.java @@ -7,6 +7,7 @@ * A DTO for the {@link io.github.jhipster.online.domain.SubGenEvent} entity. */ public class SubGenEventDTO implements Serializable { + private Long id; private Integer year; @@ -109,17 +110,32 @@ public void setDate(Instant date) { @Override public String toString() { - return "SubGenEventDTO{" + - "id=" + id + - ", year=" + year + - ", month=" + month + - ", week=" + week + - ", day=" + day + - ", hour=" + hour + - ", source='" + source + '\'' + - ", type='" + type + '\'' + - ", event='" + event + '\'' + - ", date=" + date + - '}'; + return ( + "SubGenEventDTO{" + + "id=" + + id + + ", year=" + + year + + ", month=" + + month + + ", week=" + + week + + ", day=" + + day + + ", hour=" + + hour + + ", source='" + + source + + '\'' + + ", type='" + + type + + '\'' + + ", event='" + + event + + '\'' + + ", date=" + + date + + '}' + ); } } diff --git a/src/main/java/io/github/jhipster/online/service/dto/TemporalCountDTO.java b/src/main/java/io/github/jhipster/online/service/dto/TemporalCountDTO.java index 793f3631..9e8eafe7 100644 --- a/src/main/java/io/github/jhipster/online/service/dto/TemporalCountDTO.java +++ b/src/main/java/io/github/jhipster/online/service/dto/TemporalCountDTO.java @@ -54,11 +54,9 @@ public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TemporalCountDTO that = (TemporalCountDTO) o; - return Objects.equals(date, that.date) && - Objects.equals(count, that.count); + return Objects.equals(date, that.date) && Objects.equals(count, that.count); } - @Override public int hashCode() { return Objects.hash(date, count); @@ -66,10 +64,7 @@ public int hashCode() { @Override public String toString() { - return "TemporalCountDTO{" + - "date=" + date + - ", count=" + count + - '}'; + return "TemporalCountDTO{" + "date=" + date + ", count=" + count + '}'; } @Override diff --git a/src/main/java/io/github/jhipster/online/service/dto/UserDTO.java b/src/main/java/io/github/jhipster/online/service/dto/UserDTO.java index 313fd727..543d101a 100644 --- a/src/main/java/io/github/jhipster/online/service/dto/UserDTO.java +++ b/src/main/java/io/github/jhipster/online/service/dto/UserDTO.java @@ -22,14 +22,13 @@ import io.github.jhipster.online.config.Constants; import io.github.jhipster.online.domain.Authority; import io.github.jhipster.online.domain.User; - +import java.time.Instant; +import java.util.Set; +import java.util.stream.Collectors; import javax.validation.constraints.Email; import javax.validation.constraints.NotBlank; import javax.validation.constraints.Pattern; import javax.validation.constraints.Size; -import java.time.Instant; -import java.util.Set; -import java.util.stream.Collectors; /** * A DTO representing a user, with his authorities. @@ -88,9 +87,7 @@ public UserDTO(User user) { this.createdDate = user.getCreatedDate(); this.lastModifiedBy = user.getLastModifiedBy(); this.lastModifiedDate = user.getLastModifiedDate(); - this.authorities = user.getAuthorities().stream() - .map(Authority::getName) - .collect(Collectors.toSet()); + this.authorities = user.getAuthorities().stream().map(Authority::getName).collect(Collectors.toSet()); } public Long getId() { @@ -199,19 +196,40 @@ public void setAuthorities(Set authorities) { @Override public String toString() { - return "UserDTO{" + - "login='" + login + '\'' + - ", firstName='" + firstName + '\'' + - ", lastName='" + lastName + '\'' + - ", email='" + email + '\'' + - ", imageUrl='" + imageUrl + '\'' + - ", activated=" + activated + - ", langKey='" + langKey + '\'' + - ", createdBy=" + createdBy + - ", createdDate=" + createdDate + - ", lastModifiedBy='" + lastModifiedBy + '\'' + - ", lastModifiedDate=" + lastModifiedDate + - ", authorities=" + authorities + - "}"; + return ( + "UserDTO{" + + "login='" + + login + + '\'' + + ", firstName='" + + firstName + + '\'' + + ", lastName='" + + lastName + + '\'' + + ", email='" + + email + + '\'' + + ", imageUrl='" + + imageUrl + + '\'' + + ", activated=" + + activated + + ", langKey='" + + langKey + + '\'' + + ", createdBy=" + + createdBy + + ", createdDate=" + + createdDate + + ", lastModifiedBy='" + + lastModifiedBy + + '\'' + + ", lastModifiedDate=" + + lastModifiedDate + + ", authorities=" + + authorities + + "}" + ); } } diff --git a/src/main/java/io/github/jhipster/online/service/dto/YoRCDTO.java b/src/main/java/io/github/jhipster/online/service/dto/YoRCDTO.java index eb716983..ef05d8d9 100644 --- a/src/main/java/io/github/jhipster/online/service/dto/YoRCDTO.java +++ b/src/main/java/io/github/jhipster/online/service/dto/YoRCDTO.java @@ -7,6 +7,7 @@ * A DTO for the {@link io.github.jhipster.online.domain.YoRC} entity. */ public class YoRCDTO implements Serializable { + private Long id; private String jhipsterVersion; @@ -399,46 +400,108 @@ public void setHasCucumber(Boolean hasCucumber) { @Override public String toString() { - return "YoRCDTO{" + - "id=" + id + - ", jhipsterVersion='" + jhipsterVersion + '\'' + - ", creationDate=" + creationDate + - ", gitProvider='" + gitProvider + '\'' + - ", nodeVersion='" + nodeVersion + '\'' + - ", os='" + os + '\'' + - ", arch='" + arch + '\'' + - ", cpu='" + cpu + '\'' + - ", cores='" + cores + '\'' + - ", memory='" + memory + '\'' + - ", userLanguage='" + userLanguage + '\'' + - ", year=" + year + - ", month=" + month + - ", week=" + week + - ", day=" + day + - ", hour=" + hour + - ", serverPort='" + serverPort + '\'' + - ", authenticationType='" + authenticationType + '\'' + - ", cacheProvider='" + cacheProvider + '\'' + - ", enableHibernateCache=" + enableHibernateCache + - ", websocket=" + websocket + - ", databaseType='" + databaseType + '\'' + - ", devDatabaseType='" + devDatabaseType + '\'' + - ", prodDatabaseType='" + prodDatabaseType + '\'' + - ", searchEngine=" + searchEngine + - ", messageBroker=" + messageBroker + - ", serviceDiscoveryType=" + serviceDiscoveryType + - ", buildTool='" + buildTool + '\'' + - ", enableSwaggerCodegen=" + enableSwaggerCodegen + - ", clientFramework='" + clientFramework + '\'' + - ", useSass=" + useSass + - ", clientPackageManager='" + clientPackageManager + '\'' + - ", applicationType='" + applicationType + '\'' + - ", jhiPrefix='" + jhiPrefix + '\'' + - ", enableTranslation=" + enableTranslation + - ", nativeLanguage='" + nativeLanguage + '\'' + - ", hasProtractor=" + hasProtractor + - ", hasGatling=" + hasGatling + - ", hasCucumber=" + hasCucumber + - '}'; + return ( + "YoRCDTO{" + + "id=" + + id + + ", jhipsterVersion='" + + jhipsterVersion + + '\'' + + ", creationDate=" + + creationDate + + ", gitProvider='" + + gitProvider + + '\'' + + ", nodeVersion='" + + nodeVersion + + '\'' + + ", os='" + + os + + '\'' + + ", arch='" + + arch + + '\'' + + ", cpu='" + + cpu + + '\'' + + ", cores='" + + cores + + '\'' + + ", memory='" + + memory + + '\'' + + ", userLanguage='" + + userLanguage + + '\'' + + ", year=" + + year + + ", month=" + + month + + ", week=" + + week + + ", day=" + + day + + ", hour=" + + hour + + ", serverPort='" + + serverPort + + '\'' + + ", authenticationType='" + + authenticationType + + '\'' + + ", cacheProvider='" + + cacheProvider + + '\'' + + ", enableHibernateCache=" + + enableHibernateCache + + ", websocket=" + + websocket + + ", databaseType='" + + databaseType + + '\'' + + ", devDatabaseType='" + + devDatabaseType + + '\'' + + ", prodDatabaseType='" + + prodDatabaseType + + '\'' + + ", searchEngine=" + + searchEngine + + ", messageBroker=" + + messageBroker + + ", serviceDiscoveryType=" + + serviceDiscoveryType + + ", buildTool='" + + buildTool + + '\'' + + ", enableSwaggerCodegen=" + + enableSwaggerCodegen + + ", clientFramework='" + + clientFramework + + '\'' + + ", useSass=" + + useSass + + ", clientPackageManager='" + + clientPackageManager + + '\'' + + ", applicationType='" + + applicationType + + '\'' + + ", jhiPrefix='" + + jhiPrefix + + '\'' + + ", enableTranslation=" + + enableTranslation + + ", nativeLanguage='" + + nativeLanguage + + '\'' + + ", hasProtractor=" + + hasProtractor + + ", hasGatling=" + + hasGatling + + ", hasCucumber=" + + hasCucumber + + '}' + ); } } diff --git a/src/main/java/io/github/jhipster/online/service/enums/CiCdTool.java b/src/main/java/io/github/jhipster/online/service/enums/CiCdTool.java index da41a725..a6a8ee65 100644 --- a/src/main/java/io/github/jhipster/online/service/enums/CiCdTool.java +++ b/src/main/java/io/github/jhipster/online/service/enums/CiCdTool.java @@ -1,11 +1,10 @@ package io.github.jhipster.online.service.enums; -import org.apache.commons.lang3.StringUtils; +import static java.text.MessageFormat.format; import java.util.Optional; import java.util.stream.Stream; - -import static java.text.MessageFormat.format; +import org.apache.commons.lang3.StringUtils; public enum CiCdTool { TRAVIS, @@ -15,20 +14,15 @@ public enum CiCdTool { GITHUB; public static Optional getByName(String name) { - return Stream - .of(values()) - .filter(ciCdTool -> ciCdTool.name().equalsIgnoreCase(name)) - .findFirst(); + return Stream.of(values()).filter(ciCdTool -> ciCdTool.name().equalsIgnoreCase(name)).findFirst(); } - - public String command() { return name().toLowerCase(); } public String branchName(String complement) { - return format("{0}-{1}-{2}" ,"jhipster", name().toLowerCase(), complement); + return format("{0}-{1}-{2}", "jhipster", name().toLowerCase(), complement); } public String capitalize() { diff --git a/src/main/java/io/github/jhipster/online/service/enums/TemporalValueType.java b/src/main/java/io/github/jhipster/online/service/enums/TemporalValueType.java index 51d758e0..62ae14ed 100644 --- a/src/main/java/io/github/jhipster/online/service/enums/TemporalValueType.java +++ b/src/main/java/io/github/jhipster/online/service/enums/TemporalValueType.java @@ -19,17 +19,17 @@ package io.github.jhipster.online.service.enums; +import static java.time.Instant.parse; + import java.time.Duration; import java.time.Instant; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.time.temporal.ChronoUnit; -import static java.time.Instant.parse; - public enum TemporalValueType { YEAR("year", ChronoUnit.DAYS, 365), - MONTH("month",ChronoUnit.DAYS, 31), + MONTH("month", ChronoUnit.DAYS, 31), WEEK("week", ChronoUnit.DAYS, 7), DAY("day", ChronoUnit.DAYS, 1), HOUR("hour", ChronoUnit.HOURS, 1); @@ -69,11 +69,13 @@ public static Instant absoluteMomentToInstant(Long value, TemporalValueType valu return parse(yearFromMonthValue + "-" + actualMonth + "-01T00:00:00.000Z"); case WEEK: case DAY: - return ZonedDateTime.ofInstant(Instant.ofEpochMilli(0), ZoneOffset.UTC) + return ZonedDateTime + .ofInstant(Instant.ofEpochMilli(0), ZoneOffset.UTC) .plus(Duration.of(value * valueType.getDayMultiplier(), ChronoUnit.DAYS)) .toInstant(); case HOUR: - return ZonedDateTime.ofInstant(Instant.ofEpochMilli(0), ZoneOffset.UTC) + return ZonedDateTime + .ofInstant(Instant.ofEpochMilli(0), ZoneOffset.UTC) .plus(Duration.of(value * valueType.getDayMultiplier(), valueType.getUnit())) .toInstant(); default: diff --git a/src/main/java/io/github/jhipster/online/service/interfaces/GitProviderService.java b/src/main/java/io/github/jhipster/online/service/interfaces/GitProviderService.java index 01eeea6a..7e213fa3 100644 --- a/src/main/java/io/github/jhipster/online/service/interfaces/GitProviderService.java +++ b/src/main/java/io/github/jhipster/online/service/interfaces/GitProviderService.java @@ -19,11 +19,9 @@ package io.github.jhipster.online.service.interfaces; import io.github.jhipster.online.domain.User; - import java.io.IOException; public interface GitProviderService { - boolean isEnabled(); String getHost(); @@ -34,12 +32,16 @@ public interface GitProviderService { User getSyncedUserFromGitProvider(User user) throws IOException; - void createGitProviderRepository(User user, String applicationId, String applicationConfiguration, String - organization, String repositoryName); + void createGitProviderRepository( + User user, + String applicationId, + String applicationConfiguration, + String organization, + String repositoryName + ); - int createPullRequest(User user, String organization, String applicationName, - String title, String branchName, String body) throws IOException; + int createPullRequest(User user, String organization, String applicationName, String title, String branchName, String body) + throws IOException; boolean isConfigured(); - } diff --git a/src/main/java/io/github/jhipster/online/service/mapper/EntityMapper.java b/src/main/java/io/github/jhipster/online/service/mapper/EntityMapper.java index d7bf4440..9e534e63 100644 --- a/src/main/java/io/github/jhipster/online/service/mapper/EntityMapper.java +++ b/src/main/java/io/github/jhipster/online/service/mapper/EntityMapper.java @@ -10,12 +10,11 @@ */ public interface EntityMapper { - E toEntity(D dto); D toDto(E entity); - List toEntity(List dtoList); + List toEntity(List dtoList); - List toDto(List entityList); + List toDto(List entityList); } diff --git a/src/main/java/io/github/jhipster/online/service/mapper/EntityStatsMapper.java b/src/main/java/io/github/jhipster/online/service/mapper/EntityStatsMapper.java index eec83e12..9fbee441 100644 --- a/src/main/java/io/github/jhipster/online/service/mapper/EntityStatsMapper.java +++ b/src/main/java/io/github/jhipster/online/service/mapper/EntityStatsMapper.java @@ -9,7 +9,6 @@ */ @Mapper(componentModel = "spring") public interface EntityStatsMapper extends EntityMapper { - default EntityStats fromId(Long id) { if (id == null) { return null; diff --git a/src/main/java/io/github/jhipster/online/service/mapper/GeneratorIdentityMapper.java b/src/main/java/io/github/jhipster/online/service/mapper/GeneratorIdentityMapper.java index 60b4932d..19d336ed 100644 --- a/src/main/java/io/github/jhipster/online/service/mapper/GeneratorIdentityMapper.java +++ b/src/main/java/io/github/jhipster/online/service/mapper/GeneratorIdentityMapper.java @@ -6,7 +6,6 @@ @Mapper(componentModel = "spring") public interface GeneratorIdentityMapper extends EntityMapper { - default GeneratorIdentity fromId(Long id) { if (id == null) { return null; diff --git a/src/main/java/io/github/jhipster/online/service/mapper/JdlMetadataMapper.java b/src/main/java/io/github/jhipster/online/service/mapper/JdlMetadataMapper.java index 2a7dc106..e4b68e0a 100644 --- a/src/main/java/io/github/jhipster/online/service/mapper/JdlMetadataMapper.java +++ b/src/main/java/io/github/jhipster/online/service/mapper/JdlMetadataMapper.java @@ -6,7 +6,6 @@ @Mapper(componentModel = "spring") public interface JdlMetadataMapper extends EntityMapper { - default JdlMetadata fromId(String id) { if (id == null) { return null; diff --git a/src/main/java/io/github/jhipster/online/service/mapper/SubGenEventMapper.java b/src/main/java/io/github/jhipster/online/service/mapper/SubGenEventMapper.java index b4d8943b..bf484899 100644 --- a/src/main/java/io/github/jhipster/online/service/mapper/SubGenEventMapper.java +++ b/src/main/java/io/github/jhipster/online/service/mapper/SubGenEventMapper.java @@ -6,7 +6,6 @@ @Mapper(componentModel = "spring") public interface SubGenEventMapper extends EntityMapper { - default SubGenEvent fromId(Long id) { if (id == null) { return null; diff --git a/src/main/java/io/github/jhipster/online/service/mapper/UserMapper.java b/src/main/java/io/github/jhipster/online/service/mapper/UserMapper.java index aad61cef..4cad0a2d 100644 --- a/src/main/java/io/github/jhipster/online/service/mapper/UserMapper.java +++ b/src/main/java/io/github/jhipster/online/service/mapper/UserMapper.java @@ -18,13 +18,12 @@ import io.github.jhipster.online.domain.Authority; import io.github.jhipster.online.domain.User; import io.github.jhipster.online.service.dto.UserDTO; -import org.springframework.stereotype.Service; - import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; +import org.springframework.stereotype.Service; /** * Mapper for the entity {@link User} and its DTO called {@link UserDTO}. @@ -36,10 +35,7 @@ public class UserMapper { public List usersToUserDTOs(List users) { - return users.stream() - .filter(Objects::nonNull) - .map(this::userToUserDTO) - .collect(Collectors.toList()); + return users.stream().filter(Objects::nonNull).map(this::userToUserDTO).collect(Collectors.toList()); } public UserDTO userToUserDTO(User user) { @@ -47,10 +43,7 @@ public UserDTO userToUserDTO(User user) { } public List userDTOsToUsers(List userDTOs) { - return userDTOs.stream() - .filter(Objects::nonNull) - .map(this::userDTOToUser) - .collect(Collectors.toList()); + return userDTOs.stream().filter(Objects::nonNull).map(this::userDTOToUser).collect(Collectors.toList()); } public User userDTOToUser(UserDTO userDTO) { @@ -72,16 +65,21 @@ public User userDTOToUser(UserDTO userDTO) { } } - private Set authoritiesFromStrings(Set authoritiesAsString) { Set authorities = new HashSet<>(); if (authoritiesAsString != null) { - authorities = authoritiesAsString.stream().map(string -> { - Authority auth = new Authority(); - auth.setName(string); - return auth; - }).collect(Collectors.toSet()); + authorities = + authoritiesAsString + .stream() + .map( + string -> { + Authority auth = new Authority(); + auth.setName(string); + return auth; + } + ) + .collect(Collectors.toSet()); } return authorities; diff --git a/src/main/java/io/github/jhipster/online/service/mapper/YoRCMapper.java b/src/main/java/io/github/jhipster/online/service/mapper/YoRCMapper.java index 3eb1d225..50ef7271 100644 --- a/src/main/java/io/github/jhipster/online/service/mapper/YoRCMapper.java +++ b/src/main/java/io/github/jhipster/online/service/mapper/YoRCMapper.java @@ -6,7 +6,6 @@ @Mapper(componentModel = "spring") public interface YoRCMapper extends EntityMapper { - default YoRC fromId(Long id) { if (id == null) { return null; diff --git a/src/main/java/io/github/jhipster/online/service/util/QueryUtil.java b/src/main/java/io/github/jhipster/online/service/util/QueryUtil.java index 53d6420c..baa61c57 100644 --- a/src/main/java/io/github/jhipster/online/service/util/QueryUtil.java +++ b/src/main/java/io/github/jhipster/online/service/util/QueryUtil.java @@ -24,14 +24,13 @@ import io.github.jhipster.online.service.dto.TemporalCountDTO; import io.github.jhipster.online.service.dto.TemporalDistributionDTO; import io.github.jhipster.online.service.enums.TemporalValueType; - -import javax.persistence.EntityManager; -import javax.persistence.criteria.CriteriaQuery; import java.time.Instant; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.stream.Collectors; +import javax.persistence.EntityManager; +import javax.persistence.criteria.CriteriaQuery; public final class QueryUtil { @@ -43,10 +42,12 @@ private QueryUtil() { throw new IllegalStateException("Utility class"); } - public static List createDistributionQueryAndCollectData(Instant after, - TemporalValueType dbTemporalFunction, - CriteriaQuery query, - EntityManager entityManager) { + public static List createDistributionQueryAndCollectData( + Instant after, + TemporalValueType dbTemporalFunction, + CriteriaQuery query, + EntityManager entityManager + ) { return entityManager .createQuery(query) .setParameter(DATE, after) @@ -55,25 +56,35 @@ public static List createDistributionQueryAndCollectDat .collect(Collectors.groupingBy(RawSQLField::getMoment)) .entrySet() .stream() - .map(entry -> { - Instant date = TemporalValueType.absoluteMomentToInstant(entry.getKey().longValue(), dbTemporalFunction); - Map values = new TreeMap<>(); - entry.getValue().forEach(e -> values.put(e.getField(), e.getCount())); - return new TemporalDistributionDTO(date, values); - }).collect(Collectors.toList()); + .map( + entry -> { + Instant date = TemporalValueType.absoluteMomentToInstant(entry.getKey().longValue(), dbTemporalFunction); + Map values = new TreeMap<>(); + entry.getValue().forEach(e -> values.put(e.getField(), e.getCount())); + return new TemporalDistributionDTO(date, values); + } + ) + .collect(Collectors.toList()); } - public static List createCountQueryAndCollectData(Instant after, - TemporalValueType dbTemporalFunction, - CriteriaQuery query, - EntityManager entityManager) { + public static List createCountQueryAndCollectData( + Instant after, + TemporalValueType dbTemporalFunction, + CriteriaQuery query, + EntityManager entityManager + ) { return entityManager .createQuery(query) .setParameter(DATE, after) .getResultList() .stream() - .map(item -> - new TemporalCountDTO(TemporalValueType.absoluteMomentToInstant(item.getMoment().longValue(), dbTemporalFunction), item.getCount())) + .map( + item -> + new TemporalCountDTO( + TemporalValueType.absoluteMomentToInstant(item.getMoment().longValue(), dbTemporalFunction), + item.getCount() + ) + ) .sorted(TemporalCountDTO::compareTo) .collect(Collectors.toList()); } diff --git a/src/main/java/io/github/jhipster/online/util/DateUtil.java b/src/main/java/io/github/jhipster/online/util/DateUtil.java index 3270f7c2..c5ba1914 100644 --- a/src/main/java/io/github/jhipster/online/util/DateUtil.java +++ b/src/main/java/io/github/jhipster/online/util/DateUtil.java @@ -23,7 +23,6 @@ import io.github.jhipster.online.domain.enums.YoRCColumn; import io.github.jhipster.online.domain.interfaces.CompleteDate; import io.github.jhipster.online.service.enums.TemporalValueType; - import java.time.Instant; import java.time.ZoneId; import java.time.ZonedDateTime; @@ -90,18 +89,10 @@ public static TemporalValueType getTemporalValueTypeFromFrequency(String frequen } public static YoRCColumn getYoColumnFromField(String field) { - return Arrays - .stream(YoRCColumn.values()) - .filter(c -> c.getDatabaseValue().equals(field)) - .findFirst() - .orElse(null); + return Arrays.stream(YoRCColumn.values()).filter(c -> c.getDatabaseValue().equals(field)).findFirst().orElse(null); } public static EntityStatColumn getEntityColumnFromField(String field) { - return Arrays - .stream(EntityStatColumn.values()) - .filter(c -> c.getDatabaseValue().equals(field)) - .findFirst() - .orElse(null); + return Arrays.stream(EntityStatColumn.values()).filter(c -> c.getDatabaseValue().equals(field)).findFirst().orElse(null); } } diff --git a/src/main/java/io/github/jhipster/online/util/SanitizeInputs.java b/src/main/java/io/github/jhipster/online/util/SanitizeInputs.java index b4315dc7..33ee09a7 100644 --- a/src/main/java/io/github/jhipster/online/util/SanitizeInputs.java +++ b/src/main/java/io/github/jhipster/online/util/SanitizeInputs.java @@ -22,6 +22,7 @@ import java.util.regex.Pattern; public class SanitizeInputs { + private static final Pattern SANITIZE_REGEX = Pattern.compile("[\n\r\t]"); private static final Pattern ALPHANUMERIC_REGEX = Pattern.compile("[a-zA-Z0-9]*"); private static final Pattern ALPHANUMERIC_AND_SPACES_REGEX = Pattern.compile("[\\w\\s]*"); @@ -31,20 +32,17 @@ private SanitizeInputs() { } public static String sanitizeInput(String inputString) { - if (inputString == null) - return null; + if (inputString == null) return null; return SANITIZE_REGEX.matcher(inputString).replaceAll("_"); } public static boolean isAlphaNumeric(String inputString) { - if (inputString == null) - return false; + if (inputString == null) return false; return ALPHANUMERIC_REGEX.matcher(inputString).matches(); } - public static boolean isLettersNumbersAndSpaces (String inputString) { - if (inputString == null) - return false; + public static boolean isLettersNumbersAndSpaces(String inputString) { + if (inputString == null) return false; return ALPHANUMERIC_AND_SPACES_REGEX.matcher(inputString).matches(); } } diff --git a/src/main/java/io/github/jhipster/online/web/rest/AccountResource.java b/src/main/java/io/github/jhipster/online/web/rest/AccountResource.java index d1bbd993..982f511a 100644 --- a/src/main/java/io/github/jhipster/online/web/rest/AccountResource.java +++ b/src/main/java/io/github/jhipster/online/web/rest/AccountResource.java @@ -32,16 +32,15 @@ import io.github.jhipster.online.web.rest.errors.LoginAlreadyUsedException; import io.github.jhipster.online.web.rest.vm.KeyAndPasswordVM; import io.github.jhipster.online.web.rest.vm.ManagedUserVM; +import java.util.Optional; +import javax.servlet.http.HttpServletRequest; +import javax.validation.Valid; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; -import javax.servlet.http.HttpServletRequest; -import javax.validation.Valid; -import java.util.Optional; - /** * REST controller for managing the current user's account. */ @@ -52,6 +51,7 @@ public class AccountResource { private static final String USER_NOT_FOUND = "User could not be found"; private static class AccountResourceException extends RuntimeException { + private AccountResourceException(String message) { super(message); } @@ -66,7 +66,6 @@ private AccountResourceException(String message) { private final MailService mailService; public AccountResource(UserRepository userRepository, UserService userService, MailService mailService) { - this.userRepository = userRepository; this.userService = userService; this.mailService = mailService; @@ -123,9 +122,7 @@ public String isAuthenticated(HttpServletRequest request) { */ @GetMapping("/account") public UserDTO getAccount() { - return userService.getUserWithAuthorities() - .map(UserDTO::new) - .orElseThrow(() -> new AccountResourceException(USER_NOT_FOUND)); + return userService.getUserWithAuthorities().map(UserDTO::new).orElseThrow(() -> new AccountResourceException(USER_NOT_FOUND)); } /** @@ -135,8 +132,9 @@ public UserDTO getAccount() { */ @DeleteMapping("/account") public void deleteAccount() { - final String userLogin = SecurityUtils.getCurrentUserLogin().orElseThrow(() -> new - AccountResourceException("Current user login not found")); + final String userLogin = SecurityUtils + .getCurrentUserLogin() + .orElseThrow(() -> new AccountResourceException("Current user login not found")); // Checks if user exists Optional user = userRepository.findOneByLogin(userLogin); if (user.isEmpty()) { @@ -154,7 +152,9 @@ public void deleteAccount() { */ @PostMapping("/account") public void saveAccount(@Valid @RequestBody UserDTO userDTO) { - String userLogin = SecurityUtils.getCurrentUserLogin().orElseThrow(() -> new AccountResourceException("Current user login not found")); + String userLogin = SecurityUtils + .getCurrentUserLogin() + .orElseThrow(() -> new AccountResourceException("Current user login not found")); Optional existingUser = userRepository.findOneByEmailIgnoreCase(userDTO.getEmail()); if (existingUser.isPresent() && (!existingUser.get().getLogin().equalsIgnoreCase(userLogin))) { throw new EmailAlreadyUsedException(); @@ -163,8 +163,13 @@ public void saveAccount(@Valid @RequestBody UserDTO userDTO) { if (!user.isPresent()) { throw new AccountResourceException(USER_NOT_FOUND); } - userService.updateUser(userDTO.getFirstName(), userDTO.getLastName(), userDTO.getEmail(), - userDTO.getLangKey(), userDTO.getImageUrl()); + userService.updateUser( + userDTO.getFirstName(), + userDTO.getLastName(), + userDTO.getEmail(), + userDTO.getLangKey(), + userDTO.getImageUrl() + ); } /** @@ -220,8 +225,7 @@ public void finishPasswordReset(@RequestBody KeyAndPasswordVM keyAndPassword) { if (!checkPasswordLength(keyAndPassword.getNewPassword())) { throw new InvalidPasswordException(); } - Optional user = - userService.completePasswordReset(keyAndPassword.getNewPassword(), keyAndPassword.getKey()); + Optional user = userService.completePasswordReset(keyAndPassword.getNewPassword(), keyAndPassword.getKey()); if (!user.isPresent()) { throw new AccountResourceException("No user was found for this reset key"); @@ -229,8 +233,10 @@ public void finishPasswordReset(@RequestBody KeyAndPasswordVM keyAndPassword) { } private static boolean checkPasswordLength(String password) { - return !StringUtils.isEmpty(password) && + return ( + !StringUtils.isEmpty(password) && password.length() >= ManagedUserVM.PASSWORD_MIN_LENGTH && - password.length() <= ManagedUserVM.PASSWORD_MAX_LENGTH; + password.length() <= ManagedUserVM.PASSWORD_MAX_LENGTH + ); } } diff --git a/src/main/java/io/github/jhipster/online/web/rest/AuditResource.java b/src/main/java/io/github/jhipster/online/web/rest/AuditResource.java index e5d1ccea..7ce3d91e 100644 --- a/src/main/java/io/github/jhipster/online/web/rest/AuditResource.java +++ b/src/main/java/io/github/jhipster/online/web/rest/AuditResource.java @@ -22,6 +22,10 @@ import io.github.jhipster.online.service.AuditEventService; import io.github.jhipster.web.util.PaginationUtil; import io.github.jhipster.web.util.ResponseUtil; +import java.time.Instant; +import java.time.LocalDate; +import java.time.ZoneId; +import java.util.List; import org.springframework.boot.actuate.audit.AuditEvent; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; @@ -31,11 +35,6 @@ import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; -import java.time.Instant; -import java.time.LocalDate; -import java.time.ZoneId; -import java.util.List; - /** * REST controller for getting the {@link AuditEvent}s. */ @@ -70,12 +69,12 @@ public ResponseEntity> getAll(Pageable pageable) { * @param pageable the pagination information. * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of {@link AuditEvent} in body. */ - @GetMapping(params = {"fromDate", "toDate"}) + @GetMapping(params = { "fromDate", "toDate" }) public ResponseEntity> getByDates( @RequestParam(value = "fromDate") LocalDate fromDate, @RequestParam(value = "toDate") LocalDate toDate, - Pageable pageable) { - + Pageable pageable + ) { Instant from = fromDate.atStartOfDay(ZoneId.systemDefault()).toInstant(); Instant to = toDate.atStartOfDay(ZoneId.systemDefault()).plusDays(1).toInstant(); diff --git a/src/main/java/io/github/jhipster/online/web/rest/CiCdResource.java b/src/main/java/io/github/jhipster/online/web/rest/CiCdResource.java index 5ab94b5b..b3c02f16 100644 --- a/src/main/java/io/github/jhipster/online/web/rest/CiCdResource.java +++ b/src/main/java/io/github/jhipster/online/web/rest/CiCdResource.java @@ -27,6 +27,7 @@ import io.github.jhipster.online.service.UserService; import io.github.jhipster.online.service.enums.CiCdTool; import io.github.jhipster.online.util.SanitizeInputs; +import java.util.Optional; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -35,8 +36,6 @@ import org.springframework.security.access.annotation.Secured; import org.springframework.web.bind.annotation.*; -import java.util.Optional; - @RestController @RequestMapping("/api") public class CiCdResource { @@ -57,14 +56,17 @@ public CiCdResource(UserService userService, CiCdService ciCdService, LogsServic @PostMapping("/ci-cd/{gitProvider}/{organizationName}/{projectName}/{ciCdTool}") @Secured(AuthoritiesConstants.USER) - public ResponseEntity configureCiCd(@PathVariable String gitProvider, @PathVariable String organizationName, - @PathVariable String projectName, @PathVariable String ciCdTool) { + public ResponseEntity configureCiCd( + @PathVariable String gitProvider, + @PathVariable String organizationName, + @PathVariable String projectName, + @PathVariable String ciCdTool + ) { projectName = SanitizeInputs.sanitizeInput(projectName); organizationName = SanitizeInputs.sanitizeInput(organizationName); ciCdTool = SanitizeInputs.sanitizeInput(ciCdTool); boolean isGitHub = gitProvider.equalsIgnoreCase("github"); - log.info("Configuring CI: {} on " + (isGitHub ? "GitHub" : "GitLab") + " {}/{}", ciCdTool, organizationName, - projectName); + log.info("Configuring CI: {} on " + (isGitHub ? "GitHub" : "GitLab") + " {}/{}", ciCdTool, organizationName, projectName); User user = userService.getUser(); String ciCdId = "ci-" + System.nanoTime(); @@ -73,14 +75,25 @@ public ResponseEntity configureCiCd(@PathVariable String gitProvider, @P this.logsService.addLog(ciCdId, "Continuous Integration with `" + ciCdTool + "` is not supported."); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } - this.logsService.addLog(ciCdId, "Continuous Integration with " + - StringUtils.capitalize(ciCdTool) + - " is going to be applied to " + - organizationName + "/" + projectName); + this.logsService.addLog( + ciCdId, + "Continuous Integration with " + + StringUtils.capitalize(ciCdTool) + + " is going to be applied to " + + organizationName + + "/" + + projectName + ); try { - this.ciCdService.configureCiCd(user, organizationName, projectName, integrationTool.get(), - ciCdId, GitProvider.getGitProviderByValue(gitProvider).orElseThrow(null)); + this.ciCdService.configureCiCd( + user, + organizationName, + projectName, + integrationTool.get(), + ciCdId, + GitProvider.getGitProviderByValue(gitProvider).orElseThrow(null) + ); } catch (Exception e) { log.error("Error generating application", e); this.logsService.addLog(ciCdId, "An error has occurred: " + e.getMessage()); diff --git a/src/main/java/io/github/jhipster/online/web/rest/EntityStatsResource.java b/src/main/java/io/github/jhipster/online/web/rest/EntityStatsResource.java index f156c6b8..9d690f26 100644 --- a/src/main/java/io/github/jhipster/online/web/rest/EntityStatsResource.java +++ b/src/main/java/io/github/jhipster/online/web/rest/EntityStatsResource.java @@ -26,6 +26,10 @@ import io.github.jhipster.online.web.rest.errors.BadRequestAlertException; import io.github.jhipster.web.util.HeaderUtil; import io.github.jhipster.web.util.ResponseUtil; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.List; +import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; @@ -33,11 +37,6 @@ import org.springframework.security.access.annotation.Secured; import org.springframework.web.bind.annotation.*; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.List; -import java.util.Optional; - /** * REST controller for managing EntityStats. */ @@ -72,7 +71,8 @@ public ResponseEntity createEntityStats(@RequestBody EntityStats throw new BadRequestAlertException("A new entityStats cannot already have an ID", ENTITY_NAME, "idexists"); } EntityStatsDTO result = entityStatsService.save(entityStats); - return ResponseEntity.created(new URI("/api/entity-stats/" + result.getId())) + return ResponseEntity + .created(new URI("/api/entity-stats/" + result.getId())) .headers(HeaderUtil.createEntityCreationAlert(applicationName, false, ENTITY_NAME, result.getId().toString())) .body(result); } @@ -93,7 +93,8 @@ public ResponseEntity updateEntityStats(@RequestBody EntityStats throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull"); } EntityStatsDTO result = entityStatsService.save(entityStats); - return ResponseEntity.ok() + return ResponseEntity + .ok() .headers(HeaderUtil.createEntityUpdateAlert(applicationName, false, ENTITY_NAME, entityStats.getId().toString())) .body(result); } @@ -135,6 +136,9 @@ public ResponseEntity getEntityStats(@PathVariable Long id) { public ResponseEntity deleteEntityStats(@PathVariable Long id) { log.debug("REST request to delete EntityStats : {}", id); entityStatsService.delete(id); - return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(applicationName, false, ENTITY_NAME, id.toString())).build(); + return ResponseEntity + .ok() + .headers(HeaderUtil.createEntityDeletionAlert(applicationName, false, ENTITY_NAME, id.toString())) + .build(); } } diff --git a/src/main/java/io/github/jhipster/online/web/rest/GeneratorIdentityResource.java b/src/main/java/io/github/jhipster/online/web/rest/GeneratorIdentityResource.java index 33942155..174d0fb1 100644 --- a/src/main/java/io/github/jhipster/online/web/rest/GeneratorIdentityResource.java +++ b/src/main/java/io/github/jhipster/online/web/rest/GeneratorIdentityResource.java @@ -26,17 +26,16 @@ import io.github.jhipster.online.web.rest.errors.BadRequestAlertException; import io.github.jhipster.web.util.HeaderUtil; import io.github.jhipster.web.util.ResponseUtil; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.List; +import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.List; -import java.util.Optional; - /** * REST controller for managing GeneratorIdentity. */ @@ -68,13 +67,15 @@ public GeneratorIdentityResource(GeneratorIdentityService generatorIdentityServi * @throws URISyntaxException if the Location URI syntax is incorrect */ @PostMapping("/generator-identities") - public ResponseEntity createGeneratorIdentity(@RequestBody GeneratorIdentityDTO generatorIdentity) throws URISyntaxException { + public ResponseEntity createGeneratorIdentity(@RequestBody GeneratorIdentityDTO generatorIdentity) + throws URISyntaxException { log.debug("REST request to save GeneratorIdentity : {}", generatorIdentity); if (generatorIdentity.getId() != null) { throw new BadRequestAlertException("A new generatorIdentity cannot already have an ID", ENTITY_NAME, "idexists"); } GeneratorIdentityDTO result = generatorIdentityService.save(generatorIdentity); - return ResponseEntity.created(new URI("/api/generator-identities/" + result.getId())) + return ResponseEntity + .created(new URI("/api/generator-identities/" + result.getId())) .headers(HeaderUtil.createEntityCreationAlert(applicationName, false, ENTITY_NAME, result.getId().toString())) .body(result); } @@ -94,7 +95,8 @@ public ResponseEntity updateGeneratorIdentity(@RequestBody throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull"); } GeneratorIdentityDTO result = generatorIdentityService.save(generatorIdentity); - return ResponseEntity.ok() + return ResponseEntity + .ok() .headers(HeaderUtil.createEntityUpdateAlert(applicationName, false, ENTITY_NAME, generatorIdentity.getId().toString())) .body(result); } @@ -133,7 +135,10 @@ public ResponseEntity getGeneratorIdentity(@PathVariable Long public ResponseEntity deleteGeneratorIdentity(@PathVariable Long id) { log.debug("REST request to delete GeneratorIdentity : {}", id); generatorIdentityService.delete(id); - return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(applicationName, false, ENTITY_NAME, id.toString())).build(); + return ResponseEntity + .ok() + .headers(HeaderUtil.createEntityDeletionAlert(applicationName, false, ENTITY_NAME, id.toString())) + .build(); } /** @@ -146,5 +151,4 @@ public List getAllOwnedGeneratorIdentities() { log.debug("REST request to get all owned GeneratorIdentities"); return generatorIdentityService.findAllOwned(userService.getUser()); } - } diff --git a/src/main/java/io/github/jhipster/online/web/rest/GeneratorResource.java b/src/main/java/io/github/jhipster/online/web/rest/GeneratorResource.java index b6c0d988..93828720 100644 --- a/src/main/java/io/github/jhipster/online/web/rest/GeneratorResource.java +++ b/src/main/java/io/github/jhipster/online/web/rest/GeneratorResource.java @@ -26,6 +26,10 @@ import io.github.jhipster.online.security.AuthoritiesConstants; import io.github.jhipster.online.service.*; import io.github.jhipster.online.util.SanitizeInputs; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.UUID; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -35,11 +39,6 @@ import org.springframework.security.access.annotation.Secured; import org.springframework.web.bind.annotation.*; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.UUID; - @RestController @RequestMapping("/api") public class GeneratorResource { @@ -56,11 +55,13 @@ public class GeneratorResource { private final LogsService logsService; - public GeneratorResource(GeneratorService generatorService, - GithubService githubService, - GitlabService gitlabService, - UserService userService, - LogsService logsService) { + public GeneratorResource( + GeneratorService generatorService, + GithubService githubService, + GitlabService gitlabService, + UserService userService, + LogsService logsService + ) { this.generatorService = generatorService; this.githubService = githubService; this.gitlabService = gitlabService; @@ -76,7 +77,8 @@ public ResponseEntity generateApplicationOnGit(@RequestBody String appli User user = userService.getUser(); log.debug("Reading application configuration"); Object document = Configuration.defaultConfiguration().jsonProvider().parse(applicationConfiguration); - GitProvider provider = GitProvider.getGitProviderByValue(JsonPath.read(document, "$.git-provider")) + GitProvider provider = GitProvider + .getGitProviderByValue(JsonPath.read(document, "$.git-provider")) .orElseThrow(() -> new Exception("No git provider")); String gitCompany = JsonPath.read(document, "$.git-company"); String repositoryName = JsonPath.read(document, "$.repository-name"); @@ -84,18 +86,14 @@ public ResponseEntity generateApplicationOnGit(@RequestBody String appli log.debug("Using provider: {} ({})", provider, JsonPath.read(document, "$.git-provider")); log.debug("Generating application in repository id={} - {} / {}", applicationId, gitCompany, repositoryName); - this.logsService.addLog(applicationId, "Generating application in repository " + gitCompany + "/" + - repositoryName); + this.logsService.addLog(applicationId, "Generating application in repository " + gitCompany + "/" + repositoryName); try { if (provider.equals(GitProvider.GITHUB)) { - this.githubService.createGitProviderRepository( - user, applicationId, applicationConfiguration, gitCompany, repositoryName); + this.githubService.createGitProviderRepository(user, applicationId, applicationConfiguration, gitCompany, repositoryName); } else if (provider.equals(GitProvider.GITLAB)) { - this.gitlabService.createGitProviderRepository( - user, applicationId, applicationConfiguration, gitCompany, repositoryName); + this.gitlabService.createGitProviderRepository(user, applicationId, applicationConfiguration, gitCompany, repositoryName); } - } catch (Exception e) { log.error("Error generating application", e); this.logsService.addLog(applicationId, "An error has occurred: " + e.getMessage()); @@ -113,15 +111,13 @@ public ResponseEntity generateApplicationOutput(@PathVariable String app @PostMapping("/download-application") @Secured(AuthoritiesConstants.USER) - public @ResponseBody - ResponseEntity downloadApplication(@RequestBody String applicationConfiguration) { + public @ResponseBody ResponseEntity downloadApplication(@RequestBody String applicationConfiguration) { applicationConfiguration = SanitizeInputs.sanitizeInput(applicationConfiguration); log.info("Downloading application - .yo-rc.json: {}", applicationConfiguration); String applicationId = UUID.randomUUID().toString(); String zippedApplication; try { - zippedApplication = this.generatorService.generateZippedApplication(applicationId, - applicationConfiguration); + zippedApplication = this.generatorService.generateZippedApplication(applicationId, applicationConfiguration); } catch (IOException ioe) { log.error("Error generating application", ioe); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); @@ -141,5 +137,4 @@ ResponseEntity downloadApplication(@RequestBody String applicationConfig return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } } - } diff --git a/src/main/java/io/github/jhipster/online/web/rest/GitResource.java b/src/main/java/io/github/jhipster/online/web/rest/GitResource.java index 21827241..baefbd56 100644 --- a/src/main/java/io/github/jhipster/online/web/rest/GitResource.java +++ b/src/main/java/io/github/jhipster/online/web/rest/GitResource.java @@ -31,15 +31,6 @@ import io.github.jhipster.online.service.UserService; import io.github.jhipster.online.service.dto.GitConfigurationDTO; import io.github.jhipster.online.util.SanitizeInputs; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.security.access.annotation.Secured; -import org.springframework.web.bind.annotation.*; -import org.springframework.web.servlet.view.RedirectView; - import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; @@ -48,6 +39,14 @@ import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.annotation.Secured; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.servlet.view.RedirectView; @RestController @RequestMapping("/api") @@ -69,10 +68,12 @@ public class GitResource { private final GitlabService gitlabService; - public GitResource(ApplicationProperties applicationProperties, - UserService userService, - GithubService githubService, - GitlabService gitlabService) { + public GitResource( + ApplicationProperties applicationProperties, + UserService userService, + GithubService githubService, + GitlabService gitlabService + ) { this.applicationProperties = applicationProperties; this.userService = userService; this.githubService = githubService; @@ -131,14 +132,14 @@ public RedirectView callback(@PathVariable String gitProvider, String code) { request.setCode(code); break; default: - return new ResponseEntity<>(UNKNOWN_GIT_PROVIDER + gitProvider, HttpStatus - .INTERNAL_SERVER_ERROR); + return new ResponseEntity<>(UNKNOWN_GIT_PROVIDER + gitProvider, HttpStatus.INTERNAL_SERVER_ERROR); } ObjectMapper objectMapper = new ObjectMapper(); String requestBody = objectMapper.writeValueAsString(request); HttpClient client = HttpClient.newHttpClient(); - HttpRequest httpRequest = HttpRequest.newBuilder() + HttpRequest httpRequest = HttpRequest + .newBuilder() .uri(URI.create(url)) .header("Content-Type", MediaType.APPLICATION_JSON_VALUE) .header("Accept", MediaType.APPLICATION_JSON_VALUE) @@ -146,8 +147,7 @@ public RedirectView callback(@PathVariable String gitProvider, String code) { .POST(HttpRequest.BodyPublishers.ofString(requestBody)) .build(); - CompletableFuture> response = client.sendAsync(httpRequest, - HttpResponse.BodyHandlers.ofString()); + CompletableFuture> response = client.sendAsync(httpRequest, HttpResponse.BodyHandlers.ofString()); String jsonResponse = response.thenApply(HttpResponse::body).get(5, TimeUnit.SECONDS); GitAccessTokenResponse accessTokenResponse = objectMapper.readValue(jsonResponse, GitAccessTokenResponse.class); @@ -213,18 +213,31 @@ public void setRedirect_uri(String redirectUri) { @Override public String toString() { - return "GitAccessTokenRequest{" + - "client_id='" + client_id + '\'' + - ", client_secret='" + client_secret + '\'' + - ", code='" + code + '\'' + - ", grantType='" + grantType + '\'' + - ", redirectUri='" + redirectUri + '\'' + - '}'; + return ( + "GitAccessTokenRequest{" + + "client_id='" + + client_id + + '\'' + + ", client_secret='" + + client_secret + + '\'' + + ", code='" + + code + + '\'' + + ", grantType='" + + grantType + + '\'' + + ", redirectUri='" + + redirectUri + + '\'' + + '}' + ); } } @JsonIgnoreProperties(ignoreUnknown = true) public static class GitAccessTokenResponse { + private String access_token; public String getAccess_token() { @@ -254,25 +267,19 @@ public void setAccess_token(String access_token) { this.gitlabService.syncUserFromGitProvider(); break; default: - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(UNKNOWN_GIT_PROVIDER + - gitProvider); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(UNKNOWN_GIT_PROVIDER + gitProvider); } return ResponseEntity.ok().build(); } catch (Exception e) { switch (gitProvider.toLowerCase()) { case GITHUB: - log.error("Could not refresh GitHub data for User `{}`: {}", SecurityUtils.getCurrentUserLogin(), - e); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("GitHub data could not be " + - "refreshed"); + log.error("Could not refresh GitHub data for User `{}`: {}", SecurityUtils.getCurrentUserLogin(), e); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("GitHub data could not be " + "refreshed"); case GITLAB: - log.error("Could not refresh GitLab data for User `{}`: {}", SecurityUtils.getCurrentUserLogin(), - e); - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("GitLab data could not be " + - "refreshed"); + log.error("Could not refresh GitLab data for User `{}`: {}", SecurityUtils.getCurrentUserLogin(), e); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("GitLab data could not be " + "refreshed"); default: - return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(UNKNOWN_GIT_PROVIDER + - gitProvider); + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(UNKNOWN_GIT_PROVIDER + gitProvider); } } } @@ -302,9 +309,11 @@ public void setAccess_token(String access_token) { @Secured(AuthoritiesConstants.USER) public @ResponseBody ResponseEntity getOrganizationProjects(@PathVariable String gitProvider, @PathVariable String companyName) { Optional maybeGitProvider = GitProvider.getGitProviderByValue(gitProvider); - return maybeGitProvider.map(gitProvider1 -> - new ResponseEntity<>(this.userService.getProjects(companyName, gitProvider1), HttpStatus.OK)).orElseGet(() -> - new ResponseEntity<>(HttpStatus.NOT_FOUND)); + return maybeGitProvider + .map( + gitProvider1 -> new ResponseEntity<>(this.userService.getProjects(companyName, gitProvider1), HttpStatus.OK) + ) + .orElseGet(() -> new ResponseEntity<>(HttpStatus.NOT_FOUND)); } @GetMapping("/git/config") @@ -319,11 +328,11 @@ public void setAccess_token(String access_token) { gitlabService.getClientId(), gitlabService.isEnabled(), githubService.isConfigured(), - gitlabService.isConfigured()); + gitlabService.isConfigured() + ); this.log.debug("Git configuration : {}", result); return new ResponseEntity<>(result, HttpStatus.OK); } - } diff --git a/src/main/java/io/github/jhipster/online/web/rest/JdlMetadataResource.java b/src/main/java/io/github/jhipster/online/web/rest/JdlMetadataResource.java index f98d2cf1..61bfb27a 100644 --- a/src/main/java/io/github/jhipster/online/web/rest/JdlMetadataResource.java +++ b/src/main/java/io/github/jhipster/online/web/rest/JdlMetadataResource.java @@ -26,6 +26,9 @@ import io.github.jhipster.online.service.dto.JdlMetadataDTO; import io.github.jhipster.web.util.HeaderUtil; import io.github.jhipster.web.util.ResponseUtil; +import java.util.List; +import java.util.Optional; +import javax.validation.Valid; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; @@ -34,10 +37,6 @@ import org.springframework.security.access.annotation.Secured; import org.springframework.web.bind.annotation.*; -import javax.validation.Valid; -import java.util.List; -import java.util.Optional; - /** * REST controller for managing JdlMetadata. */ @@ -74,7 +73,8 @@ public JdlMetadataResource(JdlMetadataService jdlMetadataService, UserService us public ResponseEntity updateJdlMetadata(@Valid @RequestBody JdlMetadataDTO jdlMetadata) { log.debug("REST request to update JdlMetadata : {}", jdlMetadata); JdlMetadataDTO result = jdlMetadataService.saveJdlMetadata(jdlMetadata); - return ResponseEntity.ok() + return ResponseEntity + .ok() .headers(HeaderUtil.createEntityUpdateAlert(applicationName, false, ENTITY_NAME, jdlMetadata.getId())) .body(result); } diff --git a/src/main/java/io/github/jhipster/online/web/rest/JdlResource.java b/src/main/java/io/github/jhipster/online/web/rest/JdlResource.java index 4a1c0c98..a6c87fe6 100644 --- a/src/main/java/io/github/jhipster/online/web/rest/JdlResource.java +++ b/src/main/java/io/github/jhipster/online/web/rest/JdlResource.java @@ -31,6 +31,9 @@ import io.github.jhipster.online.service.UserService; import io.github.jhipster.online.util.SanitizeInputs; import io.github.jhipster.online.web.rest.vm.JdlVM; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; @@ -38,10 +41,6 @@ import org.springframework.security.access.annotation.Secured; import org.springframework.web.bind.annotation.*; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Optional; - @RestController @RequestMapping("/api") public class JdlResource { @@ -58,9 +57,13 @@ public class JdlResource { private final LogsService logsService; - public JdlResource(UserService userService, JdlMetadataService jdlMetadataService, - JdlRepository jdlRepository, LogsService logsService, - JdlService jdlService) { + public JdlResource( + UserService userService, + JdlMetadataService jdlMetadataService, + JdlRepository jdlRepository, + LogsService logsService, + JdlService jdlService + ) { this.userService = userService; this.jdlMetadataService = jdlMetadataService; this.jdlRepository = jdlRepository; @@ -90,10 +93,12 @@ public ResponseEntity getJdlFile(@PathVariable String jdlId) { */ @PostMapping("/jdl") @Secured(AuthoritiesConstants.USER) - public @ResponseBody - ResponseEntity createJdlFile(@RequestBody JdlVM vm) throws URISyntaxException { - if (!SanitizeInputs.isLettersNumbersAndSpaces(vm.getName()) && !SanitizeInputs.isLettersNumbersAndSpaces(vm.getContent())) - throw new IllegalArgumentException("Provided user input is not valid: vm.name: " + vm.getName() + "vm.content: " + vm.getContent()); + public @ResponseBody ResponseEntity createJdlFile(@RequestBody JdlVM vm) throws URISyntaxException { + if ( + !SanitizeInputs.isLettersNumbersAndSpaces(vm.getName()) && !SanitizeInputs.isLettersNumbersAndSpaces(vm.getContent()) + ) throw new IllegalArgumentException( + "Provided user input is not valid: vm.name: " + vm.getName() + "vm.content: " + vm.getContent() + ); JdlMetadata jdlMetadata = new JdlMetadata(); if (vm.getName() == null || vm.getName().equals("")) { jdlMetadata.setName("New JDL Model"); @@ -101,7 +106,8 @@ ResponseEntity createJdlFile(@RequestBody JdlVM vm) throws URISynta jdlMetadata.setName(vm.getName()); } jdlMetadataService.create(jdlMetadata, vm.getContent()); - return ResponseEntity.created(new URI("/api/jdl/" + jdlMetadata.getId())) //NOSONAR + return ResponseEntity + .created(new URI("/api/jdl/" + jdlMetadata.getId())) //NOSONAR .body(jdlMetadata); } @@ -110,12 +116,11 @@ ResponseEntity createJdlFile(@RequestBody JdlVM vm) throws URISynta */ @PutMapping("/jdl/{jdlId}") @Secured(AuthoritiesConstants.USER) - public @ResponseBody - ResponseEntity updateJdlFile(@PathVariable String jdlId, @RequestBody JdlVM vm) { + public @ResponseBody ResponseEntity updateJdlFile(@PathVariable String jdlId, @RequestBody JdlVM vm) { Optional jdlMetadata = jdlMetadataService.findOne(jdlId); try { if (jdlMetadata.isEmpty()) { - throw new IllegalArgumentException("jdlMetaData object for jdlId="+ jdlId + " is empty"); + throw new IllegalArgumentException("jdlMetaData object for jdlId=" + jdlId + " is empty"); } jdlMetadataService.updateJdlContent(jdlMetadata.get(), vm.getContent()); } catch (Exception e) { @@ -130,8 +135,7 @@ ResponseEntity updateJdlFile(@PathVariable String jdlId, @RequestBody Jd */ @DeleteMapping("/jdl/{jdlId}") @Secured(AuthoritiesConstants.USER) - public @ResponseBody - ResponseEntity deleteJdlFile(@PathVariable String jdlId) { + public @ResponseBody ResponseEntity deleteJdlFile(@PathVariable String jdlId) { jdlId = SanitizeInputs.sanitizeInput(jdlId); try { this.jdlMetadataService.delete(jdlId); @@ -144,30 +148,37 @@ ResponseEntity deleteJdlFile(@PathVariable String jdlId) { @PostMapping("/apply-jdl/{gitProvider}/{organizationName}/{projectName}/{jdlId}") @Secured(AuthoritiesConstants.USER) - public ResponseEntity applyJdl(@PathVariable String gitProvider, @PathVariable String organizationName, - @PathVariable String projectName, - @PathVariable String jdlId) { + public ResponseEntity applyJdl( + @PathVariable String gitProvider, + @PathVariable String organizationName, + @PathVariable String projectName, + @PathVariable String jdlId + ) { projectName = SanitizeInputs.sanitizeInput(projectName); organizationName = SanitizeInputs.sanitizeInput(organizationName); jdlId = SanitizeInputs.sanitizeInput(jdlId); boolean isGitHub = gitProvider.equalsIgnoreCase("github"); - log.info("Applying JDL `{}` on " + (isGitHub ? "GitHub" : "GitLab") + " project {}/{}", jdlId, - organizationName, projectName); + log.info("Applying JDL `{}` on " + (isGitHub ? "GitHub" : "GitLab") + " project {}/{}", jdlId, organizationName, projectName); User user = userService.getUser(); Optional jdlMetadata = this.jdlMetadataService.findOne(jdlId); String applyJdlId; try { if (jdlMetadata.isEmpty()) { - throw new IllegalArgumentException("jdlMetaData object for jdlId="+ jdlId + " is empty"); + throw new IllegalArgumentException("jdlMetaData object for jdlId=" + jdlId + " is empty"); } applyJdlId = this.jdlService.kebabCaseJdlName(jdlMetadata.get()) + "-" + System.nanoTime(); - this.logsService.addLog(applyJdlId, "JDL Model is going to be applied to " + organizationName + "/" + - projectName); - - this.jdlService.applyJdl(user, organizationName, projectName, jdlMetadata.get(), - applyJdlId, GitProvider.getGitProviderByValue(gitProvider).orElseThrow(null)); + this.logsService.addLog(applyJdlId, "JDL Model is going to be applied to " + organizationName + "/" + projectName); + + this.jdlService.applyJdl( + user, + organizationName, + projectName, + jdlMetadata.get(), + applyJdlId, + GitProvider.getGitProviderByValue(gitProvider).orElseThrow(null) + ); } catch (Exception e) { log.error("Error generating application", e); this.logsService.addLog(jdlId, "An error has occurred: " + e.getMessage()); diff --git a/src/main/java/io/github/jhipster/online/web/rest/StatisticsResource.java b/src/main/java/io/github/jhipster/online/web/rest/StatisticsResource.java index d4771500..19e923c0 100644 --- a/src/main/java/io/github/jhipster/online/web/rest/StatisticsResource.java +++ b/src/main/java/io/github/jhipster/online/web/rest/StatisticsResource.java @@ -31,6 +31,12 @@ import io.github.jhipster.online.service.enums.TemporalValueType; import io.github.jhipster.online.util.DateUtil; import io.github.jhipster.online.util.SanitizeInputs; +import java.io.IOException; +import java.time.Instant; +import java.time.ZonedDateTime; +import java.util.List; +import javax.servlet.http.HttpServletRequest; +import javax.validation.constraints.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; @@ -38,13 +44,6 @@ import org.springframework.security.access.annotation.Secured; import org.springframework.web.bind.annotation.*; -import javax.servlet.http.HttpServletRequest; -import javax.validation.constraints.NotNull; -import java.io.IOException; -import java.time.Instant; -import java.time.ZonedDateTime; -import java.util.List; - @RestController @RequestMapping("/api/s") public class StatisticsResource { @@ -65,13 +64,15 @@ public class StatisticsResource { private final EntityStatsService entityStatService; - public StatisticsResource(StatisticsService statisticsService, - YoRCService yoRCService, - JdlService jdlService, - SubGenEventService subGenEventService, - UserService userService, - GeneratorIdentityService generatorIdentityService, - EntityStatsService entityStatService) { + public StatisticsResource( + StatisticsService statisticsService, + YoRCService yoRCService, + JdlService jdlService, + SubGenEventService subGenEventService, + UserService userService, + GeneratorIdentityService generatorIdentityService, + EntityStatsService entityStatService + ) { this.statisticsService = statisticsService; this.yoRCService = yoRCService; this.jdlService = jdlService; @@ -81,7 +82,6 @@ public StatisticsResource(StatisticsService statisticsService, this.entityStatService = entityStatService; } - @GetMapping("/count-yo/{frequency}") public ResponseEntity> getCount(@PathVariable String frequency) { Instant frequencyInstant = DateUtil.getFrequencyInstant(ZonedDateTime.now(), frequency); @@ -95,7 +95,10 @@ public ResponseEntity> getCount(@PathVariable String freq } @GetMapping("/yo/{field}/{frequency}") - public ResponseEntity> getYoFieldCount(@NotNull @PathVariable String field, @NotNull @PathVariable String frequency) { + public ResponseEntity> getYoFieldCount( + @NotNull @PathVariable String field, + @NotNull @PathVariable String frequency + ) { Instant frequencyInstant = DateUtil.getFrequencyInstant(ZonedDateTime.now(), frequency); TemporalValueType temporalValueType = DateUtil.getTemporalValueTypeFromFrequency(frequency); YoRCColumn column = DateUtil.getYoColumnFromField(field); @@ -108,7 +111,10 @@ public ResponseEntity> getYoFieldCount(@NotNull @P } @GetMapping("/entity/{field}/{frequency}") - public ResponseEntity> getEntityFieldCount(@NotNull @PathVariable String field, @NotNull @PathVariable String frequency) { + public ResponseEntity> getEntityFieldCount( + @NotNull @PathVariable String field, + @NotNull @PathVariable String frequency + ) { Instant frequencyInstant = DateUtil.getFrequencyInstant(ZonedDateTime.now(), frequency); TemporalValueType temporalValueType = DateUtil.getTemporalValueTypeFromFrequency(frequency); EntityStatColumn column = DateUtil.getEntityColumnFromField(field); @@ -120,7 +126,6 @@ public ResponseEntity> getEntityFieldCount(@NotNul } } - @GetMapping("/sub-gen-event/deployment/{frequency}") public ResponseEntity> getDeploymentToolsDistribution(@NotNull @PathVariable String frequency) { Instant frequencyInstant = DateUtil.getFrequencyInstant(ZonedDateTime.now(), frequency); @@ -129,7 +134,10 @@ public ResponseEntity> getDeploymentToolsDistribut if (frequencyInstant == null || temporalValueType == null) { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } else { - return new ResponseEntity<>(subGenEventService.getDeploymentToolDistribution(frequencyInstant, temporalValueType), HttpStatus.OK); + return new ResponseEntity<>( + subGenEventService.getDeploymentToolDistribution(frequencyInstant, temporalValueType), + HttpStatus.OK + ); } } diff --git a/src/main/java/io/github/jhipster/online/web/rest/SubGenEventResource.java b/src/main/java/io/github/jhipster/online/web/rest/SubGenEventResource.java index 94302bf4..086864e0 100644 --- a/src/main/java/io/github/jhipster/online/web/rest/SubGenEventResource.java +++ b/src/main/java/io/github/jhipster/online/web/rest/SubGenEventResource.java @@ -26,6 +26,10 @@ import io.github.jhipster.online.web.rest.errors.BadRequestAlertException; import io.github.jhipster.web.util.HeaderUtil; import io.github.jhipster.web.util.ResponseUtil; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.List; +import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; @@ -33,11 +37,6 @@ import org.springframework.security.access.annotation.Secured; import org.springframework.web.bind.annotation.*; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.List; -import java.util.Optional; - /** * REST controller for managing SubGenEvent. */ @@ -72,7 +71,8 @@ public ResponseEntity createSubGenEvent(@RequestBody SubGenEvent throw new BadRequestAlertException("A new subGenEvent cannot already have an ID", ENTITY_NAME, "idexists"); } SubGenEventDTO result = subGenEventService.save(subGenEvent); - return ResponseEntity.created(new URI("/api/sub-gen-events/" + result.getId())) + return ResponseEntity + .created(new URI("/api/sub-gen-events/" + result.getId())) .headers(HeaderUtil.createEntityCreationAlert(applicationName, false, ENTITY_NAME, result.getId().toString())) .body(result); } @@ -105,7 +105,8 @@ public ResponseEntity updateSubGenEvent(@RequestBody SubGenEvent throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull"); } SubGenEventDTO result = subGenEventService.save(subGenEvent); - return ResponseEntity.ok() + return ResponseEntity + .ok() .headers(HeaderUtil.createEntityUpdateAlert(applicationName, false, ENTITY_NAME, subGenEvent.getId().toString())) .body(result); } @@ -135,6 +136,9 @@ public ResponseEntity getSubGenEvent(@PathVariable Long id) { public ResponseEntity deleteSubGenEvent(@PathVariable Long id) { log.debug("REST request to delete SubGenEvent : {}", id); subGenEventService.delete(id); - return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(applicationName, false, ENTITY_NAME, id.toString())).build(); + return ResponseEntity + .ok() + .headers(HeaderUtil.createEntityDeletionAlert(applicationName, false, ENTITY_NAME, id.toString())) + .build(); } } diff --git a/src/main/java/io/github/jhipster/online/web/rest/UserJWTController.java b/src/main/java/io/github/jhipster/online/web/rest/UserJWTController.java index 503b14ea..af33140d 100644 --- a/src/main/java/io/github/jhipster/online/web/rest/UserJWTController.java +++ b/src/main/java/io/github/jhipster/online/web/rest/UserJWTController.java @@ -23,6 +23,7 @@ import io.github.jhipster.online.security.jwt.JWTFilter; import io.github.jhipster.online.security.jwt.TokenProvider; import io.github.jhipster.online.web.rest.vm.LoginVM; +import javax.validation.Valid; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -35,8 +36,6 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; -import javax.validation.Valid; - /** * Controller to authenticate users. */ @@ -55,9 +54,10 @@ public UserJWTController(TokenProvider tokenProvider, AuthenticationManagerBuild @PostMapping("/authenticate") public ResponseEntity authorize(@Valid @RequestBody LoginVM loginVM) { - - UsernamePasswordAuthenticationToken authenticationToken = - new UsernamePasswordAuthenticationToken(loginVM.getUsername(), loginVM.getPassword()); + UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken( + loginVM.getUsername(), + loginVM.getPassword() + ); Authentication authentication = authenticationManagerBuilder.getObject().authenticate(authenticationToken); SecurityContextHolder.getContext().setAuthentication(authentication); @@ -67,6 +67,7 @@ public ResponseEntity authorize(@Valid @RequestBody LoginVM loginVM) { httpHeaders.add(JWTFilter.AUTHORIZATION_HEADER, "Bearer " + jwt); return new ResponseEntity<>(new JWTToken(jwt), httpHeaders, HttpStatus.OK); } + /** * Object to return as body in JWT Authentication. */ diff --git a/src/main/java/io/github/jhipster/online/web/rest/UserResource.java b/src/main/java/io/github/jhipster/online/web/rest/UserResource.java index 68fc9e10..c43c5295 100644 --- a/src/main/java/io/github/jhipster/online/web/rest/UserResource.java +++ b/src/main/java/io/github/jhipster/online/web/rest/UserResource.java @@ -32,6 +32,11 @@ import io.github.jhipster.web.util.HeaderUtil; import io.github.jhipster.web.util.PaginationUtil; import io.github.jhipster.web.util.ResponseUtil; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.List; +import java.util.Optional; +import javax.validation.Valid; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; @@ -44,12 +49,6 @@ import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; -import javax.validation.Valid; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.List; -import java.util.Optional; - /** * REST controller for managing users. *

@@ -123,8 +122,11 @@ public ResponseEntity createUser(@Valid @RequestBody UserDTO userDTO) thro User newUser = userService.createUser(userDTO); mailService.sendCreationEmail(newUser); - return ResponseEntity.created(new URI("/api/users/" + newUser.getLogin())) - .headers(HeaderUtil.createAlert(applicationName, "A user is created with identifier " + newUser.getLogin(), newUser.getLogin())) + return ResponseEntity + .created(new URI("/api/users/" + newUser.getLogin())) + .headers( + HeaderUtil.createAlert(applicationName, "A user is created with identifier " + newUser.getLogin(), newUser.getLogin()) + ) .body(newUser); } } @@ -151,8 +153,10 @@ public ResponseEntity updateUser(@Valid @RequestBody UserDTO userDTO) { } Optional updatedUser = userService.updateUser(userDTO); - return ResponseUtil.wrapOrNotFound(updatedUser, - HeaderUtil.createAlert(applicationName, "A user is updated with identifier " + userDTO.getLogin(), userDTO.getLogin())); + return ResponseUtil.wrapOrNotFound( + updatedUser, + HeaderUtil.createAlert(applicationName, "A user is updated with identifier " + userDTO.getLogin(), userDTO.getLogin()) + ); } /** @@ -188,9 +192,7 @@ public List getAuthorities() { @GetMapping("/users/{login:" + Constants.LOGIN_REGEX + "}") public ResponseEntity getUser(@PathVariable String login) { log.debug("REST request to get User : {}", login); - return ResponseUtil.wrapOrNotFound( - userService.getUserWithAuthoritiesByLogin(login) - .map(UserDTO::new)); + return ResponseUtil.wrapOrNotFound(userService.getUserWithAuthoritiesByLogin(login).map(UserDTO::new)); } /** @@ -204,6 +206,9 @@ public ResponseEntity getUser(@PathVariable String login) { public ResponseEntity deleteUser(@PathVariable String login) { log.debug("REST request to delete User: {}", login); userService.deleteUser(login); - return ResponseEntity.noContent().headers(HeaderUtil.createAlert(applicationName, "A user is deleted with identifier " + login, login)).build(); + return ResponseEntity + .noContent() + .headers(HeaderUtil.createAlert(applicationName, "A user is deleted with identifier " + login, login)) + .build(); } } diff --git a/src/main/java/io/github/jhipster/online/web/rest/YoRCResource.java b/src/main/java/io/github/jhipster/online/web/rest/YoRCResource.java index cd0b042e..6a68f86f 100644 --- a/src/main/java/io/github/jhipster/online/web/rest/YoRCResource.java +++ b/src/main/java/io/github/jhipster/online/web/rest/YoRCResource.java @@ -26,6 +26,10 @@ import io.github.jhipster.online.web.rest.errors.BadRequestAlertException; import io.github.jhipster.web.util.HeaderUtil; import io.github.jhipster.web.util.ResponseUtil; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.List; +import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; @@ -33,11 +37,6 @@ import org.springframework.security.access.annotation.Secured; import org.springframework.web.bind.annotation.*; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.List; -import java.util.Optional; - /** * REST controller for managing YoRC. */ @@ -72,7 +71,8 @@ public ResponseEntity createYoRC(@RequestBody YoRCDTO yoRC) throws URIS throw new BadRequestAlertException("A new yoRC cannot already have an ID", ENTITY_NAME, "idexists"); } YoRCDTO result = yoRCService.save(yoRC); - return ResponseEntity.created(new URI("/api/yo-rcs/" + result.getId())) + return ResponseEntity + .created(new URI("/api/yo-rcs/" + result.getId())) .headers(HeaderUtil.createEntityCreationAlert(applicationName, false, ENTITY_NAME, result.getId().toString())) .body(result); } @@ -93,7 +93,8 @@ public ResponseEntity updateYoRC(@RequestBody YoRCDTO yoRC) { throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull"); } YoRCDTO result = yoRCService.save(yoRC); - return ResponseEntity.ok() + return ResponseEntity + .ok() .headers(HeaderUtil.createEntityUpdateAlert(applicationName, false, ENTITY_NAME, yoRC.getId().toString())) .body(result); } @@ -135,6 +136,9 @@ public ResponseEntity getYoRC(@PathVariable Long id) { public ResponseEntity deleteYoRC(@PathVariable Long id) { log.debug("REST request to delete YoRC : {}", id); yoRCService.delete(id); - return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(applicationName, false, ENTITY_NAME, id.toString())).build(); + return ResponseEntity + .ok() + .headers(HeaderUtil.createEntityDeletionAlert(applicationName, false, ENTITY_NAME, id.toString())) + .build(); } } diff --git a/src/main/java/io/github/jhipster/online/web/rest/errors/BadRequestAlertException.java b/src/main/java/io/github/jhipster/online/web/rest/errors/BadRequestAlertException.java index aa052e52..bd423094 100644 --- a/src/main/java/io/github/jhipster/online/web/rest/errors/BadRequestAlertException.java +++ b/src/main/java/io/github/jhipster/online/web/rest/errors/BadRequestAlertException.java @@ -19,12 +19,11 @@ package io.github.jhipster.online.web.rest.errors; -import org.zalando.problem.AbstractThrowableProblem; -import org.zalando.problem.Status; - import java.net.URI; import java.util.HashMap; import java.util.Map; +import org.zalando.problem.AbstractThrowableProblem; +import org.zalando.problem.Status; public class BadRequestAlertException extends AbstractThrowableProblem { diff --git a/src/main/java/io/github/jhipster/online/web/rest/errors/ErrorConstants.java b/src/main/java/io/github/jhipster/online/web/rest/errors/ErrorConstants.java index 1f58031c..e4f22428 100644 --- a/src/main/java/io/github/jhipster/online/web/rest/errors/ErrorConstants.java +++ b/src/main/java/io/github/jhipster/online/web/rest/errors/ErrorConstants.java @@ -32,6 +32,5 @@ public final class ErrorConstants { public static final URI EMAIL_ALREADY_USED_TYPE = URI.create(PROBLEM_BASE_URL + "/email-already-used"); public static final URI LOGIN_ALREADY_USED_TYPE = URI.create(PROBLEM_BASE_URL + "/login-already-used"); - private ErrorConstants() { - } + private ErrorConstants() {} } diff --git a/src/main/java/io/github/jhipster/online/web/rest/errors/ExceptionTranslator.java b/src/main/java/io/github/jhipster/online/web/rest/errors/ExceptionTranslator.java index c379eb7b..4034a99e 100644 --- a/src/main/java/io/github/jhipster/online/web/rest/errors/ExceptionTranslator.java +++ b/src/main/java/io/github/jhipster/online/web/rest/errors/ExceptionTranslator.java @@ -20,6 +20,11 @@ package io.github.jhipster.online.web.rest.errors; import io.github.jhipster.web.util.HeaderUtil; +import java.util.List; +import java.util.stream.Collectors; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Value; import org.springframework.dao.ConcurrencyFailureException; import org.springframework.http.ResponseEntity; @@ -36,12 +41,6 @@ import org.zalando.problem.spring.web.advice.security.SecurityAdviceTrait; import org.zalando.problem.violations.ConstraintViolationProblem; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import javax.servlet.http.HttpServletRequest; -import java.util.List; -import java.util.stream.Collectors; - /** * Controller advice to translate the server side exceptions to client-friendly json structures. * The error response follows RFC7807 - Problem Details for HTTP APIs (https://tools.ietf.org/html/rfc7807). @@ -69,7 +68,8 @@ public ResponseEntity process(@Nullable ResponseEntity entity, if (!(problem instanceof ConstraintViolationProblem || problem instanceof DefaultProblem)) { return entity; } - ProblemBuilder builder = Problem.builder() + ProblemBuilder builder = Problem + .builder() .withType(Problem.DEFAULT_TYPE.equals(problem.getType()) ? ErrorConstants.DEFAULT_TYPE : problem.getType()) .withStatus(problem.getStatus()) .withTitle(problem.getTitle()) @@ -80,10 +80,7 @@ public ResponseEntity process(@Nullable ResponseEntity entity, .with(VIOLATIONS_KEY, ((ConstraintViolationProblem) problem).getViolations()) .with(MESSAGE_KEY, ErrorConstants.ERR_VALIDATION); } else { - builder - .withCause(((DefaultProblem) problem).getCause()) - .withDetail(problem.getDetail()) - .withInstance(problem.getInstance()); + builder.withCause(((DefaultProblem) problem).getCause()).withDetail(problem.getDetail()).withInstance(problem.getInstance()); problem.getParameters().forEach(builder::with); if (!problem.getParameters().containsKey(MESSAGE_KEY) && problem.getStatus() != null) { builder.with(MESSAGE_KEY, "error.http." + problem.getStatus().getStatusCode()); @@ -95,11 +92,14 @@ public ResponseEntity process(@Nullable ResponseEntity entity, @Override public ResponseEntity handleMethodArgumentNotValid(MethodArgumentNotValidException ex, @Nonnull NativeWebRequest request) { BindingResult result = ex.getBindingResult(); - List fieldErrors = result.getFieldErrors().stream() + List fieldErrors = result + .getFieldErrors() + .stream() .map(f -> new FieldErrorVM(f.getObjectName().replaceFirst("DTO$", ""), f.getField(), f.getCode())) .collect(Collectors.toList()); - Problem problem = Problem.builder() + Problem problem = Problem + .builder() .withType(ErrorConstants.CONSTRAINT_VIOLATION_TYPE) .withTitle("Method argument not valid") .withStatus(defaultConstraintViolationStatus()) @@ -110,33 +110,51 @@ public ResponseEntity handleMethodArgumentNotValid(MethodArgumentNotVal } @ExceptionHandler - public ResponseEntity handleEmailAlreadyUsedException(io.github.jhipster.online.service.EmailAlreadyUsedException ex, NativeWebRequest request) { + public ResponseEntity handleEmailAlreadyUsedException( + io.github.jhipster.online.service.EmailAlreadyUsedException ex, + NativeWebRequest request + ) { EmailAlreadyUsedException problem = new EmailAlreadyUsedException(); - return create(problem, request, HeaderUtil.createFailureAlert(applicationName, false, problem.getEntityName(), problem.getErrorKey(), problem.getMessage())); + return create( + problem, + request, + HeaderUtil.createFailureAlert(applicationName, false, problem.getEntityName(), problem.getErrorKey(), problem.getMessage()) + ); } @ExceptionHandler - public ResponseEntity handleUsernameAlreadyUsedException(io.github.jhipster.online.service.UsernameAlreadyUsedException ex, NativeWebRequest request) { + public ResponseEntity handleUsernameAlreadyUsedException( + io.github.jhipster.online.service.UsernameAlreadyUsedException ex, + NativeWebRequest request + ) { LoginAlreadyUsedException problem = new LoginAlreadyUsedException(); - return create(problem, request, HeaderUtil.createFailureAlert(applicationName, false, problem.getEntityName(), problem.getErrorKey(), problem.getMessage())); + return create( + problem, + request, + HeaderUtil.createFailureAlert(applicationName, false, problem.getEntityName(), problem.getErrorKey(), problem.getMessage()) + ); } @ExceptionHandler - public ResponseEntity handleInvalidPasswordException(io.github.jhipster.online.service.InvalidPasswordException ex, NativeWebRequest request) { + public ResponseEntity handleInvalidPasswordException( + io.github.jhipster.online.service.InvalidPasswordException ex, + NativeWebRequest request + ) { return create(new InvalidPasswordException(), request); } @ExceptionHandler public ResponseEntity handleBadRequestAlertException(BadRequestAlertException ex, NativeWebRequest request) { - return create(ex, request, HeaderUtil.createFailureAlert(applicationName, false, ex.getEntityName(), ex.getErrorKey(), ex.getMessage())); + return create( + ex, + request, + HeaderUtil.createFailureAlert(applicationName, false, ex.getEntityName(), ex.getErrorKey(), ex.getMessage()) + ); } @ExceptionHandler public ResponseEntity handleConcurrencyFailure(ConcurrencyFailureException ex, NativeWebRequest request) { - Problem problem = Problem.builder() - .withStatus(Status.CONFLICT) - .with(MESSAGE_KEY, ErrorConstants.ERR_CONCURRENCY_FAILURE) - .build(); + Problem problem = Problem.builder().withStatus(Status.CONFLICT).with(MESSAGE_KEY, ErrorConstants.ERR_CONCURRENCY_FAILURE).build(); return create(ex, problem, request); } } diff --git a/src/main/java/io/github/jhipster/online/web/rest/errors/FieldErrorVM.java b/src/main/java/io/github/jhipster/online/web/rest/errors/FieldErrorVM.java index 8d7e48e7..5d19ac88 100644 --- a/src/main/java/io/github/jhipster/online/web/rest/errors/FieldErrorVM.java +++ b/src/main/java/io/github/jhipster/online/web/rest/errors/FieldErrorVM.java @@ -48,5 +48,4 @@ public String getField() { public String getMessage() { return message; } - } diff --git a/src/main/java/io/github/jhipster/online/web/rest/vm/LoginVM.java b/src/main/java/io/github/jhipster/online/web/rest/vm/LoginVM.java index e7e778d1..6d811c7b 100644 --- a/src/main/java/io/github/jhipster/online/web/rest/vm/LoginVM.java +++ b/src/main/java/io/github/jhipster/online/web/rest/vm/LoginVM.java @@ -63,9 +63,6 @@ public void setRememberMe(Boolean rememberMe) { @Override public String toString() { - return "LoginVM{" + - "username='" + username + '\'' + - ", rememberMe=" + rememberMe + - '}'; + return "LoginVM{" + "username='" + username + '\'' + ", rememberMe=" + rememberMe + '}'; } } diff --git a/src/main/java/io/github/jhipster/online/web/rest/vm/ManagedUserVM.java b/src/main/java/io/github/jhipster/online/web/rest/vm/ManagedUserVM.java index b6f5ee0d..63e27278 100644 --- a/src/main/java/io/github/jhipster/online/web/rest/vm/ManagedUserVM.java +++ b/src/main/java/io/github/jhipster/online/web/rest/vm/ManagedUserVM.java @@ -20,7 +20,6 @@ package io.github.jhipster.online.web.rest.vm; import io.github.jhipster.online.service.dto.UserDTO; - import javax.validation.constraints.Size; /** diff --git a/src/main/resources/config/application.yml b/src/main/resources/config/application.yml index 265bd156..2d1eac83 100644 --- a/src/main/resources/config/application.yml +++ b/src/main/resources/config/application.yml @@ -74,7 +74,7 @@ spring: jpa: open-in-view: false properties: -# hibernate.jdbc.time_zone: UTC + # hibernate.jdbc.time_zone: UTC hibernate.id.new_generator_mappings: true hibernate.connection.provider_disables_autocommit: true hibernate.cache.use_second_level_cache: true diff --git a/src/main/webapp/app/admin/user-management/user-modal.service.ts b/src/main/webapp/app/admin/user-management/user-modal.service.ts index c650fdd9..48604482 100644 --- a/src/main/webapp/app/admin/user-management/user-modal.service.ts +++ b/src/main/webapp/app/admin/user-management/user-modal.service.ts @@ -24,35 +24,35 @@ import { User, UserService } from 'app/core'; @Injectable({ providedIn: 'root' }) export class UserModalService { - private isOpen = false; - constructor(private modalService: NgbModal, private router: Router, private userService: UserService) {} + private isOpen = false; + constructor(private modalService: NgbModal, private router: Router, private userService: UserService) {} - open(component: Component, login?: string): NgbModalRef { - if (this.isOpen) { - return; - } - this.isOpen = true; - - if (login) { - this.userService.find(login).subscribe(user => this.userModalRef(component, user.body)); - } else { - return this.userModalRef(component, new User()); - } + open(component: Component, login?: string): NgbModalRef { + if (this.isOpen) { + return; } + this.isOpen = true; - userModalRef(component: Component, user: User): NgbModalRef { - const modalRef = this.modalService.open(component, { size: 'lg', backdrop: 'static' }); - modalRef.componentInstance.user = user; - modalRef.result.then( - () => { - this.router.navigate([{ outlets: { popup: null } }], { replaceUrl: true }); - this.isOpen = false; - }, - () => { - this.router.navigate([{ outlets: { popup: null } }], { replaceUrl: true }); - this.isOpen = false; - } - ); - return modalRef; + if (login) { + this.userService.find(login).subscribe(user => this.userModalRef(component, user.body)); + } else { + return this.userModalRef(component, new User()); } + } + + userModalRef(component: Component, user: User): NgbModalRef { + const modalRef = this.modalService.open(component, { size: 'lg', backdrop: 'static' }); + modalRef.componentInstance.user = user; + modalRef.result.then( + () => { + this.router.navigate([{ outlets: { popup: null } }], { replaceUrl: true }); + this.isOpen = false; + }, + () => { + this.router.navigate([{ outlets: { popup: null } }], { replaceUrl: true }); + this.isOpen = false; + } + ); + return modalRef; + } } diff --git a/src/main/webapp/app/entities/statistics/statistics.scss b/src/main/webapp/app/entities/statistics/statistics.scss index 4bdd4560..8a498dc4 100644 --- a/src/main/webapp/app/entities/statistics/statistics.scss +++ b/src/main/webapp/app/entities/statistics/statistics.scss @@ -3,8 +3,8 @@ Statistics page styles ========================================================================== */ .chart { - margin-bottom: 5%; - box-shadow: 5px 5px rgba(53, 61, 71, 0.2); + margin-bottom: 5%; + box-shadow: 5px 5px rgba(53, 61, 71, 0.2); } /* ========================================================================== @@ -12,26 +12,26 @@ Full screen mode ========================================================================== */ .fullScreen { - padding: 1%; - width: 100%; + padding: 1%; + width: 100%; } .numbersCard { - height: 150px; - padding-top: 25px; - width: 100%; + height: 150px; + padding-top: 25px; + width: 100%; } .chartBox { - height: 375px; + height: 375px; } .chartBoxContainer { - margin: auto; + margin: auto; } .categoryChart { - background-color: #e0e0e0; - margin-bottom: 5%; - padding: 1%; + background-color: #e0e0e0; + margin-bottom: 5%; + padding: 1%; } diff --git a/src/main/webapp/app/entities/statistics/statistics.service.ts b/src/main/webapp/app/entities/statistics/statistics.service.ts index f438106a..a6ad5f65 100644 --- a/src/main/webapp/app/entities/statistics/statistics.service.ts +++ b/src/main/webapp/app/entities/statistics/statistics.service.ts @@ -22,37 +22,37 @@ import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class StatisticsService { - constructor(private http: HttpClient) {} + constructor(private http: HttpClient) {} - countYos(): Observable { - return this.http.get(`/api/s/count-yo`); - } + countYos(): Observable { + return this.http.get(`/api/s/count-yo`); + } - countUsers(): Observable { - return this.http.get(`/api/s/count-user`); - } + countUsers(): Observable { + return this.http.get(`/api/s/count-user`); + } - countJdls(): Observable { - return this.http.get(`/api/s/count-jdl`); - } + countJdls(): Observable { + return this.http.get(`/api/s/count-jdl`); + } - getCount(frequency: string): Observable { - return this.http.get(`/api/s/count-yo/${frequency}`); - } + getCount(frequency: string): Observable { + return this.http.get(`/api/s/count-yo/${frequency}`); + } - getFieldCount(field: string, frequency: string): Observable { - return this.http.get(`/api/s/yo/${field}/${frequency}`); - } + getFieldCount(field: string, frequency: string): Observable { + return this.http.get(`/api/s/yo/${field}/${frequency}`); + } - getDeploymentToolsCount(frequency: string): Observable { - return this.http.get(`/api/s/sub-gen-event/deployment/${frequency}`); - } + getDeploymentToolsCount(frequency: string): Observable { + return this.http.get(`/api/s/sub-gen-event/deployment/${frequency}`); + } - getEntityGenerationCount(frequency: string): Observable { - return this.http.get(`/api/s/entity/${frequency}`); - } + getEntityGenerationCount(frequency: string): Observable { + return this.http.get(`/api/s/entity/${frequency}`); + } - getEntityFieldCount(field: string, frequency: string): Observable { - return this.http.get(`/api/s/entity/${field}/${frequency}`); - } + getEntityFieldCount(field: string, frequency: string): Observable { + return this.http.get(`/api/s/entity/${field}/${frequency}`); + } } diff --git a/src/main/webapp/app/home/generator/git.company.model.ts b/src/main/webapp/app/home/generator/git.company.model.ts index 41f17ce4..7409896c 100644 --- a/src/main/webapp/app/home/generator/git.company.model.ts +++ b/src/main/webapp/app/home/generator/git.company.model.ts @@ -17,5 +17,5 @@ * limitations under the License. */ export class GitCompanyModel { - constructor(public id: number, public name: string, public gitProvider: string) {} + constructor(public id: number, public name: string, public gitProvider: string) {} } diff --git a/src/main/webapp/app/home/welcome/welcome.route.ts b/src/main/webapp/app/home/welcome/welcome.route.ts index f7ce8420..8e8960f5 100644 --- a/src/main/webapp/app/home/welcome/welcome.route.ts +++ b/src/main/webapp/app/home/welcome/welcome.route.ts @@ -21,10 +21,10 @@ import { Route } from '@angular/router'; import { WelcomeComponent } from './welcome.component'; export const WELCOME_ROUTE: Route = { - path: '', - component: WelcomeComponent, - data: { - authorities: [], - pageTitle: 'JHipster Online' - } + path: '', + component: WelcomeComponent, + data: { + authorities: [], + pageTitle: 'JHipster Online' + } }; diff --git a/src/main/webapp/app/home/welcome/welcome.scss b/src/main/webapp/app/home/welcome/welcome.scss index a7f8431b..e35a3420 100644 --- a/src/main/webapp/app/home/welcome/welcome.scss +++ b/src/main/webapp/app/home/welcome/welcome.scss @@ -1,7 +1,7 @@ .hipster { - display: inline-block; - width: 170px; - height: 89px; - background: url('../../../content/images/logo-jhipster.svg') no-repeat center top; - background-size: contain; + display: inline-block; + width: 170px; + height: 89px; + background: url('../../../content/images/logo-jhipster.svg') no-repeat center top; + background-size: contain; } diff --git a/src/main/webapp/app/layouts/footer/footer.component.ts b/src/main/webapp/app/layouts/footer/footer.component.ts index 0ee33f10..aa13d6ff 100644 --- a/src/main/webapp/app/layouts/footer/footer.component.ts +++ b/src/main/webapp/app/layouts/footer/footer.component.ts @@ -19,8 +19,8 @@ import { Component } from '@angular/core'; @Component({ - selector: 'jhi-footer', - templateUrl: './footer.component.html', - styleUrls: ['footer.scss'] + selector: 'jhi-footer', + templateUrl: './footer.component.html', + styleUrls: ['footer.scss'] }) export class FooterComponent {} diff --git a/src/main/webapp/app/layouts/footer/footer.scss b/src/main/webapp/app/layouts/footer/footer.scss index f5a9de84..3e73449c 100644 --- a/src/main/webapp/app/layouts/footer/footer.scss +++ b/src/main/webapp/app/layouts/footer/footer.scss @@ -2,5 +2,5 @@ Footer ========================================================================== */ .footer-icons { - font-size: 2.25em; + font-size: 2.25em; } diff --git a/src/main/webapp/app/shared/model/crash-report.model.ts b/src/main/webapp/app/shared/model/crash-report.model.ts index cf6a9523..25ab811a 100644 --- a/src/main/webapp/app/shared/model/crash-report.model.ts +++ b/src/main/webapp/app/shared/model/crash-report.model.ts @@ -1,23 +1,23 @@ import { Moment } from 'moment'; export interface ICrashReport { - id?: number; - date?: Moment; - source?: string; - env?: string; - stack?: string; - yorc?: string; - jdl?: string; + id?: number; + date?: Moment; + source?: string; + env?: string; + stack?: string; + yorc?: string; + jdl?: string; } export class CrashReport implements ICrashReport { - constructor( - public id?: number, - public date?: Moment, - public source?: string, - public env?: string, - public stack?: string, - public yorc?: string, - public jdl?: string - ) {} + constructor( + public id?: number, + public date?: Moment, + public source?: string, + public env?: string, + public stack?: string, + public yorc?: string, + public jdl?: string + ) {} } diff --git a/src/main/webapp/app/shared/model/entity-stats.model.ts b/src/main/webapp/app/shared/model/entity-stats.model.ts index dcdf43bf..b4752d9a 100644 --- a/src/main/webapp/app/shared/model/entity-stats.model.ts +++ b/src/main/webapp/app/shared/model/entity-stats.model.ts @@ -2,39 +2,39 @@ import { Moment } from 'moment'; import { IGeneratorIdentity } from 'app/shared/model//generator-identity.model'; export interface IEntityStats { - id?: number; - year?: number; - month?: number; - week?: number; - day?: number; - hour?: number; - fields?: number; - relationships?: number; - pagination?: string; - dto?: string; - service?: string; - fluentMethods?: boolean; - date?: Moment; - owner?: IGeneratorIdentity; + id?: number; + year?: number; + month?: number; + week?: number; + day?: number; + hour?: number; + fields?: number; + relationships?: number; + pagination?: string; + dto?: string; + service?: string; + fluentMethods?: boolean; + date?: Moment; + owner?: IGeneratorIdentity; } export class EntityStats implements IEntityStats { - constructor( - public id?: number, - public year?: number, - public month?: number, - public week?: number, - public day?: number, - public hour?: number, - public fields?: number, - public relationships?: number, - public pagination?: string, - public dto?: string, - public service?: string, - public fluentMethods?: boolean, - public date?: Moment, - public owner?: IGeneratorIdentity - ) { - this.fluentMethods = false; - } + constructor( + public id?: number, + public year?: number, + public month?: number, + public week?: number, + public day?: number, + public hour?: number, + public fields?: number, + public relationships?: number, + public pagination?: string, + public dto?: string, + public service?: string, + public fluentMethods?: boolean, + public date?: Moment, + public owner?: IGeneratorIdentity + ) { + this.fluentMethods = false; + } } diff --git a/src/main/webapp/app/shared/model/generator-identity.model.ts b/src/main/webapp/app/shared/model/generator-identity.model.ts index 98a5ce8a..c3c85924 100644 --- a/src/main/webapp/app/shared/model/generator-identity.model.ts +++ b/src/main/webapp/app/shared/model/generator-identity.model.ts @@ -1,12 +1,12 @@ import { IUser } from 'app/core/user/user.model'; export interface IGeneratorIdentity { - id?: number; - host?: string; - guid?: string; - owner?: IUser; + id?: number; + host?: string; + guid?: string; + owner?: IUser; } export class GeneratorIdentity implements IGeneratorIdentity { - constructor(public id?: number, public host?: string, public guid?: string, public owner?: IUser) {} + constructor(public id?: number, public host?: string, public guid?: string, public owner?: IUser) {} } diff --git a/src/main/webapp/app/shared/model/language.model.ts b/src/main/webapp/app/shared/model/language.model.ts index 531e710a..1191de16 100644 --- a/src/main/webapp/app/shared/model/language.model.ts +++ b/src/main/webapp/app/shared/model/language.model.ts @@ -1,11 +1,11 @@ import { IYoRC } from './yo-rc.model'; export interface ILanguage { - id?: number; - isoCode?: string; - yoRC?: IYoRC; + id?: number; + isoCode?: string; + yoRC?: IYoRC; } export class Language implements ILanguage { - constructor(public id?: number, public isoCode?: string, public yoRC?: IYoRC) {} + constructor(public id?: number, public isoCode?: string, public yoRC?: IYoRC) {} } diff --git a/src/main/webapp/app/shared/model/sub-gen-event.model.ts b/src/main/webapp/app/shared/model/sub-gen-event.model.ts index b838e76c..483e43f4 100644 --- a/src/main/webapp/app/shared/model/sub-gen-event.model.ts +++ b/src/main/webapp/app/shared/model/sub-gen-event.model.ts @@ -2,31 +2,31 @@ import { Moment } from 'moment'; import { IGeneratorIdentity } from 'app/shared/model//generator-identity.model'; export interface ISubGenEvent { - id?: number; - year?: number; - month?: number; - week?: number; - day?: number; - hour?: number; - source?: string; - type?: string; - event?: string; - date?: Moment; - owner?: IGeneratorIdentity; + id?: number; + year?: number; + month?: number; + week?: number; + day?: number; + hour?: number; + source?: string; + type?: string; + event?: string; + date?: Moment; + owner?: IGeneratorIdentity; } export class SubGenEvent implements ISubGenEvent { - constructor( - public id?: number, - public year?: number, - public month?: number, - public week?: number, - public day?: number, - public hour?: number, - public source?: string, - public type?: string, - public event?: string, - public date?: Moment, - public owner?: IGeneratorIdentity - ) {} + constructor( + public id?: number, + public year?: number, + public month?: number, + public week?: number, + public day?: number, + public hour?: number, + public source?: string, + public type?: string, + public event?: string, + public date?: Moment, + public owner?: IGeneratorIdentity + ) {} } diff --git a/src/main/webapp/app/shared/model/test-framework.model.ts b/src/main/webapp/app/shared/model/test-framework.model.ts index 743f1312..cfb2f9dc 100644 --- a/src/main/webapp/app/shared/model/test-framework.model.ts +++ b/src/main/webapp/app/shared/model/test-framework.model.ts @@ -1,11 +1,11 @@ import { IYoRC } from './yo-rc.model'; export interface ITestFramework { - id?: number; - testFramework?: string; - yorcs?: IYoRC[]; + id?: number; + testFramework?: string; + yorcs?: IYoRC[]; } export class TestFramework implements ITestFramework { - constructor(public id?: number, public testFramework?: string, public yorcs?: IYoRC[]) {} + constructor(public id?: number, public testFramework?: string, public yorcs?: IYoRC[]) {} } diff --git a/src/main/webapp/app/shared/model/yo-rc.model.ts b/src/main/webapp/app/shared/model/yo-rc.model.ts index 35442b79..2545e5ce 100644 --- a/src/main/webapp/app/shared/model/yo-rc.model.ts +++ b/src/main/webapp/app/shared/model/yo-rc.model.ts @@ -2,101 +2,101 @@ import { Moment } from 'moment'; import { IGeneratorIdentity } from 'app/shared/model//generator-identity.model'; export interface IYoRC { - id?: number; - jhipsterVersion?: string; - creationDate?: Moment; - gitProvider?: string; - nodeVersion?: string; - os?: string; - arch?: string; - cpu?: string; - cores?: string; - memory?: string; - userLanguage?: string; - year?: number; - month?: number; - week?: number; - day?: number; - hour?: number; - serverPort?: string; - authenticationType?: string; - cacheProvider?: string; - enableHibernateCache?: boolean; - websocket?: boolean; - databaseType?: string; - devDatabaseType?: string; - prodDatabaseType?: string; - searchEngine?: boolean; - messageBroker?: boolean; - serviceDiscoveryType?: boolean; - buildTool?: string; - enableSwaggerCodegen?: boolean; - clientFramework?: string; - useSass?: boolean; - clientPackageManager?: string; - applicationType?: string; - jhiPrefix?: string; - enableTranslation?: boolean; - nativeLanguage?: string; - hasProtractor?: boolean; - hasGatling?: boolean; - hasCucumber?: boolean; - owner?: IGeneratorIdentity; + id?: number; + jhipsterVersion?: string; + creationDate?: Moment; + gitProvider?: string; + nodeVersion?: string; + os?: string; + arch?: string; + cpu?: string; + cores?: string; + memory?: string; + userLanguage?: string; + year?: number; + month?: number; + week?: number; + day?: number; + hour?: number; + serverPort?: string; + authenticationType?: string; + cacheProvider?: string; + enableHibernateCache?: boolean; + websocket?: boolean; + databaseType?: string; + devDatabaseType?: string; + prodDatabaseType?: string; + searchEngine?: boolean; + messageBroker?: boolean; + serviceDiscoveryType?: boolean; + buildTool?: string; + enableSwaggerCodegen?: boolean; + clientFramework?: string; + useSass?: boolean; + clientPackageManager?: string; + applicationType?: string; + jhiPrefix?: string; + enableTranslation?: boolean; + nativeLanguage?: string; + hasProtractor?: boolean; + hasGatling?: boolean; + hasCucumber?: boolean; + owner?: IGeneratorIdentity; } export class YoRC implements IYoRC { - constructor( - public id?: number, - public jhipsterVersion?: string, - public creationDate?: Moment, - public gitProvider?: string, - public nodeVersion?: string, - public os?: string, - public arch?: string, - public cpu?: string, - public cores?: string, - public memory?: string, - public userLanguage?: string, - public year?: number, - public month?: number, - public week?: number, - public day?: number, - public hour?: number, - public serverPort?: string, - public authenticationType?: string, - public cacheProvider?: string, - public enableHibernateCache?: boolean, - public websocket?: boolean, - public databaseType?: string, - public devDatabaseType?: string, - public prodDatabaseType?: string, - public searchEngine?: boolean, - public messageBroker?: boolean, - public serviceDiscoveryType?: boolean, - public buildTool?: string, - public enableSwaggerCodegen?: boolean, - public clientFramework?: string, - public useSass?: boolean, - public clientPackageManager?: string, - public applicationType?: string, - public jhiPrefix?: string, - public enableTranslation?: boolean, - public nativeLanguage?: string, - public hasProtractor?: boolean, - public hasGatling?: boolean, - public hasCucumber?: boolean, - public owner?: IGeneratorIdentity - ) { - this.enableHibernateCache = false; - this.websocket = false; - this.searchEngine = false; - this.messageBroker = false; - this.serviceDiscoveryType = false; - this.enableSwaggerCodegen = false; - this.useSass = false; - this.enableTranslation = false; - this.hasProtractor = false; - this.hasGatling = false; - this.hasCucumber = false; - } + constructor( + public id?: number, + public jhipsterVersion?: string, + public creationDate?: Moment, + public gitProvider?: string, + public nodeVersion?: string, + public os?: string, + public arch?: string, + public cpu?: string, + public cores?: string, + public memory?: string, + public userLanguage?: string, + public year?: number, + public month?: number, + public week?: number, + public day?: number, + public hour?: number, + public serverPort?: string, + public authenticationType?: string, + public cacheProvider?: string, + public enableHibernateCache?: boolean, + public websocket?: boolean, + public databaseType?: string, + public devDatabaseType?: string, + public prodDatabaseType?: string, + public searchEngine?: boolean, + public messageBroker?: boolean, + public serviceDiscoveryType?: boolean, + public buildTool?: string, + public enableSwaggerCodegen?: boolean, + public clientFramework?: string, + public useSass?: boolean, + public clientPackageManager?: string, + public applicationType?: string, + public jhiPrefix?: string, + public enableTranslation?: boolean, + public nativeLanguage?: string, + public hasProtractor?: boolean, + public hasGatling?: boolean, + public hasCucumber?: boolean, + public owner?: IGeneratorIdentity + ) { + this.enableHibernateCache = false; + this.websocket = false; + this.searchEngine = false; + this.messageBroker = false; + this.serviceDiscoveryType = false; + this.enableSwaggerCodegen = false; + this.useSass = false; + this.enableTranslation = false; + this.hasProtractor = false; + this.hasGatling = false; + this.hasCucumber = false; + } } diff --git a/src/test/java/io/github/jhipster/online/ArchTest.java b/src/test/java/io/github/jhipster/online/ArchTest.java index 481f5250..47208705 100644 --- a/src/test/java/io/github/jhipster/online/ArchTest.java +++ b/src/test/java/io/github/jhipster/online/ArchTest.java @@ -1,29 +1,29 @@ package io.github.jhipster.online; +import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses; + import com.tngtech.archunit.core.domain.JavaClasses; import com.tngtech.archunit.core.importer.ClassFileImporter; import com.tngtech.archunit.core.importer.ImportOption; import org.junit.jupiter.api.Test; -import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses; - class ArchTest { @Test void servicesAndRepositoriesShouldNotDependOnWebLayer() { - JavaClasses importedClasses = new ClassFileImporter() .withImportOption(ImportOption.Predefined.DO_NOT_INCLUDE_TESTS) .importPackages("io.github.jhipster.online"); noClasses() .that() - .resideInAnyPackage("io.github.jhipster.online.service..") + .resideInAnyPackage("io.github.jhipster.online.service..") .or() - .resideInAnyPackage("io.github.jhipster.online.repository..") - .should().dependOnClassesThat() - .resideInAnyPackage("..io.github.jhipster.online.web..") - .because("Services and repositories should not depend on web layer") - .check(importedClasses); + .resideInAnyPackage("io.github.jhipster.online.repository..") + .should() + .dependOnClassesThat() + .resideInAnyPackage("..io.github.jhipster.online.web..") + .because("Services and repositories should not depend on web layer") + .check(importedClasses); } } diff --git a/src/test/java/io/github/jhipster/online/config/AsyncConfiguration.java b/src/test/java/io/github/jhipster/online/config/AsyncConfiguration.java index cc9719c5..c27fa473 100644 --- a/src/test/java/io/github/jhipster/online/config/AsyncConfiguration.java +++ b/src/test/java/io/github/jhipster/online/config/AsyncConfiguration.java @@ -19,6 +19,7 @@ package io.github.jhipster.online.config; import io.github.jhipster.config.JHipsterProperties; +import java.util.concurrent.Executor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Bean; @@ -28,8 +29,6 @@ import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.annotation.EnableScheduling; -import java.util.concurrent.Executor; - @Configuration @EnableAsync @EnableScheduling diff --git a/src/test/java/io/github/jhipster/online/config/NoOpMailConfiguration.java b/src/test/java/io/github/jhipster/online/config/NoOpMailConfiguration.java index feee7a78..60f5b867 100644 --- a/src/test/java/io/github/jhipster/online/config/NoOpMailConfiguration.java +++ b/src/test/java/io/github/jhipster/online/config/NoOpMailConfiguration.java @@ -1,15 +1,16 @@ package io.github.jhipster.online.config; -import io.github.jhipster.online.service.MailService; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.mock; +import io.github.jhipster.online.service.MailService; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + @Configuration public class NoOpMailConfiguration { + private final MailService mockMailService; public NoOpMailConfiguration() { diff --git a/src/test/java/io/github/jhipster/online/config/WebConfigurerTest.java b/src/test/java/io/github/jhipster/online/config/WebConfigurerTest.java index a28b9e5a..2c0f7c37 100644 --- a/src/test/java/io/github/jhipster/online/config/WebConfigurerTest.java +++ b/src/test/java/io/github/jhipster/online/config/WebConfigurerTest.java @@ -18,9 +18,23 @@ */ package io.github.jhipster.online.config; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.options; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + import io.github.jhipster.config.JHipsterConstants; import io.github.jhipster.config.JHipsterProperties; import io.github.jhipster.web.filter.CachingHttpHeadersFilter; +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import javax.servlet.*; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory; @@ -30,21 +44,6 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import javax.servlet.*; -import java.io.File; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.*; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.options; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - /** * Unit tests for the {@link WebConfigurer} class. */ @@ -61,10 +60,8 @@ class WebConfigurerTest { @BeforeEach public void setup() { servletContext = spy(new MockServletContext()); - doReturn(mock(FilterRegistration.Dynamic.class)) - .when(servletContext).addFilter(anyString(), any(Filter.class)); - doReturn(mock(ServletRegistration.Dynamic.class)) - .when(servletContext).addServlet(anyString(), any(Servlet.class)); + doReturn(mock(FilterRegistration.Dynamic.class)).when(servletContext).addFilter(anyString(), any(Filter.class)); + doReturn(mock(ServletRegistration.Dynamic.class)).when(servletContext).addServlet(anyString(), any(Servlet.class)); env = new MockEnvironment(); props = new JHipsterProperties(); @@ -109,14 +106,14 @@ void testCorsFilterOnApiPath() throws Exception { props.getCors().setMaxAge(1800L); props.getCors().setAllowCredentials(true); - MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()) - .addFilters(webConfigurer.corsFilter()) - .build(); + MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build(); - mockMvc.perform( - options("/api/test-cors") - .header(HttpHeaders.ORIGIN, "other.domain.com") - .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST")) + mockMvc + .perform( + options("/api/test-cors") + .header(HttpHeaders.ORIGIN, "other.domain.com") + .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST") + ) .andExpect(status().isOk()) .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")) .andExpect(header().string(HttpHeaders.VARY, "Origin")) @@ -124,9 +121,8 @@ void testCorsFilterOnApiPath() throws Exception { .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")) .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800")); - mockMvc.perform( - get("/api/test-cors") - .header(HttpHeaders.ORIGIN, "other.domain.com")) + mockMvc + .perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")) .andExpect(status().isOk()) .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")); } @@ -139,13 +135,10 @@ void testCorsFilterOnOtherPath() throws Exception { props.getCors().setMaxAge(1800L); props.getCors().setAllowCredentials(true); - MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()) - .addFilters(webConfigurer.corsFilter()) - .build(); + MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build(); - mockMvc.perform( - get("/test/test-cors") - .header(HttpHeaders.ORIGIN, "other.domain.com")) + mockMvc + .perform(get("/test/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")) .andExpect(status().isOk()) .andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); } @@ -154,13 +147,10 @@ void testCorsFilterOnOtherPath() throws Exception { void testCorsFilterDeactivated() throws Exception { props.getCors().setAllowedOrigins(null); - MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()) - .addFilters(webConfigurer.corsFilter()) - .build(); + MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build(); - mockMvc.perform( - get("/api/test-cors") - .header(HttpHeaders.ORIGIN, "other.domain.com")) + mockMvc + .perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")) .andExpect(status().isOk()) .andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); } @@ -169,13 +159,10 @@ void testCorsFilterDeactivated() throws Exception { void testCorsFilterDeactivated2() throws Exception { props.getCors().setAllowedOrigins(new ArrayList<>()); - MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()) - .addFilters(webConfigurer.corsFilter()) - .build(); + MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build(); - mockMvc.perform( - get("/api/test-cors") - .header(HttpHeaders.ORIGIN, "other.domain.com")) + mockMvc + .perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")) .andExpect(status().isOk()) .andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); } diff --git a/src/test/java/io/github/jhipster/online/config/WebConfigurerTestController.java b/src/test/java/io/github/jhipster/online/config/WebConfigurerTestController.java index 784456fd..5696f2b7 100644 --- a/src/test/java/io/github/jhipster/online/config/WebConfigurerTestController.java +++ b/src/test/java/io/github/jhipster/online/config/WebConfigurerTestController.java @@ -25,10 +25,8 @@ public class WebConfigurerTestController { @GetMapping("/api/test-cors") - public void testCorsOnApiPath() { - } + public void testCorsOnApiPath() {} @GetMapping("/test/test-cors") - public void testCorsOnOtherPath() { - } + public void testCorsOnOtherPath() {} } diff --git a/src/test/java/io/github/jhipster/online/repository/CustomAuditEventRepositoryIT.java b/src/test/java/io/github/jhipster/online/repository/CustomAuditEventRepositoryIT.java index 184d9e0f..057b1505 100644 --- a/src/test/java/io/github/jhipster/online/repository/CustomAuditEventRepositoryIT.java +++ b/src/test/java/io/github/jhipster/online/repository/CustomAuditEventRepositoryIT.java @@ -18,10 +18,19 @@ */ package io.github.jhipster.online.repository; +import static io.github.jhipster.online.repository.CustomAuditEventRepository.EVENT_DATA_COLUMN_MAX_LENGTH; +import static org.assertj.core.api.Assertions.assertThat; + import io.github.jhipster.online.JhonlineApp; import io.github.jhipster.online.config.Constants; import io.github.jhipster.online.config.audit.AuditEventConverter; import io.github.jhipster.online.domain.PersistentAuditEvent; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.servlet.http.HttpSession; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -32,16 +41,6 @@ import org.springframework.security.web.authentication.WebAuthenticationDetails; import org.springframework.transaction.annotation.Transactional; -import javax.servlet.http.HttpSession; -import java.time.Instant; -import java.time.temporal.ChronoUnit; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import static io.github.jhipster.online.repository.CustomAuditEventRepository.EVENT_DATA_COLUMN_MAX_LENGTH; -import static org.assertj.core.api.Assertions.assertThat; - /** * Integration tests for {@link CustomAuditEventRepository}. */ @@ -171,5 +170,4 @@ void addAuditEventWithAuthorizationFailureType() { List persistentAuditEvents = persistenceAuditEventRepository.findAll(); assertThat(persistentAuditEvents).isEmpty(); } - } diff --git a/src/test/java/io/github/jhipster/online/security/DomainUserDetailsServiceIT.java b/src/test/java/io/github/jhipster/online/security/DomainUserDetailsServiceIT.java index 4b5e791b..d503c230 100644 --- a/src/test/java/io/github/jhipster/online/security/DomainUserDetailsServiceIT.java +++ b/src/test/java/io/github/jhipster/online/security/DomainUserDetailsServiceIT.java @@ -18,9 +18,13 @@ */ package io.github.jhipster.online.security; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + import io.github.jhipster.online.JhonlineApp; import io.github.jhipster.online.domain.User; import io.github.jhipster.online.repository.UserRepository; +import java.util.Locale; import org.apache.commons.lang3.RandomStringUtils; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -30,11 +34,6 @@ import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.transaction.annotation.Transactional; -import java.util.Locale; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; - /** * Integrations tests for {@link DomainUserDetailsService}. */ @@ -135,8 +134,7 @@ void assertThatEmailIsPrioritizedOverLogin() { @Test @Transactional void assertThatUserNotActivatedExceptionIsThrownForNotActivatedUsers() { - assertThatExceptionOfType(UserNotActivatedException.class).isThrownBy( - () -> domainUserDetailsService.loadUserByUsername(USER_THREE_LOGIN)); + assertThatExceptionOfType(UserNotActivatedException.class) + .isThrownBy(() -> domainUserDetailsService.loadUserByUsername(USER_THREE_LOGIN)); } - } diff --git a/src/test/java/io/github/jhipster/online/security/SecurityUtilsUnitTest.java b/src/test/java/io/github/jhipster/online/security/SecurityUtilsUnitTest.java index c076c9b3..c9421b77 100644 --- a/src/test/java/io/github/jhipster/online/security/SecurityUtilsUnitTest.java +++ b/src/test/java/io/github/jhipster/online/security/SecurityUtilsUnitTest.java @@ -18,6 +18,11 @@ */ package io.github.jhipster.online.security; +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Optional; import org.junit.jupiter.api.Test; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.GrantedAuthority; @@ -25,12 +30,6 @@ import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Optional; - -import static org.assertj.core.api.Assertions.assertThat; - /** * Test class for the {@link SecurityUtils} utility class. */ @@ -85,5 +84,4 @@ void testIsCurrentUserInRole() { assertThat(SecurityUtils.isCurrentUserInRole(AuthoritiesConstants.USER)).isTrue(); assertThat(SecurityUtils.isCurrentUserInRole(AuthoritiesConstants.ADMIN)).isFalse(); } - } diff --git a/src/test/java/io/github/jhipster/online/security/jwt/JWTFilterTest.java b/src/test/java/io/github/jhipster/online/security/jwt/JWTFilterTest.java index 7a2572f6..a8f75e62 100644 --- a/src/test/java/io/github/jhipster/online/security/jwt/JWTFilterTest.java +++ b/src/test/java/io/github/jhipster/online/security/jwt/JWTFilterTest.java @@ -18,10 +18,13 @@ */ package io.github.jhipster.online.security.jwt; +import static org.assertj.core.api.Assertions.assertThat; + import io.github.jhipster.config.JHipsterProperties; import io.github.jhipster.online.security.AuthoritiesConstants; import io.jsonwebtoken.io.Decoders; import io.jsonwebtoken.security.Keys; +import java.util.Collections; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.http.HttpStatus; @@ -33,10 +36,6 @@ import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.test.util.ReflectionTestUtils; -import java.util.Collections; - -import static org.assertj.core.api.Assertions.assertThat; - class JWTFilterTest { private TokenProvider tokenProvider; @@ -127,5 +126,4 @@ void testJWTFilterWrongScheme() throws Exception { assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); } - } diff --git a/src/test/java/io/github/jhipster/online/security/jwt/TokenProviderTest.java b/src/test/java/io/github/jhipster/online/security/jwt/TokenProviderTest.java index 66e38957..d99e7f5a 100644 --- a/src/test/java/io/github/jhipster/online/security/jwt/TokenProviderTest.java +++ b/src/test/java/io/github/jhipster/online/security/jwt/TokenProviderTest.java @@ -18,12 +18,18 @@ */ package io.github.jhipster.online.security.jwt; +import static org.assertj.core.api.Assertions.assertThat; + import io.github.jhipster.config.JHipsterProperties; import io.github.jhipster.online.security.AuthoritiesConstants; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import io.jsonwebtoken.io.Decoders; import io.jsonwebtoken.security.Keys; +import java.security.Key; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; @@ -32,14 +38,8 @@ import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.test.util.ReflectionTestUtils; -import java.security.Key; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; - -import static org.assertj.core.api.Assertions.assertThat; - class TokenProviderTest { + private static final long ONE_MINUTE = 60000; private Key key; @@ -110,17 +110,16 @@ private Authentication createAuthentication() { } private String createUnsupportedToken() { - return Jwts.builder() - .setPayload("payload") - .signWith(key, SignatureAlgorithm.HS512) - .compact(); + return Jwts.builder().setPayload("payload").signWith(key, SignatureAlgorithm.HS512).compact(); } private String createTokenWithDifferentSignature() { - Key otherKey = Keys.hmacShaKeyFor(Decoders.BASE64 - .decode("Xfd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8")); + Key otherKey = Keys.hmacShaKeyFor( + Decoders.BASE64.decode("Xfd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8") + ); - return Jwts.builder() + return Jwts + .builder() .setSubject("anonymous") .signWith(otherKey, SignatureAlgorithm.HS512) .setExpiration(new Date(new Date().getTime() + ONE_MINUTE)) diff --git a/src/test/java/io/github/jhipster/online/service/AuditEventServiceIT.java b/src/test/java/io/github/jhipster/online/service/AuditEventServiceIT.java index d4414df6..88c07a82 100644 --- a/src/test/java/io/github/jhipster/online/service/AuditEventServiceIT.java +++ b/src/test/java/io/github/jhipster/online/service/AuditEventServiceIT.java @@ -1,26 +1,26 @@ package io.github.jhipster.online.service; +import static org.assertj.core.api.Assertions.assertThat; + import io.github.jhipster.config.JHipsterProperties; import io.github.jhipster.online.JhonlineApp; import io.github.jhipster.online.domain.PersistentAuditEvent; import io.github.jhipster.online.repository.PersistenceAuditEventRepository; +import java.time.Instant; +import java.time.temporal.ChronoUnit; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.transaction.annotation.Transactional; -import java.time.Instant; -import java.time.temporal.ChronoUnit; - -import static org.assertj.core.api.Assertions.assertThat; - /** * Integration tests for {@link AuditEventService}. */ @SpringBootTest(classes = JhonlineApp.class) @Transactional -class AuditEventServiceIT { +class AuditEventServiceIT { + @Autowired private AuditEventService auditEventService; @@ -44,7 +44,9 @@ public void init() { auditEventOld.setAuditEventType("test-type"); auditEventWithinRetention = new PersistentAuditEvent(); - auditEventWithinRetention.setAuditEventDate(Instant.now().minus(jHipsterProperties.getAuditEvents().getRetentionPeriod() - 1, ChronoUnit.DAYS)); + auditEventWithinRetention.setAuditEventDate( + Instant.now().minus(jHipsterProperties.getAuditEvents().getRetentionPeriod() - 1, ChronoUnit.DAYS) + ); auditEventWithinRetention.setPrincipal("test-user-retention"); auditEventWithinRetention.setAuditEventType("test-type"); diff --git a/src/test/java/io/github/jhipster/online/service/DataGenerationFixture.java b/src/test/java/io/github/jhipster/online/service/DataGenerationFixture.java index b5bb11f5..cd0b380d 100644 --- a/src/test/java/io/github/jhipster/online/service/DataGenerationFixture.java +++ b/src/test/java/io/github/jhipster/online/service/DataGenerationFixture.java @@ -19,16 +19,15 @@ package io.github.jhipster.online.service; +import static java.time.ZonedDateTime.parse; + import io.github.jhipster.online.domain.YoRC; import io.github.jhipster.online.repository.YoRCRepository; - import java.time.Instant; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.temporal.ChronoUnit; -import static java.time.ZonedDateTime.parse; - public class DataGenerationFixture { public static void fillDatabaseWithYoRCs(YoRCRepository yoRCRepository) { @@ -61,7 +60,8 @@ public static void fillDatabaseWithYoRCs(YoRCRepository yoRCRepository) { } public static YoRC yorc(Instant createdDate, String clientFramework) { - YoRC yorc = new YoRC().serverPort("8080") + YoRC yorc = new YoRC() + .serverPort("8080") .authenticationType("jwt") .cacheProvider("ehcache") .enableHibernateCache(true) diff --git a/src/test/java/io/github/jhipster/online/service/GeneratorIdentityServiceTest.java b/src/test/java/io/github/jhipster/online/service/GeneratorIdentityServiceTest.java index e0e83e85..94aef119 100644 --- a/src/test/java/io/github/jhipster/online/service/GeneratorIdentityServiceTest.java +++ b/src/test/java/io/github/jhipster/online/service/GeneratorIdentityServiceTest.java @@ -19,9 +19,13 @@ package io.github.jhipster.online.service; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + import io.github.jhipster.online.JhonlineApp; import io.github.jhipster.online.domain.GeneratorIdentity; import io.github.jhipster.online.repository.GeneratorIdentityRepository; +import java.util.Optional; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -31,11 +35,6 @@ import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.test.context.junit.jupiter.SpringExtension; -import java.util.Optional; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.when; - @ExtendWith(SpringExtension.class) @SpringBootTest(classes = JhonlineApp.class) class GeneratorIdentityServiceTest { diff --git a/src/test/java/io/github/jhipster/online/service/MailServiceIT.java b/src/test/java/io/github/jhipster/online/service/MailServiceIT.java index 8eff3b45..4c20bc02 100644 --- a/src/test/java/io/github/jhipster/online/service/MailServiceIT.java +++ b/src/test/java/io/github/jhipster/online/service/MailServiceIT.java @@ -18,10 +18,30 @@ */ package io.github.jhipster.online.service; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + import io.github.jhipster.config.JHipsterProperties; import io.github.jhipster.online.JhonlineApp; import io.github.jhipster.online.config.Constants; import io.github.jhipster.online.domain.User; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStreamReader; +import java.net.URI; +import java.net.URL; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.util.Properties; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import javax.mail.Multipart; +import javax.mail.internet.MimeBodyPart; +import javax.mail.internet.MimeMessage; +import javax.mail.internet.MimeMultipart; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; @@ -35,27 +55,6 @@ import org.springframework.mail.javamail.JavaMailSenderImpl; import org.thymeleaf.spring5.SpringTemplateEngine; -import javax.mail.Multipart; -import javax.mail.internet.MimeBodyPart; -import javax.mail.internet.MimeMessage; -import javax.mail.internet.MimeMultipart; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.InputStreamReader; -import java.net.URI; -import java.net.URL; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.util.Properties; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.*; - /** * Integration tests for {@link MailService}. */ @@ -242,7 +241,8 @@ void testSendLocalizedEmailForAllSupportedLanguages() throws Exception { String emailTitle = (String) properties.get("email.test.title"); assertThat(message.getSubject()).isEqualTo(emailTitle); - assertThat(message.getContent().toString()).isEqualToNormalizingNewlines("" + emailTitle + ", http://127.0.0.1:8080, john\n"); + assertThat(message.getContent().toString()) + .isEqualToNormalizingNewlines("" + emailTitle + ", http://127.0.0.1:8080, john\n"); } } @@ -253,7 +253,7 @@ private String getJavaLocale(String langKey) { String javaLangKey = langKey; Matcher matcher2 = PATTERN_LOCALE_2.matcher(langKey); if (matcher2.matches()) { - javaLangKey = matcher2.group(1) + "_"+ matcher2.group(2).toUpperCase(); + javaLangKey = matcher2.group(1) + "_" + matcher2.group(2).toUpperCase(); } Matcher matcher3 = PATTERN_LOCALE_3.matcher(langKey); if (matcher3.matches()) { diff --git a/src/test/java/io/github/jhipster/online/service/UserServiceIT.java b/src/test/java/io/github/jhipster/online/service/UserServiceIT.java index 6ce13058..16230396 100644 --- a/src/test/java/io/github/jhipster/online/service/UserServiceIT.java +++ b/src/test/java/io/github/jhipster/online/service/UserServiceIT.java @@ -18,12 +18,20 @@ */ package io.github.jhipster.online.service; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + import io.github.jhipster.online.JhonlineApp; import io.github.jhipster.online.config.Constants; import io.github.jhipster.online.domain.User; import io.github.jhipster.online.repository.UserRepository; import io.github.jhipster.online.service.dto.UserDTO; import io.github.jhipster.security.RandomUtil; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.temporal.ChronoUnit; +import java.util.List; +import java.util.Optional; import org.apache.commons.lang3.RandomStringUtils; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -36,15 +44,6 @@ import org.springframework.data.domain.PageRequest; import org.springframework.transaction.annotation.Transactional; -import java.time.Instant; -import java.time.LocalDateTime; -import java.time.temporal.ChronoUnit; -import java.util.List; -import java.util.Optional; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.when; - /** * Integration tests for {@link UserService}. */ @@ -178,7 +177,9 @@ void assertThatNotActivatedUsersWithNotNullActivationKeyCreatedBefore3DaysAreDel User dbUser = userRepository.saveAndFlush(user); dbUser.setCreatedDate(now.minus(4, ChronoUnit.DAYS)); userRepository.saveAndFlush(user); - List users = userRepository.findAllByActivatedIsFalseAndActivationKeyIsNotNullAndCreatedDateBefore(now.minus(3, ChronoUnit.DAYS)); + List users = userRepository.findAllByActivatedIsFalseAndActivationKeyIsNotNullAndCreatedDateBefore( + now.minus(3, ChronoUnit.DAYS) + ); assertThat(users).isNotEmpty(); userService.removeNotActivatedUsers(); users = userRepository.findAllByActivatedIsFalseAndActivationKeyIsNotNullAndCreatedDateBefore(now.minus(3, ChronoUnit.DAYS)); @@ -194,7 +195,9 @@ void assertThatNotActivatedUsersWithNullActivationKeyCreatedBefore3DaysAreNotDel User dbUser = userRepository.saveAndFlush(user); dbUser.setCreatedDate(now.minus(4, ChronoUnit.DAYS)); userRepository.saveAndFlush(user); - List users = userRepository.findAllByActivatedIsFalseAndActivationKeyIsNotNullAndCreatedDateBefore(now.minus(3, ChronoUnit.DAYS)); + List users = userRepository.findAllByActivatedIsFalseAndActivationKeyIsNotNullAndCreatedDateBefore( + now.minus(3, ChronoUnit.DAYS) + ); assertThat(users).isEmpty(); userService.removeNotActivatedUsers(); Optional maybeDbUser = userRepository.findById(dbUser.getId()); @@ -210,9 +213,6 @@ void assertThatAnonymousUserIsNotGet() { } final PageRequest pageable = PageRequest.of(0, (int) userRepository.count()); final Page allManagedUsers = userService.getAllManagedUsers(pageable); - assertThat(allManagedUsers.getContent().stream() - .noneMatch(user -> Constants.ANONYMOUS_USER.equals(user.getLogin()))) - .isTrue(); + assertThat(allManagedUsers.getContent().stream().noneMatch(user -> Constants.ANONYMOUS_USER.equals(user.getLogin()))).isTrue(); } - } diff --git a/src/test/java/io/github/jhipster/online/service/enums/TemporalValueTypeTest.java b/src/test/java/io/github/jhipster/online/service/enums/TemporalValueTypeTest.java index bb353888..209f6e03 100644 --- a/src/test/java/io/github/jhipster/online/service/enums/TemporalValueTypeTest.java +++ b/src/test/java/io/github/jhipster/online/service/enums/TemporalValueTypeTest.java @@ -1,12 +1,11 @@ package io.github.jhipster.online.service.enums; -import org.junit.jupiter.api.Test; - -import java.time.Instant; - import static java.time.Instant.parse; import static org.assertj.core.api.Assertions.assertThat; +import java.time.Instant; +import org.junit.jupiter.api.Test; + class TemporalValueTypeTest { @Test diff --git a/src/test/java/io/github/jhipster/online/service/mapper/UserMapperTest.java b/src/test/java/io/github/jhipster/online/service/mapper/UserMapperTest.java index 3afa1149..0781ba4f 100644 --- a/src/test/java/io/github/jhipster/online/service/mapper/UserMapperTest.java +++ b/src/test/java/io/github/jhipster/online/service/mapper/UserMapperTest.java @@ -1,17 +1,16 @@ package io.github.jhipster.online.service.mapper; +import static org.assertj.core.api.Assertions.assertThat; + import io.github.jhipster.online.domain.User; import io.github.jhipster.online.service.dto.UserDTO; -import org.apache.commons.lang3.RandomStringUtils; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; - -import static org.assertj.core.api.Assertions.assertThat; +import org.apache.commons.lang3.RandomStringUtils; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Unit tests for {@link UserMapper}. diff --git a/src/test/java/io/github/jhipster/online/service/yorc/YoRCServiceChoicesIntTest.java b/src/test/java/io/github/jhipster/online/service/yorc/YoRCServiceChoicesIntTest.java index 75f869e4..b7565525 100644 --- a/src/test/java/io/github/jhipster/online/service/yorc/YoRCServiceChoicesIntTest.java +++ b/src/test/java/io/github/jhipster/online/service/yorc/YoRCServiceChoicesIntTest.java @@ -19,6 +19,9 @@ package io.github.jhipster.online.service.yorc; +import static java.time.ZonedDateTime.parse; +import static org.assertj.core.api.Assertions.assertThat; + import io.github.jhipster.online.JhonlineApp; import io.github.jhipster.online.domain.enums.YoRCColumn; import io.github.jhipster.online.repository.YoRCRepository; @@ -26,6 +29,9 @@ import io.github.jhipster.online.service.YoRCService; import io.github.jhipster.online.service.dto.TemporalDistributionDTO; import io.github.jhipster.online.service.enums.TemporalValueType; +import java.time.Instant; +import java.util.List; +import java.util.Map; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; @@ -33,13 +39,6 @@ import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.transaction.annotation.Transactional; -import java.time.Instant; -import java.util.List; -import java.util.Map; - -import static java.time.ZonedDateTime.parse; -import static org.assertj.core.api.Assertions.assertThat; - @ExtendWith(SpringExtension.class) @SpringBootTest(classes = JhonlineApp.class) class YoRCServiceChoicesIntTest { @@ -64,10 +63,7 @@ void assertThatYearlyProportionsAreCorrect() { assertThat(result) .hasSize(2) .extracting(TemporalDistributionDTO::getDate) - .containsExactly( - Instant.parse("2018-01-01T00:00:00Z"), - Instant.parse("2019-01-01T00:00:00Z") - ); + .containsExactly(Instant.parse("2018-01-01T00:00:00Z"), Instant.parse("2019-01-01T00:00:00Z")); Map fst = result.get(0).getValues(); // 2018 Map snd = result.get(1).getValues(); // 2019 diff --git a/src/test/java/io/github/jhipster/online/service/yorc/YoRCServiceCountsIntTest.java b/src/test/java/io/github/jhipster/online/service/yorc/YoRCServiceCountsIntTest.java index f67d80c1..e3157e36 100644 --- a/src/test/java/io/github/jhipster/online/service/yorc/YoRCServiceCountsIntTest.java +++ b/src/test/java/io/github/jhipster/online/service/yorc/YoRCServiceCountsIntTest.java @@ -19,12 +19,18 @@ package io.github.jhipster.online.service.yorc; +import static java.time.ZonedDateTime.parse; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.tuple; + import io.github.jhipster.online.JhonlineApp; import io.github.jhipster.online.repository.YoRCRepository; import io.github.jhipster.online.service.DataGenerationFixture; import io.github.jhipster.online.service.YoRCService; import io.github.jhipster.online.service.dto.TemporalCountDTO; import io.github.jhipster.online.service.enums.TemporalValueType; +import java.time.Instant; +import java.util.List; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; @@ -32,13 +38,6 @@ import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.transaction.annotation.Transactional; -import java.time.Instant; -import java.util.List; - -import static java.time.ZonedDateTime.parse; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.tuple; - @ExtendWith(SpringExtension.class) @SpringBootTest(classes = JhonlineApp.class) class YoRCServiceCountsIntTest { @@ -62,10 +61,7 @@ void assertThatYearCountIsCorrect() { assertThat(result) .hasSize(2) .extracting(TemporalCountDTO::getDate, TemporalCountDTO::getCount) - .contains( - tuple(Instant.parse("2018-01-01T00:00:00Z"), 8L), - tuple(Instant.parse("2019-01-01T00:00:00Z"), 4L) - ); + .contains(tuple(Instant.parse("2018-01-01T00:00:00Z"), 8L), tuple(Instant.parse("2019-01-01T00:00:00Z"), 4L)); } @Transactional diff --git a/src/test/java/io/github/jhipster/online/util/DateUtilTest.java b/src/test/java/io/github/jhipster/online/util/DateUtilTest.java index a95a298b..3adb7d97 100644 --- a/src/test/java/io/github/jhipster/online/util/DateUtilTest.java +++ b/src/test/java/io/github/jhipster/online/util/DateUtilTest.java @@ -1,16 +1,15 @@ package io.github.jhipster.online.util; +import static java.time.Instant.parse; +import static org.assertj.core.api.Assertions.assertThat; + import io.github.jhipster.online.domain.YoRC; import io.github.jhipster.online.service.DataGenerationFixture; -import org.junit.jupiter.api.Test; -import org.springframework.transaction.annotation.Transactional; - import java.time.Instant; import java.time.ZoneId; import java.time.ZonedDateTime; - -import static java.time.Instant.parse; -import static org.assertj.core.api.Assertions.assertThat; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.annotation.Transactional; class DateUtilTest { diff --git a/src/test/java/io/github/jhipster/online/util/SanitizeInputsTest.java b/src/test/java/io/github/jhipster/online/util/SanitizeInputsTest.java index cf2ac649..4a5ab637 100644 --- a/src/test/java/io/github/jhipster/online/util/SanitizeInputsTest.java +++ b/src/test/java/io/github/jhipster/online/util/SanitizeInputsTest.java @@ -1,9 +1,8 @@ package io.github.jhipster.online.util; -import org.junit.jupiter.api.Test; - import static org.assertj.core.api.Assertions.assertThat; +import org.junit.jupiter.api.Test; class SanitizeInputsTest { @@ -30,12 +29,12 @@ void isAlphaNumeric() { @Test void isLettersNumbersAndSpaces() { - assertThat(SanitizeInputs.isLettersNumbersAndSpaces(null)).isFalse(); - assertThat(SanitizeInputs.isLettersNumbersAndSpaces("This is JHipster")).isTrue(); - assertThat(SanitizeInputs.isLettersNumbersAndSpaces("442kj32342kd")).isTrue(); - assertThat(SanitizeInputs.isLettersNumbersAndSpaces("23094823023")).isTrue(); - assertThat(SanitizeInputs.isLettersNumbersAndSpaces("2309/482$3023")).isFalse(); - assertThat(SanitizeInputs.isLettersNumbersAndSpaces("2309/\n482\r$3\t023")).isFalse(); - assertThat(SanitizeInputs.isLettersNumbersAndSpaces("23};09/\n482\r$3\t023**")).isFalse(); + assertThat(SanitizeInputs.isLettersNumbersAndSpaces(null)).isFalse(); + assertThat(SanitizeInputs.isLettersNumbersAndSpaces("This is JHipster")).isTrue(); + assertThat(SanitizeInputs.isLettersNumbersAndSpaces("442kj32342kd")).isTrue(); + assertThat(SanitizeInputs.isLettersNumbersAndSpaces("23094823023")).isTrue(); + assertThat(SanitizeInputs.isLettersNumbersAndSpaces("2309/482$3023")).isFalse(); + assertThat(SanitizeInputs.isLettersNumbersAndSpaces("2309/\n482\r$3\t023")).isFalse(); + assertThat(SanitizeInputs.isLettersNumbersAndSpaces("23};09/\n482\r$3\t023**")).isFalse(); } } diff --git a/src/test/java/io/github/jhipster/online/web/rest/AccountResourceIT.java b/src/test/java/io/github/jhipster/online/web/rest/AccountResourceIT.java index af2f6447..1239c162 100644 --- a/src/test/java/io/github/jhipster/online/web/rest/AccountResourceIT.java +++ b/src/test/java/io/github/jhipster/online/web/rest/AccountResourceIT.java @@ -18,6 +18,12 @@ */ package io.github.jhipster.online.web.rest; +import static io.github.jhipster.online.web.rest.AccountResourceIT.TEST_USER_LOGIN; +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + import io.github.jhipster.online.JhonlineApp; import io.github.jhipster.online.config.Constants; import io.github.jhipster.online.domain.User; @@ -29,6 +35,11 @@ import io.github.jhipster.online.service.dto.UserDTO; import io.github.jhipster.online.web.rest.vm.KeyAndPasswordVM; import io.github.jhipster.online.web.rest.vm.ManagedUserVM; +import java.time.Instant; +import java.util.Collections; +import java.util.HashSet; +import java.util.Optional; +import java.util.Set; import org.apache.commons.lang3.RandomStringUtils; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -40,18 +51,6 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.transaction.annotation.Transactional; -import java.time.Instant; -import java.util.Collections; -import java.util.HashSet; -import java.util.Optional; -import java.util.Set; - -import static io.github.jhipster.online.web.rest.AccountResourceIT.TEST_USER_LOGIN; -import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; - /** * Integration tests for the {@link AccountResource} REST controller. */ @@ -59,6 +58,7 @@ @WithMockUser(value = TEST_USER_LOGIN) @SpringBootTest(classes = JhonlineApp.class) class AccountResourceIT { + static final String TEST_USER_LOGIN = "test"; @Autowired @@ -79,20 +79,25 @@ class AccountResourceIT { @Test @WithUnauthenticatedMockUser void testNonAuthenticatedUser() throws Exception { - restAccountMockMvc.perform(get("/api/authenticate") - .accept(MediaType.APPLICATION_JSON)) + restAccountMockMvc + .perform(get("/api/authenticate").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().string("")); } @Test void testAuthenticatedUser() throws Exception { - restAccountMockMvc.perform(get("/api/authenticate") - .with(request -> { - request.setRemoteUser(TEST_USER_LOGIN); - return request; - }) - .accept(MediaType.APPLICATION_JSON)) + restAccountMockMvc + .perform( + get("/api/authenticate") + .with( + request -> { + request.setRemoteUser(TEST_USER_LOGIN); + return request; + } + ) + .accept(MediaType.APPLICATION_JSON) + ) .andExpect(status().isOk()) .andExpect(content().string(TEST_USER_LOGIN)); } @@ -112,8 +117,8 @@ void testGetExistingAccount() throws Exception { user.setAuthorities(authorities); userService.createUser(user); - restAccountMockMvc.perform(get("/api/account") - .accept(MediaType.APPLICATION_JSON)) + restAccountMockMvc + .perform(get("/api/account").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(jsonPath("$.login").value(TEST_USER_LOGIN)) @@ -127,8 +132,8 @@ void testGetExistingAccount() throws Exception { @Test void testGetUnknownAccount() throws Exception { - restAccountMockMvc.perform(get("/api/account") - .accept(MediaType.APPLICATION_PROBLEM_JSON)) + restAccountMockMvc + .perform(get("/api/account").accept(MediaType.APPLICATION_PROBLEM_JSON)) .andExpect(status().isInternalServerError()); } @@ -146,10 +151,8 @@ void testRegisterValid() throws Exception { validUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); assertThat(userRepository.findOneByLogin("test-register-valid")).isNotPresent(); - restAccountMockMvc.perform( - post("/api/register") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(validUser))) + restAccountMockMvc + .perform(post("/api/register").contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(validUser))) .andExpect(status().isCreated()); assertThat(userRepository.findOneByLogin("test-register-valid")).isPresent(); @@ -159,7 +162,7 @@ void testRegisterValid() throws Exception { @Transactional void testRegisterInvalidLogin() throws Exception { ManagedUserVM invalidUser = new ManagedUserVM(); - invalidUser.setLogin("funky-log!n");// <-- invalid + invalidUser.setLogin("funky-log!n"); // <-- invalid invalidUser.setPassword("password"); invalidUser.setFirstName("Funky"); invalidUser.setLastName("One"); @@ -169,10 +172,8 @@ void testRegisterInvalidLogin() throws Exception { invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE); invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); - restAccountMockMvc.perform( - post("/api/register") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(invalidUser))) + restAccountMockMvc + .perform(post("/api/register").contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(invalidUser))) .andExpect(status().isBadRequest()); Optional user = userRepository.findOneByEmailIgnoreCase("funky@example.com"); @@ -187,16 +188,14 @@ void testRegisterInvalidEmail() throws Exception { invalidUser.setPassword("password"); invalidUser.setFirstName("Bob"); invalidUser.setLastName("Green"); - invalidUser.setEmail("invalid");// <-- invalid + invalidUser.setEmail("invalid"); // <-- invalid invalidUser.setActivated(true); invalidUser.setImageUrl("http://placehold.it/50x50"); invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE); invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); - restAccountMockMvc.perform( - post("/api/register") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(invalidUser))) + restAccountMockMvc + .perform(post("/api/register").contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(invalidUser))) .andExpect(status().isBadRequest()); Optional user = userRepository.findOneByLogin("bob"); @@ -208,7 +207,7 @@ void testRegisterInvalidEmail() throws Exception { void testRegisterInvalidPassword() throws Exception { ManagedUserVM invalidUser = new ManagedUserVM(); invalidUser.setLogin("bob"); - invalidUser.setPassword("123");// password with only 3 digits + invalidUser.setPassword("123"); // password with only 3 digits invalidUser.setFirstName("Bob"); invalidUser.setLastName("Green"); invalidUser.setEmail("bob@example.com"); @@ -217,10 +216,8 @@ void testRegisterInvalidPassword() throws Exception { invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE); invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); - restAccountMockMvc.perform( - post("/api/register") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(invalidUser))) + restAccountMockMvc + .perform(post("/api/register").contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(invalidUser))) .andExpect(status().isBadRequest()); Optional user = userRepository.findOneByLogin("bob"); @@ -232,7 +229,7 @@ void testRegisterInvalidPassword() throws Exception { void testRegisterNullPassword() throws Exception { ManagedUserVM invalidUser = new ManagedUserVM(); invalidUser.setLogin("bob"); - invalidUser.setPassword(null);// invalid null password + invalidUser.setPassword(null); // invalid null password invalidUser.setFirstName("Bob"); invalidUser.setLastName("Green"); invalidUser.setEmail("bob@example.com"); @@ -241,10 +238,8 @@ void testRegisterNullPassword() throws Exception { invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE); invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); - restAccountMockMvc.perform( - post("/api/register") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(invalidUser))) + restAccountMockMvc + .perform(post("/api/register").contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(invalidUser))) .andExpect(status().isBadRequest()); Optional user = userRepository.findOneByLogin("bob"); @@ -281,17 +276,13 @@ void testRegisterDuplicateLogin() throws Exception { secondUser.setAuthorities(new HashSet<>(firstUser.getAuthorities())); // First user - restAccountMockMvc.perform( - post("/api/register") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(firstUser))) + restAccountMockMvc + .perform(post("/api/register").contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(firstUser))) .andExpect(status().isCreated()); // Second (non activated) user - restAccountMockMvc.perform( - post("/api/register") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(secondUser))) + restAccountMockMvc + .perform(post("/api/register").contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(secondUser))) .andExpect(status().isCreated()); Optional testUser = userRepository.findOneByEmailIgnoreCase("alice2@example.com"); @@ -300,10 +291,8 @@ void testRegisterDuplicateLogin() throws Exception { userRepository.save(testUser.get()); // Second (already activated) user - restAccountMockMvc.perform( - post("/api/register") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(secondUser))) + restAccountMockMvc + .perform(post("/api/register").contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(secondUser))) .andExpect(status().is4xxClientError()); } @@ -322,10 +311,8 @@ void testRegisterDuplicateEmail() throws Exception { firstUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); // Register first user - restAccountMockMvc.perform( - post("/api/register") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(firstUser))) + restAccountMockMvc + .perform(post("/api/register").contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(firstUser))) .andExpect(status().isCreated()); Optional testUser1 = userRepository.findOneByLogin("test-register-duplicate-email"); @@ -343,10 +330,8 @@ void testRegisterDuplicateEmail() throws Exception { secondUser.setAuthorities(new HashSet<>(firstUser.getAuthorities())); // Register second (non activated) user - restAccountMockMvc.perform( - post("/api/register") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(secondUser))) + restAccountMockMvc + .perform(post("/api/register").contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(secondUser))) .andExpect(status().isCreated()); Optional testUser2 = userRepository.findOneByLogin("test-register-duplicate-email"); @@ -368,10 +353,12 @@ void testRegisterDuplicateEmail() throws Exception { userWithUpperCaseEmail.setAuthorities(new HashSet<>(firstUser.getAuthorities())); // Register third (not activated) user - restAccountMockMvc.perform( - post("/api/register") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(userWithUpperCaseEmail))) + restAccountMockMvc + .perform( + post("/api/register") + .contentType(MediaType.APPLICATION_JSON) + .content(TestUtil.convertObjectToJsonBytes(userWithUpperCaseEmail)) + ) .andExpect(status().isCreated()); Optional testUser4 = userRepository.findOneByLogin("test-register-duplicate-email-3"); @@ -382,10 +369,8 @@ void testRegisterDuplicateEmail() throws Exception { userService.updateUser((new UserDTO(testUser4.get()))); // Register 4th (already activated) user - restAccountMockMvc.perform( - post("/api/register") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(secondUser))) + restAccountMockMvc + .perform(post("/api/register").contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(secondUser))) .andExpect(status().is4xxClientError()); } @@ -403,15 +388,14 @@ void testRegisterAdminIsIgnored() throws Exception { validUser.setLangKey(Constants.DEFAULT_LANGUAGE); validUser.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN)); - restAccountMockMvc.perform( - post("/api/register") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(validUser))) + restAccountMockMvc + .perform(post("/api/register").contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(validUser))) .andExpect(status().isCreated()); Optional userDup = userRepository.findOneByLogin("badguy"); assertThat(userDup).isPresent(); - assertThat(userDup.get().getAuthorities()).hasSize(1) + assertThat(userDup.get().getAuthorities()) + .hasSize(1) .containsExactly(authorityRepository.findById(AuthoritiesConstants.USER).get()); } @@ -428,8 +412,7 @@ void testActivateAccount() throws Exception { userRepository.saveAndFlush(user); - restAccountMockMvc.perform(get("/api/activate?key={activationKey}", activationKey)) - .andExpect(status().isOk()); + restAccountMockMvc.perform(get("/api/activate?key={activationKey}", activationKey)).andExpect(status().isOk()); user = userRepository.findOneByLogin(user.getLogin()).orElse(null); assertThat(user.getActivated()).isTrue(); @@ -438,8 +421,7 @@ void testActivateAccount() throws Exception { @Test @Transactional void testActivateAccountWithWrongKey() throws Exception { - restAccountMockMvc.perform(get("/api/activate?key=wrongActivationKey")) - .andExpect(status().isInternalServerError()); + restAccountMockMvc.perform(get("/api/activate?key=wrongActivationKey")).andExpect(status().isInternalServerError()); } @Test @@ -464,10 +446,8 @@ void testSaveAccount() throws Exception { userDTO.setLangKey(Constants.DEFAULT_LANGUAGE); userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN)); - restAccountMockMvc.perform( - post("/api/account") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(userDTO))) + restAccountMockMvc + .perform(post("/api/account").contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(userDTO))) .andExpect(status().isOk()); User updatedUser = userRepository.findOneByLogin(user.getLogin()).orElse(null); @@ -503,10 +483,8 @@ void testSaveInvalidEmail() throws Exception { userDTO.setLangKey(Constants.DEFAULT_LANGUAGE); userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN)); - restAccountMockMvc.perform( - post("/api/account") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(userDTO))) + restAccountMockMvc + .perform(post("/api/account").contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(userDTO))) .andExpect(status().isBadRequest()); assertThat(userRepository.findOneByEmailIgnoreCase("invalid email")).isNotPresent(); @@ -542,10 +520,8 @@ void testSaveExistingEmail() throws Exception { userDTO.setLangKey(Constants.DEFAULT_LANGUAGE); userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN)); - restAccountMockMvc.perform( - post("/api/account") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(userDTO))) + restAccountMockMvc + .perform(post("/api/account").contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(userDTO))) .andExpect(status().isBadRequest()); User updatedUser = userRepository.findOneByLogin("save-existing-email").orElse(null); @@ -574,10 +550,8 @@ void testSaveExistingEmailAndLogin() throws Exception { userDTO.setLangKey(Constants.DEFAULT_LANGUAGE); userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN)); - restAccountMockMvc.perform( - post("/api/account") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(userDTO))) + restAccountMockMvc + .perform(post("/api/account").contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(userDTO))) .andExpect(status().isOk()); User updatedUser = userRepository.findOneByLogin("save-existing-email-and-login").orElse(null); @@ -595,10 +569,12 @@ void testChangePasswordWrongExistingPassword() throws Exception { user.setEmail("change-password-wrong-existing-password@example.com"); userRepository.saveAndFlush(user); - restAccountMockMvc.perform(post("/api/account/change-password") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO("1"+currentPassword, "new password"))) -) + restAccountMockMvc + .perform( + post("/api/account/change-password") + .contentType(MediaType.APPLICATION_JSON) + .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO("1" + currentPassword, "new password"))) + ) .andExpect(status().isBadRequest()); User updatedUser = userRepository.findOneByLogin("change-password-wrong-existing-password").orElse(null); @@ -617,10 +593,12 @@ void testChangePassword() throws Exception { user.setEmail("change-password@example.com"); userRepository.saveAndFlush(user); - restAccountMockMvc.perform(post("/api/account/change-password") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, "new password"))) -) + restAccountMockMvc + .perform( + post("/api/account/change-password") + .contentType(MediaType.APPLICATION_JSON) + .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, "new password"))) + ) .andExpect(status().isOk()); User updatedUser = userRepository.findOneByLogin("change-password").orElse(null); @@ -640,10 +618,12 @@ void testChangePasswordTooSmall() throws Exception { String newPassword = RandomStringUtils.random(ManagedUserVM.PASSWORD_MIN_LENGTH - 1); - restAccountMockMvc.perform(post("/api/account/change-password") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, newPassword))) -) + restAccountMockMvc + .perform( + post("/api/account/change-password") + .contentType(MediaType.APPLICATION_JSON) + .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, newPassword))) + ) .andExpect(status().isBadRequest()); User updatedUser = userRepository.findOneByLogin("change-password-too-small").orElse(null); @@ -663,10 +643,12 @@ void testChangePasswordTooLong() throws Exception { String newPassword = RandomStringUtils.random(ManagedUserVM.PASSWORD_MAX_LENGTH + 1); - restAccountMockMvc.perform(post("/api/account/change-password") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, newPassword))) -) + restAccountMockMvc + .perform( + post("/api/account/change-password") + .contentType(MediaType.APPLICATION_JSON) + .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, newPassword))) + ) .andExpect(status().isBadRequest()); User updatedUser = userRepository.findOneByLogin("change-password-too-long").orElse(null); @@ -684,10 +666,12 @@ void testChangePasswordEmpty() throws Exception { user.setEmail("change-password-empty@example.com"); userRepository.saveAndFlush(user); - restAccountMockMvc.perform(post("/api/account/change-password") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, ""))) -) + restAccountMockMvc + .perform( + post("/api/account/change-password") + .contentType(MediaType.APPLICATION_JSON) + .content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, ""))) + ) .andExpect(status().isBadRequest()); User updatedUser = userRepository.findOneByLogin("change-password-empty").orElse(null); @@ -704,9 +688,8 @@ void testRequestPasswordReset() throws Exception { user.setEmail("password-reset@example.com"); userRepository.saveAndFlush(user); - restAccountMockMvc.perform(post("/api/account/reset-password/init") - .content("password-reset@example.com") -) + restAccountMockMvc + .perform(post("/api/account/reset-password/init").content("password-reset@example.com")) .andExpect(status().isOk()); } @@ -720,17 +703,15 @@ void testRequestPasswordResetUpperCaseEmail() throws Exception { user.setEmail("password-reset@example.com"); userRepository.saveAndFlush(user); - restAccountMockMvc.perform(post("/api/account/reset-password/init") - .content("password-reset@EXAMPLE.COM") -) + restAccountMockMvc + .perform(post("/api/account/reset-password/init").content("password-reset@EXAMPLE.COM")) .andExpect(status().isOk()); } @Test void testRequestPasswordResetWrongEmail() throws Exception { - restAccountMockMvc.perform( - post("/api/account/reset-password/init") - .content("password-reset-wrong-email@example.com")) + restAccountMockMvc + .perform(post("/api/account/reset-password/init").content("password-reset-wrong-email@example.com")) .andExpect(status().isOk()); } @@ -749,10 +730,12 @@ void testFinishPasswordReset() throws Exception { keyAndPassword.setKey(user.getResetKey()); keyAndPassword.setNewPassword("new password"); - restAccountMockMvc.perform( - post("/api/account/reset-password/finish") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(keyAndPassword))) + restAccountMockMvc + .perform( + post("/api/account/reset-password/finish") + .contentType(MediaType.APPLICATION_JSON) + .content(TestUtil.convertObjectToJsonBytes(keyAndPassword)) + ) .andExpect(status().isOk()); User updatedUser = userRepository.findOneByLogin(user.getLogin()).orElse(null); @@ -774,10 +757,12 @@ void testFinishPasswordResetTooSmall() throws Exception { keyAndPassword.setKey(user.getResetKey()); keyAndPassword.setNewPassword("foo"); - restAccountMockMvc.perform( - post("/api/account/reset-password/finish") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(keyAndPassword))) + restAccountMockMvc + .perform( + post("/api/account/reset-password/finish") + .contentType(MediaType.APPLICATION_JSON) + .content(TestUtil.convertObjectToJsonBytes(keyAndPassword)) + ) .andExpect(status().isBadRequest()); User updatedUser = userRepository.findOneByLogin(user.getLogin()).orElse(null); @@ -791,10 +776,12 @@ void testFinishPasswordResetWrongKey() throws Exception { keyAndPassword.setKey("wrong reset key"); keyAndPassword.setNewPassword("new password"); - restAccountMockMvc.perform( - post("/api/account/reset-password/finish") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(keyAndPassword))) + restAccountMockMvc + .perform( + post("/api/account/reset-password/finish") + .contentType(MediaType.APPLICATION_JSON) + .content(TestUtil.convertObjectToJsonBytes(keyAndPassword)) + ) .andExpect(status().isInternalServerError()); } } diff --git a/src/test/java/io/github/jhipster/online/web/rest/AuditResourceIT.java b/src/test/java/io/github/jhipster/online/web/rest/AuditResourceIT.java index 400fce5c..5622728e 100644 --- a/src/test/java/io/github/jhipster/online/web/rest/AuditResourceIT.java +++ b/src/test/java/io/github/jhipster/online/web/rest/AuditResourceIT.java @@ -18,10 +18,16 @@ */ package io.github.jhipster.online.web.rest; +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.hamcrest.Matchers.hasItem; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + import io.github.jhipster.online.JhonlineApp; import io.github.jhipster.online.domain.PersistentAuditEvent; import io.github.jhipster.online.repository.PersistenceAuditEventRepository; import io.github.jhipster.online.security.AuthoritiesConstants; +import java.time.Instant; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -32,13 +38,6 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.transaction.annotation.Transactional; -import java.time.Instant; - -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; -import static org.hamcrest.Matchers.hasItem; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; - /** * Integration tests for the {@link AuditResource} REST controller. */ @@ -76,7 +75,8 @@ void getAllAudits() throws Exception { auditEventRepository.save(auditEvent); // Get all the audits - restAuditMockMvc.perform(get("/management/audits")) + restAuditMockMvc + .perform(get("/management/audits")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(jsonPath("$.[*].principal").value(hasItem(SAMPLE_PRINCIPAL))); @@ -88,7 +88,8 @@ void getAudit() throws Exception { auditEventRepository.save(auditEvent); // Get the audit - restAuditMockMvc.perform(get("/management/audits/{id}", auditEvent.getId())) + restAuditMockMvc + .perform(get("/management/audits/{id}", auditEvent.getId())) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(jsonPath("$.principal").value(SAMPLE_PRINCIPAL)); @@ -104,7 +105,8 @@ void getAuditsByDate() throws Exception { String toDate = SAMPLE_TIMESTAMP.plusSeconds(SECONDS_PER_DAY).toString().substring(0, 10); // Get the audit - restAuditMockMvc.perform(get("/management/audits?fromDate="+fromDate+"&toDate="+toDate)) + restAuditMockMvc + .perform(get("/management/audits?fromDate=" + fromDate + "&toDate=" + toDate)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(jsonPath("$.[*].principal").value(hasItem(SAMPLE_PRINCIPAL))); @@ -116,11 +118,12 @@ void getNonExistingAuditsByDate() throws Exception { auditEventRepository.save(auditEvent); // Generate dates for selecting audits by date, making sure the period will not contain the sample audit - String fromDate = SAMPLE_TIMESTAMP.minusSeconds(2*SECONDS_PER_DAY).toString().substring(0, 10); + String fromDate = SAMPLE_TIMESTAMP.minusSeconds(2 * SECONDS_PER_DAY).toString().substring(0, 10); String toDate = SAMPLE_TIMESTAMP.minusSeconds(SECONDS_PER_DAY).toString().substring(0, 10); // Query audits but expect no results - restAuditMockMvc.perform(get("/management/audits?fromDate=" + fromDate + "&toDate=" + toDate)) + restAuditMockMvc + .perform(get("/management/audits?fromDate=" + fromDate + "&toDate=" + toDate)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(header().string("X-Total-Count", "0")); @@ -129,8 +132,7 @@ void getNonExistingAuditsByDate() throws Exception { @Test void getNonExistingAudit() throws Exception { // Get the audit - restAuditMockMvc.perform(get("/management/audits/{id}", Long.MAX_VALUE)) - .andExpect(status().isNotFound()); + restAuditMockMvc.perform(get("/management/audits/{id}", Long.MAX_VALUE)).andExpect(status().isNotFound()); } @Test diff --git a/src/test/java/io/github/jhipster/online/web/rest/ClientForwardControllerTest.java b/src/test/java/io/github/jhipster/online/web/rest/ClientForwardControllerTest.java index a94fc6b2..1f775e16 100644 --- a/src/test/java/io/github/jhipster/online/web/rest/ClientForwardControllerTest.java +++ b/src/test/java/io/github/jhipster/online/web/rest/ClientForwardControllerTest.java @@ -1,5 +1,8 @@ package io.github.jhipster.online.web.rest; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.http.MediaType; @@ -9,9 +12,6 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; - /** * Unit tests for the {@link ClientForwardController} REST controller. */ @@ -22,14 +22,13 @@ class ClientForwardControllerTest { @BeforeEach public void setup() { ClientForwardController clientForwardController = new ClientForwardController(); - this.restMockMvc = MockMvcBuilders - .standaloneSetup(clientForwardController, new TestController()) - .build(); + this.restMockMvc = MockMvcBuilders.standaloneSetup(clientForwardController, new TestController()).build(); } @Test void getBackendEndpoint() throws Exception { - restMockMvc.perform(get("/test")) + restMockMvc + .perform(get("/test")) .andExpect(status().isOk()) .andExpect(content().contentTypeCompatibleWith(MediaType.TEXT_PLAIN_VALUE)) .andExpect(content().string("test")); @@ -38,19 +37,14 @@ void getBackendEndpoint() throws Exception { @Test void getClientEndpoint() throws Exception { ResultActions perform = restMockMvc.perform(get("/non-existant-mapping")); - perform - .andExpect(status().isOk()) - .andExpect(forwardedUrl("/")); + perform.andExpect(status().isOk()).andExpect(forwardedUrl("/")); } @Test void getNestedClientEndpoint() throws Exception { - restMockMvc.perform(get("/admin/user-management")) - .andExpect(status().isOk()) - .andExpect(forwardedUrl("/")); + restMockMvc.perform(get("/admin/user-management")).andExpect(status().isOk()).andExpect(forwardedUrl("/")); } - @RestController static class TestController { diff --git a/src/test/java/io/github/jhipster/online/web/rest/EntityStatsResourceIntTest.java b/src/test/java/io/github/jhipster/online/web/rest/EntityStatsResourceIntTest.java index c7055b37..e9b9fb34 100644 --- a/src/test/java/io/github/jhipster/online/web/rest/EntityStatsResourceIntTest.java +++ b/src/test/java/io/github/jhipster/online/web/rest/EntityStatsResourceIntTest.java @@ -1,5 +1,11 @@ package io.github.jhipster.online.web.rest; +import static io.github.jhipster.online.web.rest.TestUtil.createFormattingConversionService; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.Matchers.hasItem; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + import io.github.jhipster.online.JhonlineApp; import io.github.jhipster.online.domain.EntityStats; import io.github.jhipster.online.repository.EntityStatsRepository; @@ -7,6 +13,10 @@ import io.github.jhipster.online.service.dto.EntityStatsDTO; import io.github.jhipster.online.service.mapper.EntityStatsMapper; import io.github.jhipster.online.web.rest.errors.ExceptionTranslator; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.List; +import javax.persistence.EntityManager; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -21,17 +31,6 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.transaction.annotation.Transactional; -import javax.persistence.EntityManager; -import java.time.Instant; -import java.time.temporal.ChronoUnit; -import java.util.List; - -import static io.github.jhipster.online.web.rest.TestUtil.createFormattingConversionService; -import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.Matchers.hasItem; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; - /** * Test class for the EntityStatsResource REST controller. * @@ -106,11 +105,14 @@ class EntityStatsResourceIntTest { public void setup() { MockitoAnnotations.initMocks(this); final EntityStatsResource entityStatsResource = new EntityStatsResource(entityStatsService); - this.restEntityStatsMockMvc = MockMvcBuilders.standaloneSetup(entityStatsResource) - .setCustomArgumentResolvers(pageableArgumentResolver) - .setControllerAdvice(exceptionTranslator) - .setConversionService(createFormattingConversionService()) - .setMessageConverters(jacksonMessageConverter).build(); + this.restEntityStatsMockMvc = + MockMvcBuilders + .standaloneSetup(entityStatsResource) + .setCustomArgumentResolvers(pageableArgumentResolver) + .setControllerAdvice(exceptionTranslator) + .setConversionService(createFormattingConversionService()) + .setMessageConverters(jacksonMessageConverter) + .build(); } /** @@ -146,9 +148,10 @@ void createEntityStats() throws Exception { int databaseSizeBeforeCreate = entityStatsRepository.findAll().size(); // Create the EntityStats - restEntityStatsMockMvc.perform(post("/api/entity-stats") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(entityStats))) + restEntityStatsMockMvc + .perform( + post("/api/entity-stats").contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(entityStats)) + ) .andExpect(status().isCreated()); // Validate the EntityStats in the database @@ -178,9 +181,10 @@ void createEntityStatsWithExistingId() throws Exception { entityStats.setId(1L); // An entity with an existing ID cannot be created, so this API call must fail - restEntityStatsMockMvc.perform(post("/api/entity-stats") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(entityStats))) + restEntityStatsMockMvc + .perform( + post("/api/entity-stats").contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(entityStats)) + ) .andExpect(status().isBadRequest()); // Validate the EntityStats in the database @@ -195,7 +199,8 @@ void getAllEntityStats() throws Exception { entityStatsRepository.saveAndFlush(entityStats); // Get all the entityStatsList - restEntityStatsMockMvc.perform(get("/api/entity-stats?sort=id,desc")) + restEntityStatsMockMvc + .perform(get("/api/entity-stats?sort=id,desc")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.[*].id").value(hasItem(entityStats.getId().intValue()))) @@ -220,7 +225,8 @@ void getEntityStats() throws Exception { entityStatsRepository.saveAndFlush(entityStats); // Get the entityStats - restEntityStatsMockMvc.perform(get("/api/entity-stats/{id}", entityStats.getId())) + restEntityStatsMockMvc + .perform(get("/api/entity-stats/{id}", entityStats.getId())) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.id").value(entityStats.getId().intValue())) @@ -242,8 +248,7 @@ void getEntityStats() throws Exception { @Transactional void getNonExistingEntityStats() throws Exception { // Get the entityStats - restEntityStatsMockMvc.perform(get("/api/entity-stats/{id}", Long.MAX_VALUE)) - .andExpect(status().isNotFound()); + restEntityStatsMockMvc.perform(get("/api/entity-stats/{id}", Long.MAX_VALUE)).andExpect(status().isNotFound()); } @Test @@ -272,9 +277,12 @@ void updateEntityStats() throws Exception { .fluentMethods(UPDATED_FLUENT_METHODS) .date(UPDATED_DATE); - restEntityStatsMockMvc.perform(put("/api/entity-stats") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(updatedEntityStats))) + restEntityStatsMockMvc + .perform( + put("/api/entity-stats") + .contentType(MediaType.APPLICATION_JSON) + .content(TestUtil.convertObjectToJsonBytes(updatedEntityStats)) + ) .andExpect(status().isOk()); // Validate the EntityStats in the database @@ -303,9 +311,10 @@ void updateNonExistingEntityStats() throws Exception { // Create the EntityStats // If the entity doesn't have an ID, it will be created instead of just being updated - restEntityStatsMockMvc.perform(put("/api/entity-stats") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(entityStats))) + restEntityStatsMockMvc + .perform( + put("/api/entity-stats").contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(entityStats)) + ) .andExpect(status().isBadRequest()); // Validate the EntityStats in the database @@ -322,8 +331,8 @@ void deleteEntityStats() throws Exception { int databaseSizeBeforeDelete = entityStatsRepository.findAll().size(); // Get the entityStats - restEntityStatsMockMvc.perform(delete("/api/entity-stats/{id}", entityStatsDTO.getId()) - .accept(MediaType.APPLICATION_JSON)) + restEntityStatsMockMvc + .perform(delete("/api/entity-stats/{id}", entityStatsDTO.getId()).accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); // Validate the database is empty diff --git a/src/test/java/io/github/jhipster/online/web/rest/GeneratorIdentityResourceIntTest.java b/src/test/java/io/github/jhipster/online/web/rest/GeneratorIdentityResourceIntTest.java index eb44e18a..d15db611 100644 --- a/src/test/java/io/github/jhipster/online/web/rest/GeneratorIdentityResourceIntTest.java +++ b/src/test/java/io/github/jhipster/online/web/rest/GeneratorIdentityResourceIntTest.java @@ -1,5 +1,11 @@ package io.github.jhipster.online.web.rest; +import static io.github.jhipster.online.web.rest.TestUtil.createFormattingConversionService; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.Matchers.hasItem; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + import io.github.jhipster.online.JhonlineApp; import io.github.jhipster.online.domain.GeneratorIdentity; import io.github.jhipster.online.repository.GeneratorIdentityRepository; @@ -8,6 +14,8 @@ import io.github.jhipster.online.service.dto.GeneratorIdentityDTO; import io.github.jhipster.online.service.mapper.GeneratorIdentityMapper; import io.github.jhipster.online.web.rest.errors.ExceptionTranslator; +import java.util.List; +import javax.persistence.EntityManager; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -22,15 +30,6 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.transaction.annotation.Transactional; -import javax.persistence.EntityManager; -import java.util.List; - -import static io.github.jhipster.online.web.rest.TestUtil.createFormattingConversionService; -import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.Matchers.hasItem; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; - /** * Test class for the GeneratorIdentityResource REST controller. * @@ -78,11 +77,14 @@ class GeneratorIdentityResourceIntTest { public void setup() { MockitoAnnotations.initMocks(this); final GeneratorIdentityResource generatorIdentityResource = new GeneratorIdentityResource(generatorIdentityService, userService); - this.restGeneratorIdentityMockMvc = MockMvcBuilders.standaloneSetup(generatorIdentityResource) - .setCustomArgumentResolvers(pageableArgumentResolver) - .setControllerAdvice(exceptionTranslator) - .setConversionService(createFormattingConversionService()) - .setMessageConverters(jacksonMessageConverter).build(); + this.restGeneratorIdentityMockMvc = + MockMvcBuilders + .standaloneSetup(generatorIdentityResource) + .setCustomArgumentResolvers(pageableArgumentResolver) + .setControllerAdvice(exceptionTranslator) + .setConversionService(createFormattingConversionService()) + .setMessageConverters(jacksonMessageConverter) + .build(); } /** @@ -92,9 +94,7 @@ public void setup() { * if they test an entity which requires the current entity. */ public static GeneratorIdentity createEntity(EntityManager em) { - return new GeneratorIdentity() - .host(DEFAULT_HOST) - .guid(DEFAULT_GUID); + return new GeneratorIdentity().host(DEFAULT_HOST).guid(DEFAULT_GUID); } @BeforeEach @@ -108,9 +108,12 @@ void createGeneratorIdentity() throws Exception { int databaseSizeBeforeCreate = generatorIdentityRepository.findAll().size(); // Create the GeneratorIdentity - restGeneratorIdentityMockMvc.perform(post("/api/generator-identities") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(generatorIdentity))) + restGeneratorIdentityMockMvc + .perform( + post("/api/generator-identities") + .contentType(MediaType.APPLICATION_JSON) + .content(TestUtil.convertObjectToJsonBytes(generatorIdentity)) + ) .andExpect(status().isCreated()); // Validate the GeneratorIdentity in the database @@ -130,9 +133,12 @@ void createGeneratorIdentityWithExistingId() throws Exception { generatorIdentity.setId(1L); // An entity with an existing ID cannot be created, so this API call must fail - restGeneratorIdentityMockMvc.perform(post("/api/generator-identities") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(generatorIdentity))) + restGeneratorIdentityMockMvc + .perform( + post("/api/generator-identities") + .contentType(MediaType.APPLICATION_JSON) + .content(TestUtil.convertObjectToJsonBytes(generatorIdentity)) + ) .andExpect(status().isBadRequest()); // Validate the GeneratorIdentity in the database @@ -147,7 +153,8 @@ void getAllGeneratorIdentities() throws Exception { generatorIdentityRepository.saveAndFlush(generatorIdentity); // Get all the generatorIdentityList - restGeneratorIdentityMockMvc.perform(get("/api/generator-identities?sort=id,desc")) + restGeneratorIdentityMockMvc + .perform(get("/api/generator-identities?sort=id,desc")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.[*].id").value(hasItem(generatorIdentity.getId().intValue()))) @@ -155,7 +162,6 @@ void getAllGeneratorIdentities() throws Exception { .andExpect(jsonPath("$.[*].guid").value(hasItem(DEFAULT_GUID))); } - @Test @Transactional void getGeneratorIdentity() throws Exception { @@ -163,19 +169,20 @@ void getGeneratorIdentity() throws Exception { generatorIdentityRepository.saveAndFlush(generatorIdentity); // Get the generatorIdentity - restGeneratorIdentityMockMvc.perform(get("/api/generator-identities/{id}", generatorIdentity.getId())) + restGeneratorIdentityMockMvc + .perform(get("/api/generator-identities/{id}", generatorIdentity.getId())) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.id").value(generatorIdentity.getId().intValue())) .andExpect(jsonPath("$.host").value(DEFAULT_HOST)) .andExpect(jsonPath("$.guid").value(DEFAULT_GUID)); } + @Test @Transactional void getNonExistingGeneratorIdentity() throws Exception { // Get the generatorIdentity - restGeneratorIdentityMockMvc.perform(get("/api/generator-identities/{id}", Long.MAX_VALUE)) - .andExpect(status().isNotFound()); + restGeneratorIdentityMockMvc.perform(get("/api/generator-identities/{id}", Long.MAX_VALUE)).andExpect(status().isNotFound()); } @Test @@ -190,13 +197,14 @@ void updateGeneratorIdentity() throws Exception { GeneratorIdentity updatedGeneratorIdentity = generatorIdentityRepository.findById(generatorIdentityDTO.getId()).get(); // Disconnect from session so that the updates on updatedGeneratorIdentity are not directly saved in db em.detach(updatedGeneratorIdentity); - updatedGeneratorIdentity - .host(UPDATED_HOST) - .guid(UPDATED_GUID); - - restGeneratorIdentityMockMvc.perform(put("/api/generator-identities") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(updatedGeneratorIdentity))) + updatedGeneratorIdentity.host(UPDATED_HOST).guid(UPDATED_GUID); + + restGeneratorIdentityMockMvc + .perform( + put("/api/generator-identities") + .contentType(MediaType.APPLICATION_JSON) + .content(TestUtil.convertObjectToJsonBytes(updatedGeneratorIdentity)) + ) .andExpect(status().isOk()); // Validate the GeneratorIdentity in the database @@ -215,9 +223,12 @@ void updateNonExistingGeneratorIdentity() throws Exception { // Create the GeneratorIdentity // If the entity doesn't have an ID, it will be created instead of just being updated - restGeneratorIdentityMockMvc.perform(put("/api/generator-identities") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(generatorIdentity))) + restGeneratorIdentityMockMvc + .perform( + put("/api/generator-identities") + .contentType(MediaType.APPLICATION_JSON) + .content(TestUtil.convertObjectToJsonBytes(generatorIdentity)) + ) .andExpect(status().isBadRequest()); // Validate the GeneratorIdentity in the database @@ -234,8 +245,8 @@ void deleteGeneratorIdentity() throws Exception { int databaseSizeBeforeDelete = generatorIdentityRepository.findAll().size(); // Get the generatorIdentity - restGeneratorIdentityMockMvc.perform(delete("/api/generator-identities/{id}", generatorIdentityDTO.getId()) - .accept(MediaType.APPLICATION_JSON)) + restGeneratorIdentityMockMvc + .perform(delete("/api/generator-identities/{id}", generatorIdentityDTO.getId()).accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); // Validate the database is empty diff --git a/src/test/java/io/github/jhipster/online/web/rest/GitResourceIntTest.java b/src/test/java/io/github/jhipster/online/web/rest/GitResourceIntTest.java index 05e6ae3f..02575d6f 100644 --- a/src/test/java/io/github/jhipster/online/web/rest/GitResourceIntTest.java +++ b/src/test/java/io/github/jhipster/online/web/rest/GitResourceIntTest.java @@ -18,6 +18,12 @@ */ package io.github.jhipster.online.web.rest; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + import io.github.jhipster.online.JhonlineApp; import io.github.jhipster.online.config.ApplicationProperties; import io.github.jhipster.online.service.GithubService; @@ -38,12 +44,6 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import static org.mockito.Mockito.when; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - /** * Test class for the GitResource REST controller. * @@ -79,10 +79,12 @@ public void setup() { GitResource gitResource = new GitResource(mockApplicationProperties, mockUserService, mockGithubService, mockGitlabService); - this.restMvc = MockMvcBuilders.standaloneSetup(gitResource) - .setMessageConverters(httpMessageConverters) - .setControllerAdvice(exceptionTranslator) - .build(); + this.restMvc = + MockMvcBuilders + .standaloneSetup(gitResource) + .setMessageConverters(httpMessageConverters) + .setControllerAdvice(exceptionTranslator) + .build(); } @Test @@ -96,9 +98,8 @@ void testGetGitConfiguration() throws Exception { when(mockGitlabService.getRedirectUri()).thenReturn("http//localhost:9000/api/callback/github"); when(mockGitlabService.isEnabled()).thenReturn(true); - restMvc.perform( - get("/api/git/config", "TestProvider") - .accept(MediaType.APPLICATION_JSON)) + restMvc + .perform(get("/api/git/config", "TestProvider").accept(MediaType.APPLICATION_JSON)) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); } @@ -106,19 +107,16 @@ void testGetGitConfiguration() throws Exception { @Test void testSaveTokenWithUnknownGitProvider() throws Exception { final String code = "ret66spihj6sio4bud2"; - restMvc.perform( - post("/api/{gitProvider}/save-token", "TestProvider") - .contentType(MediaType.APPLICATION_JSON) - .content(code)) + restMvc + .perform(post("/api/{gitProvider}/save-token", "TestProvider").contentType(MediaType.APPLICATION_JSON).content(code)) .andExpect(status().isInternalServerError()); } @Test void testRefreshGithubWithUnknownProvider() throws Exception { final String unavailableGitProvider = "TestProvider"; - restMvc.perform( - post("/api/{gitProvider}/refresh", "TestProvider") - .contentType(MediaType.APPLICATION_JSON)) + restMvc + .perform(post("/api/{gitProvider}/refresh", "TestProvider").contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isInternalServerError()) .andExpect(content().string("Unknown git provider: " + unavailableGitProvider)); } diff --git a/src/test/java/io/github/jhipster/online/web/rest/StatisticsResourceIntTest.java b/src/test/java/io/github/jhipster/online/web/rest/StatisticsResourceIntTest.java index e8684f66..9574c8b4 100644 --- a/src/test/java/io/github/jhipster/online/web/rest/StatisticsResourceIntTest.java +++ b/src/test/java/io/github/jhipster/online/web/rest/StatisticsResourceIntTest.java @@ -1,5 +1,10 @@ package io.github.jhipster.online.web.rest; +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + import io.github.jhipster.online.JhonlineApp; import io.github.jhipster.online.domain.GeneratorIdentity; import io.github.jhipster.online.domain.YoRC; @@ -19,11 +24,6 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.transaction.annotation.Transactional; -import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - @ExtendWith(SpringExtension.class) @SpringBootTest(classes = JhonlineApp.class) class StatisticsResourceIntTest { @@ -67,7 +67,8 @@ class StatisticsResourceIntTest { private String generatorId = "cf51ff78-187a-4554-9b09-8f6f95f1a7a5"; - private String dummyYo = "{\n" + + private String dummyYo = + "{\n" + " \"generator-jhipster\": {\n" + " \"useYarn\": false,\n" + " \"experimental\": false,\n" + @@ -97,7 +98,9 @@ class StatisticsResourceIntTest { " ],\n" + " \"applicationType\": \"monolith\"\n" + " },\n" + - " \"generator-id\": \"" + generatorId + "\",\n" + + " \"generator-id\": \"" + + generatorId + + "\",\n" + " \"generator-version\": \"5.1.0\",\n" + " \"git-provider\": \"local\",\n" + " \"node-version\": \"v8.11.1\",\n" + @@ -120,20 +123,21 @@ public void setup() { subGenEventService, userService, generatorIdentityService, - entityStatService); - - this.restStatiticsMockMvc = MockMvcBuilders.standaloneSetup(statisticsResource) - .setMessageConverters(httpMessageConverters) - .setControllerAdvice(exceptionTranslator) - .build(); + entityStatService + ); + + this.restStatiticsMockMvc = + MockMvcBuilders + .standaloneSetup(statisticsResource) + .setMessageConverters(httpMessageConverters) + .setControllerAdvice(exceptionTranslator) + .build(); } @Test @Transactional void shouldNotGetCountWithUnknownFrequency() throws Exception { - restStatiticsMockMvc - .perform(get("/api/s/count-yo/{frequency}", "every minutes")) - .andExpect(status().isBadRequest()); + restStatiticsMockMvc.perform(get("/api/s/count-yo/{frequency}", "every minutes")).andExpect(status().isBadRequest()); } @Test @@ -149,9 +153,7 @@ void shouldNotGetFieldCountWithUnknownFieldOrFrequency() throws Exception { void getYoCount() throws Exception { int databaseSizeBeforeAdd = yoRCRepository.findAll().size(); - restStatiticsMockMvc - .perform(get("/api/s/count-yo")) - .andExpect(status().isOk()); + restStatiticsMockMvc.perform(get("/api/s/count-yo")).andExpect(status().isOk()); YoRC yorc = new YoRC().owner(new GeneratorIdentity()); generatorIdentityRepository.saveAndFlush(yorc.getOwner()); @@ -167,9 +169,7 @@ void getYoCount() throws Exception { void addEntry() throws Exception { int databaseSizeBeforeAdd = yoRCRepository.findAll().size(); - restStatiticsMockMvc.perform(post("/api/s/entry") - .content(dummyYo)) - .andExpect(status().isCreated()); + restStatiticsMockMvc.perform(post("/api/s/entry").content(dummyYo)).andExpect(status().isCreated()); int databaseSizeAfterAdd = yoRCRepository.findAll().size(); diff --git a/src/test/java/io/github/jhipster/online/web/rest/SubGenEventResourceIntTest.java b/src/test/java/io/github/jhipster/online/web/rest/SubGenEventResourceIntTest.java index 4e582819..1c077987 100644 --- a/src/test/java/io/github/jhipster/online/web/rest/SubGenEventResourceIntTest.java +++ b/src/test/java/io/github/jhipster/online/web/rest/SubGenEventResourceIntTest.java @@ -1,5 +1,11 @@ package io.github.jhipster.online.web.rest; +import static io.github.jhipster.online.web.rest.TestUtil.createFormattingConversionService; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.Matchers.hasItem; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + import io.github.jhipster.online.JhonlineApp; import io.github.jhipster.online.domain.SubGenEvent; import io.github.jhipster.online.repository.SubGenEventRepository; @@ -7,6 +13,10 @@ import io.github.jhipster.online.service.dto.SubGenEventDTO; import io.github.jhipster.online.service.mapper.SubGenEventMapper; import io.github.jhipster.online.web.rest.errors.ExceptionTranslator; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.List; +import javax.persistence.EntityManager; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -21,17 +31,6 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.transaction.annotation.Transactional; -import javax.persistence.EntityManager; -import java.time.Instant; -import java.time.temporal.ChronoUnit; -import java.util.List; - -import static io.github.jhipster.online.web.rest.TestUtil.createFormattingConversionService; -import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.Matchers.hasItem; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; - /** * Test class for the SubGenEventResource REST controller. * @@ -97,11 +96,14 @@ class SubGenEventResourceIntTest { public void setup() { MockitoAnnotations.initMocks(this); final SubGenEventResource subGenEventResource = new SubGenEventResource(subGenEventService); - this.restSubGenEventMockMvc = MockMvcBuilders.standaloneSetup(subGenEventResource) - .setCustomArgumentResolvers(pageableArgumentResolver) - .setControllerAdvice(exceptionTranslator) - .setConversionService(createFormattingConversionService()) - .setMessageConverters(jacksonMessageConverter).build(); + this.restSubGenEventMockMvc = + MockMvcBuilders + .standaloneSetup(subGenEventResource) + .setCustomArgumentResolvers(pageableArgumentResolver) + .setControllerAdvice(exceptionTranslator) + .setConversionService(createFormattingConversionService()) + .setMessageConverters(jacksonMessageConverter) + .build(); } /** @@ -134,9 +136,10 @@ void createSubGenEvent() throws Exception { int databaseSizeBeforeCreate = subGenEventRepository.findAll().size(); // Create the SubGenEvent - restSubGenEventMockMvc.perform(post("/api/sub-gen-events") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(subGenEvent))) + restSubGenEventMockMvc + .perform( + post("/api/sub-gen-events").contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(subGenEvent)) + ) .andExpect(status().isCreated()); // Validate the SubGenEvent in the database @@ -163,9 +166,10 @@ void createSubGenEventWithExistingId() throws Exception { subGenEvent.setId(1L); // An entity with an existing ID cannot be created, so this API call must fail - restSubGenEventMockMvc.perform(post("/api/sub-gen-events") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(subGenEvent))) + restSubGenEventMockMvc + .perform( + post("/api/sub-gen-events").contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(subGenEvent)) + ) .andExpect(status().isBadRequest()); // Validate the SubGenEvent in the database @@ -180,7 +184,8 @@ void getAllSubGenEvents() throws Exception { subGenEventRepository.saveAndFlush(subGenEvent); // Get all the subGenEventList - restSubGenEventMockMvc.perform(get("/api/sub-gen-events?sort=id,desc")) + restSubGenEventMockMvc + .perform(get("/api/sub-gen-events?sort=id,desc")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.[*].id").value(hasItem(subGenEvent.getId().intValue()))) @@ -195,7 +200,6 @@ void getAllSubGenEvents() throws Exception { .andExpect(jsonPath("$.[*].date").value(hasItem(DEFAULT_DATE.toString()))); } - @Test @Transactional void getSubGenEvent() throws Exception { @@ -203,7 +207,8 @@ void getSubGenEvent() throws Exception { subGenEventRepository.saveAndFlush(subGenEvent); // Get the subGenEvent - restSubGenEventMockMvc.perform(get("/api/sub-gen-events/{id}", subGenEvent.getId())) + restSubGenEventMockMvc + .perform(get("/api/sub-gen-events/{id}", subGenEvent.getId())) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.id").value(subGenEvent.getId().intValue())) @@ -217,12 +222,12 @@ void getSubGenEvent() throws Exception { .andExpect(jsonPath("$.event").value(DEFAULT_EVENT)) .andExpect(jsonPath("$.date").value(DEFAULT_DATE.toString())); } + @Test @Transactional void getNonExistingSubGenEvent() throws Exception { // Get the subGenEvent - restSubGenEventMockMvc.perform(get("/api/sub-gen-events/{id}", Long.MAX_VALUE)) - .andExpect(status().isNotFound()); + restSubGenEventMockMvc.perform(get("/api/sub-gen-events/{id}", Long.MAX_VALUE)).andExpect(status().isNotFound()); } @Test @@ -248,9 +253,12 @@ void updateSubGenEvent() throws Exception { .event(UPDATED_EVENT) .date(UPDATED_DATE); - restSubGenEventMockMvc.perform(put("/api/sub-gen-events") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(updatedSubGenEvent))) + restSubGenEventMockMvc + .perform( + put("/api/sub-gen-events") + .contentType(MediaType.APPLICATION_JSON) + .content(TestUtil.convertObjectToJsonBytes(updatedSubGenEvent)) + ) .andExpect(status().isOk()); // Validate the SubGenEvent in the database @@ -276,9 +284,10 @@ void updateNonExistingSubGenEvent() throws Exception { // Create the SubGenEvent // If the entity doesn't have an ID, it will be created instead of just being updated - restSubGenEventMockMvc.perform(put("/api/sub-gen-events") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(subGenEvent))) + restSubGenEventMockMvc + .perform( + put("/api/sub-gen-events").contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(subGenEvent)) + ) .andExpect(status().isBadRequest()); // Validate the SubGenEvent in the database @@ -295,8 +304,8 @@ void deleteSubGenEvent() throws Exception { int databaseSizeBeforeDelete = subGenEventRepository.findAll().size(); // Get the subGenEvent - restSubGenEventMockMvc.perform(delete("/api/sub-gen-events/{id}", subGenEventDTO.getId()) - .accept(MediaType.APPLICATION_JSON)) + restSubGenEventMockMvc + .perform(delete("/api/sub-gen-events/{id}", subGenEventDTO.getId()).accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); // Validate the database is empty diff --git a/src/test/java/io/github/jhipster/online/web/rest/TestUtil.java b/src/test/java/io/github/jhipster/online/web/rest/TestUtil.java index 44686e85..d8375576 100644 --- a/src/test/java/io/github/jhipster/online/web/rest/TestUtil.java +++ b/src/test/java/io/github/jhipster/online/web/rest/TestUtil.java @@ -18,27 +18,26 @@ */ package io.github.jhipster.online.web.rest; +import static org.assertj.core.api.Assertions.assertThat; + import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; -import org.hamcrest.Description; -import org.hamcrest.TypeSafeDiagnosingMatcher; -import org.springframework.format.datetime.standard.DateTimeFormatterRegistrar; -import org.springframework.format.support.DefaultFormattingConversionService; -import org.springframework.format.support.FormattingConversionService; - +import java.io.IOException; +import java.time.ZonedDateTime; +import java.time.format.DateTimeParseException; +import java.util.List; import javax.persistence.EntityManager; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; -import java.io.IOException; -import java.time.ZonedDateTime; -import java.time.format.DateTimeParseException; -import java.util.List; - -import static org.assertj.core.api.Assertions.assertThat; +import org.hamcrest.Description; +import org.hamcrest.TypeSafeDiagnosingMatcher; +import org.springframework.format.datetime.standard.DateTimeFormatterRegistrar; +import org.springframework.format.support.DefaultFormattingConversionService; +import org.springframework.format.support.FormattingConversionService; /** * Utility class for testing REST controllers. @@ -101,11 +100,9 @@ protected boolean matchesSafely(String item, Description mismatchDescription) { } return true; } catch (DateTimeParseException e) { - mismatchDescription.appendText("was ").appendValue(item) - .appendText(", which could not be parsed as a ZonedDateTime"); + mismatchDescription.appendText("was ").appendValue(item).appendText(", which could not be parsed as a ZonedDateTime"); return false; } - } @Override @@ -147,7 +144,7 @@ public static void equalsVerifier(Class clazz) throws Exception { * @return the {@link FormattingConversionService}. */ public static FormattingConversionService createFormattingConversionService() { - DefaultFormattingConversionService dfcs = new DefaultFormattingConversionService (); + DefaultFormattingConversionService dfcs = new DefaultFormattingConversionService(); DateTimeFormatterRegistrar registrar = new DateTimeFormatterRegistrar(); registrar.setUseIsoFormat(true); registrar.registerFormatters(dfcs); diff --git a/src/test/java/io/github/jhipster/online/web/rest/UserJWTControllerIT.java b/src/test/java/io/github/jhipster/online/web/rest/UserJWTControllerIT.java index a720566b..b40a7b4c 100644 --- a/src/test/java/io/github/jhipster/online/web/rest/UserJWTControllerIT.java +++ b/src/test/java/io/github/jhipster/online/web/rest/UserJWTControllerIT.java @@ -18,6 +18,10 @@ */ package io.github.jhipster.online.web.rest; +import static org.hamcrest.Matchers.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + import io.github.jhipster.online.JhonlineApp; import io.github.jhipster.online.domain.User; import io.github.jhipster.online.repository.UserRepository; @@ -31,10 +35,6 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.transaction.annotation.Transactional; -import static org.hamcrest.Matchers.*; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; - /** * Integration tests for the {@link UserJWTController} REST controller. */ @@ -65,9 +65,8 @@ void testAuthorize() throws Exception { LoginVM login = new LoginVM(); login.setUsername("user-jwt-controller"); login.setPassword("test"); - mockMvc.perform(post("/api/authenticate") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(login))) + mockMvc + .perform(post("/api/authenticate").contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(login))) .andExpect(status().isOk()) .andExpect(jsonPath("$.id_token").isString()) .andExpect(jsonPath("$.id_token").isNotEmpty()) @@ -90,9 +89,8 @@ void testAuthorizeWithRememberMe() throws Exception { login.setUsername("user-jwt-controller-remember-me"); login.setPassword("test"); login.setRememberMe(true); - mockMvc.perform(post("/api/authenticate") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(login))) + mockMvc + .perform(post("/api/authenticate").contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(login))) .andExpect(status().isOk()) .andExpect(jsonPath("$.id_token").isString()) .andExpect(jsonPath("$.id_token").isNotEmpty()) @@ -105,9 +103,8 @@ void testAuthorizeFails() throws Exception { LoginVM login = new LoginVM(); login.setUsername("wrong-user"); login.setPassword("wrong password"); - mockMvc.perform(post("/api/authenticate") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(login))) + mockMvc + .perform(post("/api/authenticate").contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(login))) .andExpect(status().isUnauthorized()) .andExpect(jsonPath("$.id_token").doesNotExist()) .andExpect(header().doesNotExist("Authorization")); diff --git a/src/test/java/io/github/jhipster/online/web/rest/UserResourceIT.java b/src/test/java/io/github/jhipster/online/web/rest/UserResourceIT.java index b9ff71e0..dcc3d7a1 100644 --- a/src/test/java/io/github/jhipster/online/web/rest/UserResourceIT.java +++ b/src/test/java/io/github/jhipster/online/web/rest/UserResourceIT.java @@ -18,6 +18,12 @@ */ package io.github.jhipster.online.web.rest; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.hasItems; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + import io.github.jhipster.online.JhonlineApp; import io.github.jhipster.online.domain.Authority; import io.github.jhipster.online.domain.User; @@ -26,6 +32,13 @@ import io.github.jhipster.online.service.dto.UserDTO; import io.github.jhipster.online.service.mapper.UserMapper; import io.github.jhipster.online.web.rest.vm.ManagedUserVM; +import java.time.Instant; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.function.Consumer; +import javax.persistence.EntityManager; import org.apache.commons.lang3.RandomStringUtils; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -38,20 +51,6 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.transaction.annotation.Transactional; -import javax.persistence.EntityManager; -import java.time.Instant; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.function.Consumer; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.Matchers.hasItem; -import static org.hamcrest.Matchers.hasItems; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; - /** * Integration tests for the {@link UserResource} REST controller. */ @@ -149,22 +148,23 @@ void createUser() throws Exception { managedUserVM.setLangKey(DEFAULT_LANGKEY); managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); - restUserMockMvc.perform(post("/api/users") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) + restUserMockMvc + .perform(post("/api/users").contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(managedUserVM))) .andExpect(status().isCreated()); // Validate the User in the database - assertPersistedUsers(users -> { - assertThat(users).hasSize(databaseSizeBeforeCreate + 1); - User testUser = users.get(users.size() - 1); - assertThat(testUser.getLogin()).isEqualTo(DEFAULT_LOGIN); - assertThat(testUser.getFirstName()).isEqualTo(DEFAULT_FIRSTNAME); - assertThat(testUser.getLastName()).isEqualTo(DEFAULT_LASTNAME); - assertThat(testUser.getEmail()).isEqualTo(DEFAULT_EMAIL); - assertThat(testUser.getImageUrl()).isEqualTo(DEFAULT_IMAGEURL); - assertThat(testUser.getLangKey()).isEqualTo(DEFAULT_LANGKEY); - }); + assertPersistedUsers( + users -> { + assertThat(users).hasSize(databaseSizeBeforeCreate + 1); + User testUser = users.get(users.size() - 1); + assertThat(testUser.getLogin()).isEqualTo(DEFAULT_LOGIN); + assertThat(testUser.getFirstName()).isEqualTo(DEFAULT_FIRSTNAME); + assertThat(testUser.getLastName()).isEqualTo(DEFAULT_LASTNAME); + assertThat(testUser.getEmail()).isEqualTo(DEFAULT_EMAIL); + assertThat(testUser.getImageUrl()).isEqualTo(DEFAULT_IMAGEURL); + assertThat(testUser.getLangKey()).isEqualTo(DEFAULT_LANGKEY); + } + ); } @Test @@ -185,9 +185,8 @@ void createUserWithExistingId() throws Exception { managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); // An entity with an existing ID cannot be created, so this API call must fail - restUserMockMvc.perform(post("/api/users") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) + restUserMockMvc + .perform(post("/api/users").contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(managedUserVM))) .andExpect(status().isBadRequest()); // Validate the User in the database @@ -202,7 +201,7 @@ void createUserWithExistingLogin() throws Exception { int databaseSizeBeforeCreate = userRepository.findAll().size(); ManagedUserVM managedUserVM = new ManagedUserVM(); - managedUserVM.setLogin(DEFAULT_LOGIN);// this login should already be used + managedUserVM.setLogin(DEFAULT_LOGIN); // this login should already be used managedUserVM.setPassword(DEFAULT_PASSWORD); managedUserVM.setFirstName(DEFAULT_FIRSTNAME); managedUserVM.setLastName(DEFAULT_LASTNAME); @@ -213,9 +212,8 @@ void createUserWithExistingLogin() throws Exception { managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); // Create the User - restUserMockMvc.perform(post("/api/users") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) + restUserMockMvc + .perform(post("/api/users").contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(managedUserVM))) .andExpect(status().isBadRequest()); // Validate the User in the database @@ -234,16 +232,15 @@ void createUserWithExistingEmail() throws Exception { managedUserVM.setPassword(DEFAULT_PASSWORD); managedUserVM.setFirstName(DEFAULT_FIRSTNAME); managedUserVM.setLastName(DEFAULT_LASTNAME); - managedUserVM.setEmail(DEFAULT_EMAIL);// this email should already be used + managedUserVM.setEmail(DEFAULT_EMAIL); // this email should already be used managedUserVM.setActivated(true); managedUserVM.setImageUrl(DEFAULT_IMAGEURL); managedUserVM.setLangKey(DEFAULT_LANGKEY); managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); // Create the User - restUserMockMvc.perform(post("/api/users") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) + restUserMockMvc + .perform(post("/api/users").contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(managedUserVM))) .andExpect(status().isBadRequest()); // Validate the User in the database @@ -254,9 +251,7 @@ void createUserWithExistingEmail() throws Exception { @Transactional @WithMockUser(authorities = AuthoritiesConstants.USER) void getAllUsersShouldBeForbiddenWithUser() throws Exception { - restUserMockMvc.perform(get("/api/users?sort=id,desc") - .accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isForbidden()); + restUserMockMvc.perform(get("/api/users?sort=id,desc").accept(MediaType.APPLICATION_JSON)).andExpect(status().isForbidden()); } @Test @@ -266,8 +261,8 @@ void getAllUsers() throws Exception { userRepository.saveAndFlush(user); // Get all the users - restUserMockMvc.perform(get("/api/users?sort=id,desc") - .accept(MediaType.APPLICATION_JSON)) + restUserMockMvc + .perform(get("/api/users?sort=id,desc").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(jsonPath("$.[*].login").value(hasItem(DEFAULT_LOGIN))) @@ -287,7 +282,8 @@ void getUser() throws Exception { assertThat(cacheManager.getCache(UserRepository.USERS_BY_LOGIN_CACHE).get(user.getLogin())).isNull(); // Get the user - restUserMockMvc.perform(get("/api/users/{login}", user.getLogin())) + restUserMockMvc + .perform(get("/api/users/{login}", user.getLogin())) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(jsonPath("$.login").value(user.getLogin())) @@ -303,8 +299,7 @@ void getUser() throws Exception { @Test @Transactional void getNonExistingUser() throws Exception { - restUserMockMvc.perform(get("/api/users/unknown")) - .andExpect(status().isNotFound()); + restUserMockMvc.perform(get("/api/users/unknown")).andExpect(status().isNotFound()); } @Test @@ -333,21 +328,22 @@ void updateUser() throws Exception { managedUserVM.setLastModifiedDate(updatedUser.getLastModifiedDate()); managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); - restUserMockMvc.perform(put("/api/users") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) + restUserMockMvc + .perform(put("/api/users").contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(managedUserVM))) .andExpect(status().isOk()); // Validate the User in the database - assertPersistedUsers(users -> { - assertThat(users).hasSize(databaseSizeBeforeUpdate); - User testUser = users.get(users.size() - 1); - assertThat(testUser.getFirstName()).isEqualTo(UPDATED_FIRSTNAME); - assertThat(testUser.getLastName()).isEqualTo(UPDATED_LASTNAME); - assertThat(testUser.getEmail()).isEqualTo(UPDATED_EMAIL); - assertThat(testUser.getImageUrl()).isEqualTo(UPDATED_IMAGEURL); - assertThat(testUser.getLangKey()).isEqualTo(UPDATED_LANGKEY); - }); + assertPersistedUsers( + users -> { + assertThat(users).hasSize(databaseSizeBeforeUpdate); + User testUser = users.get(users.size() - 1); + assertThat(testUser.getFirstName()).isEqualTo(UPDATED_FIRSTNAME); + assertThat(testUser.getLastName()).isEqualTo(UPDATED_LASTNAME); + assertThat(testUser.getEmail()).isEqualTo(UPDATED_EMAIL); + assertThat(testUser.getImageUrl()).isEqualTo(UPDATED_IMAGEURL); + assertThat(testUser.getLangKey()).isEqualTo(UPDATED_LANGKEY); + } + ); } @Test @@ -376,22 +372,23 @@ void updateUserLogin() throws Exception { managedUserVM.setLastModifiedDate(updatedUser.getLastModifiedDate()); managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); - restUserMockMvc.perform(put("/api/users") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) + restUserMockMvc + .perform(put("/api/users").contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(managedUserVM))) .andExpect(status().isOk()); // Validate the User in the database - assertPersistedUsers(users -> { - assertThat(users).hasSize(databaseSizeBeforeUpdate); - User testUser = users.get(users.size() - 1); - assertThat(testUser.getLogin()).isEqualTo(UPDATED_LOGIN); - assertThat(testUser.getFirstName()).isEqualTo(UPDATED_FIRSTNAME); - assertThat(testUser.getLastName()).isEqualTo(UPDATED_LASTNAME); - assertThat(testUser.getEmail()).isEqualTo(UPDATED_EMAIL); - assertThat(testUser.getImageUrl()).isEqualTo(UPDATED_IMAGEURL); - assertThat(testUser.getLangKey()).isEqualTo(UPDATED_LANGKEY); - }); + assertPersistedUsers( + users -> { + assertThat(users).hasSize(databaseSizeBeforeUpdate); + User testUser = users.get(users.size() - 1); + assertThat(testUser.getLogin()).isEqualTo(UPDATED_LOGIN); + assertThat(testUser.getFirstName()).isEqualTo(UPDATED_FIRSTNAME); + assertThat(testUser.getLastName()).isEqualTo(UPDATED_LASTNAME); + assertThat(testUser.getEmail()).isEqualTo(UPDATED_EMAIL); + assertThat(testUser.getImageUrl()).isEqualTo(UPDATED_IMAGEURL); + assertThat(testUser.getLangKey()).isEqualTo(UPDATED_LANGKEY); + } + ); } @Test @@ -420,7 +417,7 @@ void updateUserExistingEmail() throws Exception { managedUserVM.setPassword(updatedUser.getPassword()); managedUserVM.setFirstName(updatedUser.getFirstName()); managedUserVM.setLastName(updatedUser.getLastName()); - managedUserVM.setEmail("jhipster@localhost");// this email should already be used by anotherUser + managedUserVM.setEmail("jhipster@localhost"); // this email should already be used by anotherUser managedUserVM.setActivated(updatedUser.getActivated()); managedUserVM.setImageUrl(updatedUser.getImageUrl()); managedUserVM.setLangKey(updatedUser.getLangKey()); @@ -430,9 +427,8 @@ void updateUserExistingEmail() throws Exception { managedUserVM.setLastModifiedDate(updatedUser.getLastModifiedDate()); managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); - restUserMockMvc.perform(put("/api/users") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) + restUserMockMvc + .perform(put("/api/users").contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(managedUserVM))) .andExpect(status().isBadRequest()); } @@ -458,7 +454,7 @@ void updateUserExistingLogin() throws Exception { ManagedUserVM managedUserVM = new ManagedUserVM(); managedUserVM.setId(updatedUser.getId()); - managedUserVM.setLogin("jhipster");// this login should already be used by anotherUser + managedUserVM.setLogin("jhipster"); // this login should already be used by anotherUser managedUserVM.setPassword(updatedUser.getPassword()); managedUserVM.setFirstName(updatedUser.getFirstName()); managedUserVM.setLastName(updatedUser.getLastName()); @@ -472,9 +468,8 @@ void updateUserExistingLogin() throws Exception { managedUserVM.setLastModifiedDate(updatedUser.getLastModifiedDate()); managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); - restUserMockMvc.perform(put("/api/users") - .contentType(MediaType.APPLICATION_JSON) - .content(TestUtil.convertObjectToJsonBytes(managedUserVM))) + restUserMockMvc + .perform(put("/api/users").contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(managedUserVM))) .andExpect(status().isBadRequest()); } @@ -486,8 +481,8 @@ void deleteUser() throws Exception { int databaseSizeBeforeDelete = userRepository.findAll().size(); // Delete the user - restUserMockMvc.perform(delete("/api/users/{login}", user.getLogin()) - .accept(MediaType.APPLICATION_JSON)) + restUserMockMvc + .perform(delete("/api/users/{login}", user.getLogin()).accept(MediaType.APPLICATION_JSON)) .andExpect(status().isNoContent()); assertThat(cacheManager.getCache(UserRepository.USERS_BY_LOGIN_CACHE).get(user.getLogin())).isNull(); @@ -499,9 +494,8 @@ void deleteUser() throws Exception { @Test @Transactional void getAllAuthorities() throws Exception { - restUserMockMvc.perform(get("/api/users/authorities") - .accept(MediaType.APPLICATION_JSON) - .contentType(MediaType.APPLICATION_JSON)) + restUserMockMvc + .perform(get("/api/users/authorities").accept(MediaType.APPLICATION_JSON).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(jsonPath("$").isArray()) diff --git a/src/test/java/io/github/jhipster/online/web/rest/WithUnauthenticatedMockUser.java b/src/test/java/io/github/jhipster/online/web/rest/WithUnauthenticatedMockUser.java index 36940514..09ad12d0 100644 --- a/src/test/java/io/github/jhipster/online/web/rest/WithUnauthenticatedMockUser.java +++ b/src/test/java/io/github/jhipster/online/web/rest/WithUnauthenticatedMockUser.java @@ -1,21 +1,20 @@ package io.github.jhipster.online.web.rest; -import org.springframework.security.core.context.SecurityContext; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.test.context.support.WithSecurityContext; -import org.springframework.security.test.context.support.WithSecurityContextFactory; - import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.test.context.support.WithSecurityContext; +import org.springframework.security.test.context.support.WithSecurityContextFactory; -@Target({ElementType.METHOD, ElementType.TYPE}) +@Target({ ElementType.METHOD, ElementType.TYPE }) @Retention(RetentionPolicy.RUNTIME) @WithSecurityContext(factory = WithUnauthenticatedMockUser.Factory.class) public @interface WithUnauthenticatedMockUser { - class Factory implements WithSecurityContextFactory { + @Override public SecurityContext createSecurityContext(WithUnauthenticatedMockUser annotation) { return SecurityContextHolder.createEmptyContext(); diff --git a/src/test/java/io/github/jhipster/online/web/rest/YoRCResourceIntTest.java b/src/test/java/io/github/jhipster/online/web/rest/YoRCResourceIntTest.java index b5270d22..38dcabb3 100644 --- a/src/test/java/io/github/jhipster/online/web/rest/YoRCResourceIntTest.java +++ b/src/test/java/io/github/jhipster/online/web/rest/YoRCResourceIntTest.java @@ -1,5 +1,12 @@ package io.github.jhipster.online.web.rest; +import static io.github.jhipster.online.web.rest.TestUtil.createFormattingConversionService; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.Matchers.hasItem; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + import io.github.jhipster.online.JhonlineApp; import io.github.jhipster.online.domain.YoRC; import io.github.jhipster.online.repository.YoRCRepository; @@ -7,6 +14,8 @@ import io.github.jhipster.online.service.dto.YoRCDTO; import io.github.jhipster.online.service.mapper.YoRCMapper; import io.github.jhipster.online.web.rest.errors.ExceptionTranslator; +import java.time.Instant; +import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -21,16 +30,6 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.transaction.annotation.Transactional; -import java.time.Instant; -import java.util.List; - -import static io.github.jhipster.online.web.rest.TestUtil.createFormattingConversionService; -import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.Matchers.hasItem; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; - /** * Test class for the YoRCResource REST controller. * @@ -142,11 +141,14 @@ class YoRCResourceIntTest { public void setup() { MockitoAnnotations.initMocks(this); final YoRCResource yoRCResource = new YoRCResource(yoRCService); - this.restYoRCMockMvc = MockMvcBuilders.standaloneSetup(yoRCResource) - .setCustomArgumentResolvers(pageableArgumentResolver) - .setControllerAdvice(exceptionTranslator) - .setConversionService(createFormattingConversionService()) - .setMessageConverters(jacksonMessageConverter).build(); + this.restYoRCMockMvc = + MockMvcBuilders + .standaloneSetup(yoRCResource) + .setCustomArgumentResolvers(pageableArgumentResolver) + .setControllerAdvice(exceptionTranslator) + .setConversionService(createFormattingConversionService()) + .setMessageConverters(jacksonMessageConverter) + .build(); } /** @@ -209,7 +211,8 @@ void getAllYoRCS() throws Exception { yoRCRepository.saveAndFlush(yoRC); // Get all the yoRCList - restYoRCMockMvc.perform(get("/api/yo-rcs?sort=id,desc")) + restYoRCMockMvc + .perform(get("/api/yo-rcs?sort=id,desc")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.[*].id").value(hasItem(yoRC.getId().intValue()))) @@ -253,7 +256,6 @@ void getAllYoRCS() throws Exception { .andExpect(jsonPath("$.[*].hasCucumber").value(hasItem(DEFAULT_HAS_CUCUMBER))); } - @Test @Transactional void getYoRC() throws Exception { @@ -261,7 +263,8 @@ void getYoRC() throws Exception { yoRCRepository.saveAndFlush(yoRC); // Get the yoRC - restYoRCMockMvc.perform(get("/api/yo-rcs/{id}", yoRC.getId())) + restYoRCMockMvc + .perform(get("/api/yo-rcs/{id}", yoRC.getId())) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.id").value(yoRC.getId().intValue())) @@ -304,12 +307,12 @@ void getYoRC() throws Exception { .andExpect(jsonPath("$.hasGatling").value(DEFAULT_HAS_GATLING)) .andExpect(jsonPath("$.hasCucumber").value(DEFAULT_HAS_CUCUMBER)); } + @Test @Transactional void getNonExistingYoRC() throws Exception { // Get the yoRC - restYoRCMockMvc.perform(get("/api/yo-rcs/{id}", Long.MAX_VALUE)) - .andExpect(status().isNotFound()); + restYoRCMockMvc.perform(get("/api/yo-rcs/{id}", Long.MAX_VALUE)).andExpect(status().isNotFound()); } @Test @@ -321,9 +324,7 @@ void deleteYoRC() throws Exception { int databaseSizeBeforeDelete = yoRCRepository.findAll().size(); // Get the yoRC - restYoRCMockMvc.perform(delete("/api/yo-rcs/{id}", yoRCDTO.getId()) - .accept(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()); + restYoRCMockMvc.perform(delete("/api/yo-rcs/{id}", yoRCDTO.getId()).accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()); // Validate the database is empty List yoRCList = yoRCRepository.findAll(); diff --git a/src/test/java/io/github/jhipster/online/web/rest/errors/ExceptionTranslatorIT.java b/src/test/java/io/github/jhipster/online/web/rest/errors/ExceptionTranslatorIT.java index 7ae372f6..e2f463dc 100644 --- a/src/test/java/io/github/jhipster/online/web/rest/errors/ExceptionTranslatorIT.java +++ b/src/test/java/io/github/jhipster/online/web/rest/errors/ExceptionTranslatorIT.java @@ -18,6 +18,10 @@ */ package io.github.jhipster.online.web.rest.errors; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + import io.github.jhipster.online.JhonlineApp; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -27,10 +31,6 @@ import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.servlet.MockMvc; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; - /** * Integration tests {@link ExceptionTranslator} controller advice. */ @@ -44,7 +44,8 @@ class ExceptionTranslatorIT { @Test void testConcurrencyFailure() throws Exception { - mockMvc.perform(get("/api/exception-translator-test/concurrency-failure")) + mockMvc + .perform(get("/api/exception-translator-test/concurrency-failure")) .andExpect(status().isConflict()) .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) .andExpect(jsonPath("$.message").value(ErrorConstants.ERR_CONCURRENCY_FAILURE)); @@ -52,18 +53,20 @@ void testConcurrencyFailure() throws Exception { @Test void testMethodArgumentNotValid() throws Exception { - mockMvc.perform(post("/api/exception-translator-test/method-argument").content("{}").contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isBadRequest()) - .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) - .andExpect(jsonPath("$.message").value(ErrorConstants.ERR_VALIDATION)) - .andExpect(jsonPath("$.fieldErrors.[0].objectName").value("test")) - .andExpect(jsonPath("$.fieldErrors.[0].field").value("test")) - .andExpect(jsonPath("$.fieldErrors.[0].message").value("NotNull")); + mockMvc + .perform(post("/api/exception-translator-test/method-argument").content("{}").contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isBadRequest()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.message").value(ErrorConstants.ERR_VALIDATION)) + .andExpect(jsonPath("$.fieldErrors.[0].objectName").value("test")) + .andExpect(jsonPath("$.fieldErrors.[0].field").value("test")) + .andExpect(jsonPath("$.fieldErrors.[0].message").value("NotNull")); } @Test void testMissingServletRequestPartException() throws Exception { - mockMvc.perform(get("/api/exception-translator-test/missing-servlet-request-part")) + mockMvc + .perform(get("/api/exception-translator-test/missing-servlet-request-part")) .andExpect(status().isBadRequest()) .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) .andExpect(jsonPath("$.message").value("error.http.400")); @@ -71,7 +74,8 @@ void testMissingServletRequestPartException() throws Exception { @Test void testMissingServletRequestParameterException() throws Exception { - mockMvc.perform(get("/api/exception-translator-test/missing-servlet-request-parameter")) + mockMvc + .perform(get("/api/exception-translator-test/missing-servlet-request-parameter")) .andExpect(status().isBadRequest()) .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) .andExpect(jsonPath("$.message").value("error.http.400")); @@ -79,7 +83,8 @@ void testMissingServletRequestParameterException() throws Exception { @Test void testAccessDenied() throws Exception { - mockMvc.perform(get("/api/exception-translator-test/access-denied")) + mockMvc + .perform(get("/api/exception-translator-test/access-denied")) .andExpect(status().isForbidden()) .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) .andExpect(jsonPath("$.message").value("error.http.403")) @@ -88,7 +93,8 @@ void testAccessDenied() throws Exception { @Test void testUnauthorized() throws Exception { - mockMvc.perform(get("/api/exception-translator-test/unauthorized")) + mockMvc + .perform(get("/api/exception-translator-test/unauthorized")) .andExpect(status().isUnauthorized()) .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) .andExpect(jsonPath("$.message").value("error.http.401")) @@ -98,7 +104,8 @@ void testUnauthorized() throws Exception { @Test void testMethodNotSupported() throws Exception { - mockMvc.perform(post("/api/exception-translator-test/access-denied")) + mockMvc + .perform(post("/api/exception-translator-test/access-denied")) .andExpect(status().isMethodNotAllowed()) .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) .andExpect(jsonPath("$.message").value("error.http.405")) @@ -107,7 +114,8 @@ void testMethodNotSupported() throws Exception { @Test void testExceptionWithResponseStatus() throws Exception { - mockMvc.perform(get("/api/exception-translator-test/response-status")) + mockMvc + .perform(get("/api/exception-translator-test/response-status")) .andExpect(status().isBadRequest()) .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) .andExpect(jsonPath("$.message").value("error.http.400")) @@ -116,7 +124,8 @@ void testExceptionWithResponseStatus() throws Exception { @Test void testInternalServerError() throws Exception { - mockMvc.perform(get("/api/exception-translator-test/internal-server-error")) + mockMvc + .perform(get("/api/exception-translator-test/internal-server-error")) .andExpect(status().isInternalServerError()) .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) .andExpect(jsonPath("$.message").value("error.http.500")) diff --git a/src/test/java/io/github/jhipster/online/web/rest/errors/ExceptionTranslatorTestController.java b/src/test/java/io/github/jhipster/online/web/rest/errors/ExceptionTranslatorTestController.java index 6a0ba892..a6baddba 100644 --- a/src/test/java/io/github/jhipster/online/web/rest/errors/ExceptionTranslatorTestController.java +++ b/src/test/java/io/github/jhipster/online/web/rest/errors/ExceptionTranslatorTestController.java @@ -18,15 +18,14 @@ */ package io.github.jhipster.online.web.rest.errors; +import javax.validation.Valid; +import javax.validation.constraints.NotNull; import org.springframework.dao.ConcurrencyFailureException; import org.springframework.http.HttpStatus; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.web.bind.annotation.*; -import javax.validation.Valid; -import javax.validation.constraints.NotNull; - @RestController @RequestMapping("/api/exception-translator-test") public class ExceptionTranslatorTestController { @@ -37,16 +36,13 @@ public void concurrencyFailure() { } @PostMapping("/method-argument") - public void methodArgument(@Valid @RequestBody TestDTO testDTO) { - } + public void methodArgument(@Valid @RequestBody TestDTO testDTO) {} @GetMapping("/missing-servlet-request-part") - public void missingServletRequestPartException(@RequestPart String part) { - } + public void missingServletRequestPartException(@RequestPart String part) {} @GetMapping("/missing-servlet-request-parameter") - public void missingServletRequestParameterException(@RequestParam String param) { - } + public void missingServletRequestParameterException(@RequestParam String param) {} @GetMapping("/access-denied") public void accessdenied() { @@ -84,7 +80,5 @@ public void setTest(String test) { @ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "test response status") @SuppressWarnings("serial") - public static class TestResponseStatusException extends RuntimeException { - } - + public static class TestResponseStatusException extends RuntimeException {} } diff --git a/src/test/javascript/jest.conf.js b/src/test/javascript/jest.conf.js index 91d9d5f8..7a0c4664 100644 --- a/src/test/javascript/jest.conf.js +++ b/src/test/javascript/jest.conf.js @@ -1,58 +1,53 @@ const tsconfig = require('../../../tsconfig.json'); module.exports = { - preset: 'jest-preset-angular', - setupFiles: ['jest-date-mock'], - setupFilesAfterEnv: ['/src/test/javascript/jest.ts'], - cacheDirectory: '/target/jest-cache', - coverageDirectory: '/target/test-results/', - globals: { - 'ts-jest': { - stringifyContentPathRegex: '\\.html$', - tsConfig: '/tsconfig.json', - astTransformers: ['jest-preset-angular/build/InlineFilesTransformer', 'jest-preset-angular/build/StripStylesTransformer'] - } - }, - coveragePathIgnorePatterns: [ - '/src/test/javascript' - ], - moduleNameMapper: mapTypescriptAliasToJestAlias(), - reporters: [ - 'default', - [ 'jest-junit', { outputDirectory: './target/test-results/', outputName: 'TESTS-results-jest.xml' } ] - ], - testResultsProcessor: 'jest-sonar-reporter', - transformIgnorePatterns: ['node_modules/'], - testMatch: ['/src/test/javascript/spec/**/@(*.)@(spec.ts)'], - rootDir: '../../../', - testURL: 'http://localhost/' + preset: 'jest-preset-angular', + setupFiles: ['jest-date-mock'], + setupFilesAfterEnv: ['/src/test/javascript/jest.ts'], + cacheDirectory: '/target/jest-cache', + coverageDirectory: '/target/test-results/', + globals: { + 'ts-jest': { + stringifyContentPathRegex: '\\.html$', + tsConfig: '/tsconfig.json', + astTransformers: ['jest-preset-angular/build/InlineFilesTransformer', 'jest-preset-angular/build/StripStylesTransformer'] + } + }, + coveragePathIgnorePatterns: ['/src/test/javascript'], + moduleNameMapper: mapTypescriptAliasToJestAlias(), + reporters: ['default', ['jest-junit', { outputDirectory: './target/test-results/', outputName: 'TESTS-results-jest.xml' }]], + testResultsProcessor: 'jest-sonar-reporter', + transformIgnorePatterns: ['node_modules/'], + testMatch: ['/src/test/javascript/spec/**/@(*.)@(spec.ts)'], + rootDir: '../../../', + testURL: 'http://localhost/' }; function mapTypescriptAliasToJestAlias(alias = {}) { - const jestAliases = { ...alias }; - if (!tsconfig.compilerOptions.paths) { - return jestAliases; - } - Object.entries(tsconfig.compilerOptions.paths) - .filter(([key, value]) => { - // use Typescript alias in Jest only if this has value - if (value.length) { - return true; - } - return false; - }) - .map(([key, value]) => { - // if Typescript alias ends with /* then in Jest: - // - alias key must end with /(.*) - // - alias value must end with /$1 - const regexToReplace = /(.*)\/\*$/; - const aliasKey = key.replace(regexToReplace, '$1/(.*)'); - const aliasValue = value[0].replace(regexToReplace, '$1/$$1'); - return [aliasKey, `/${aliasValue}`]; - }) - .reduce((aliases, [key, value]) => { - aliases[key] = value; - return aliases; - }, jestAliases); + const jestAliases = { ...alias }; + if (!tsconfig.compilerOptions.paths) { return jestAliases; + } + Object.entries(tsconfig.compilerOptions.paths) + .filter(([key, value]) => { + // use Typescript alias in Jest only if this has value + if (value.length) { + return true; + } + return false; + }) + .map(([key, value]) => { + // if Typescript alias ends with /* then in Jest: + // - alias key must end with /(.*) + // - alias value must end with /$1 + const regexToReplace = /(.*)\/\*$/; + const aliasKey = key.replace(regexToReplace, '$1/(.*)'); + const aliasValue = value[0].replace(regexToReplace, '$1/$$1'); + return [aliasKey, `/${aliasValue}`]; + }) + .reduce((aliases, [key, value]) => { + aliases[key] = value; + return aliases; + }, jestAliases); + return jestAliases; } diff --git a/src/test/resources/config/application.yml b/src/test/resources/config/application.yml index 6f87386c..0e1dd4c8 100644 --- a/src/test/resources/config/application.yml +++ b/src/test/resources/config/application.yml @@ -43,7 +43,7 @@ spring: hibernate.cache.use_query_cache: false hibernate.generate_statistics: false hibernate.hbm2ddl.auto: validate -# hibernate.jdbc.time_zone: UTC + # hibernate.jdbc.time_zone: UTC liquibase: contexts: test mail: diff --git a/tsconfig-aot.json b/tsconfig-aot.json index 16552d03..c53085cc 100644 --- a/tsconfig-aot.json +++ b/tsconfig-aot.json @@ -1,30 +1,28 @@ { - "compilerOptions": { - "target": "es5", - "module": "es2015", - "moduleResolution": "node", - "sourceMap": false, - "emitDecoratorMetadata": true, - "experimentalDecorators": true, - "removeComments": false, - "noImplicitAny": false, - "suppressImplicitAnyIndexErrors": true, - "skipLibCheck": true, - "outDir": "target/www/app", - "lib": ["es7", "dom"], - "typeRoots": [ - "node_modules/@types" - ], - "baseUrl": "./", - "paths": { - "app/*": ["src/main/webapp/app/*"] - }, - "importHelpers": true + "compilerOptions": { + "target": "es5", + "module": "es2015", + "moduleResolution": "node", + "sourceMap": false, + "emitDecoratorMetadata": true, + "experimentalDecorators": true, + "removeComments": false, + "noImplicitAny": false, + "suppressImplicitAnyIndexErrors": true, + "skipLibCheck": true, + "outDir": "target/www/app", + "lib": ["es7", "dom"], + "typeRoots": ["node_modules/@types"], + "baseUrl": "./", + "paths": { + "app/*": ["src/main/webapp/app/*"] }, - "angularCompilerOptions": { - "genDir": "target/aot", - "skipMetadataEmit" : true, - "fullTemplateTypeCheck": true, - "preserveWhitespaces": true - } + "importHelpers": true + }, + "angularCompilerOptions": { + "genDir": "target/aot", + "skipMetadataEmit": true, + "fullTemplateTypeCheck": true, + "preserveWhitespaces": true + } } diff --git a/yarn.lock b/yarn.lock index fb59f4b0..389f7103 100644 --- a/yarn.lock +++ b/yarn.lock @@ -6155,6 +6155,14 @@ jake@^10.6.1: filelist "^1.0.1" minimatch "^3.0.4" +java-parser@0.8.2: + version "0.8.2" + resolved "https://registry.yarnpkg.com/java-parser/-/java-parser-0.8.2.tgz#12a29a6ef8e9ca50d5d047e4c4c8ac383ff240d6" + integrity sha512-YphTEk4zIpWAHqBriAdjlNnTEcEYQ2xBA8KOH5V7QxggNbxjkeEcKJjNYnQvqEue8+O1TLj7vfL0NVG6x5LGMw== + dependencies: + chevrotain "6.5.0" + lodash "4.17.20" + java-parser@^0.8.0: version "0.8.0" resolved "https://registry.yarnpkg.com/java-parser/-/java-parser-0.8.0.tgz#5abee16e3fbc11d0d90c5b6ac69919e01fe1ba5c" @@ -7117,6 +7125,11 @@ lodash@4.17.15, lodash@^4, lodash@^4.17.10, lodash@^4.17.11, lodash@^4.17.12, lo resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.15.tgz#b447f6670a0455bbfeedd11392eff330ea097548" integrity sha512-8xOcRHvCjnocdS5cpwXQXVzmmh5e5+saE2QGoeQmbKmRS6J3VQppPOIt0MnmE+4xlZoumy0GPG0D0MVIQbNA1A== +lodash@4.17.20: + version "4.17.20" + resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.20.tgz#b44a9b6297bcb698f1c51a3545a2b3b368d59c52" + integrity sha512-PlhdFcillOINfeV7Ni6oF1TAEayyZBoZ8bcshTHqOYJYlrqzRK5hagpagky5o4HfCzzd1TRkXPMFq6cKk9rGmA== + log-symbols@^1.0.2: version "1.0.2" resolved "https://registry.yarnpkg.com/log-symbols/-/log-symbols-1.0.2.tgz#376ff7b58ea3086a0f09facc74617eca501e1a18" @@ -9159,6 +9172,15 @@ prettier-plugin-java@0.8.0: lodash "4.17.15" prettier "2.0.4" +prettier-plugin-java@0.8.3: + version "0.8.3" + resolved "https://registry.yarnpkg.com/prettier-plugin-java/-/prettier-plugin-java-0.8.3.tgz#a7d381c2945a2cdda4f7baa6ced2205cb6cceebb" + integrity sha512-LyFle106727RkY1NBGzHHnzEJKjILigSfHPPqalNi5yJ/DkM5hjOVxWa4374gm44LStMl1arNgzpCnYPL0F8cg== + dependencies: + java-parser "0.8.2" + lodash "4.17.20" + prettier "2.1.1" + prettier@1.19.1: version "1.19.1" resolved "https://registry.yarnpkg.com/prettier/-/prettier-1.19.1.tgz#f7d7f5ff8a9cd872a7be4ca142095956a60797cb" @@ -9174,6 +9196,11 @@ prettier@2.0.5: resolved "https://registry.yarnpkg.com/prettier/-/prettier-2.0.5.tgz#d6d56282455243f2f92cc1716692c08aa31522d4" integrity sha512-7PtVymN48hGcO4fGjybyBSIWDsLU4H4XlvOHfq91pz9kkGlonzwTfYkaIEwiRg/dAJF9YlbsduBAgtYLi+8cFg== +prettier@2.1.1: + version "2.1.1" + resolved "https://registry.yarnpkg.com/prettier/-/prettier-2.1.1.tgz#d9485dd5e499daa6cb547023b87a6cf51bee37d6" + integrity sha512-9bY+5ZWCfqj3ghYBLxApy2zf6m+NJo5GzmLTpr9FsApsfjriNnS2dahWReHMi7qNPhhHl9SYHJs2cHZLgexNIw== + pretty-bytes@^5.1.0, pretty-bytes@^5.2.0: version "5.3.0" resolved "https://registry.yarnpkg.com/pretty-bytes/-/pretty-bytes-5.3.0.tgz#f2849e27db79fb4d6cfe24764fc4134f165989f2"